// JavaScript Document
var showProductLoadingDiv = function() {
	//GabeUtil.screenDimLoading(true, "<center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Loading your Website Business Management page.<br />Please wait...</center>");	
	//top.document.getElementById('clientarealoadingdiv').innerHTML = "";
}

var hideProductLoadingDiv = function() {
	top.document.getElementById('clientarealoadingdiv').style.display = 'none';
}

var adminLoginSuccessCallback = function(option) {
	if(!option) {
		option = {};	
	}
	alert('!');
}

var Webzone = {};

Webzone.previewWindow = null;
Webzone.previewFront = null;
Webzone.previewAdmin = null;
Webzone.clientareaUser = null;
Webzone.reschedSession = null;
Webzone.submitSessionReportCallback = new Array();
Webzone.adminClockTmp = "<div class='timezonediv'><span class='timezonename'>{timezonename}</span><br /><span class=\"timezonetime {ts:'{ts}'}\"></span></div>";

Webzone.openControlWindow = function(url) {
	var win = window.open(url, 'webzonecontrolwindow', 'width=850,height=550,scrollbars=yes,location=no,toolbar=no,menubar=no,resizable=no');
	win.focus();
	return win;
}

Webzone.installWebPackageApp = function(pid, elem, option) {
	
	if(!option) {
		option = {};	
	}
	
	var command = $(elem).metadata().command;
	var appType = $(elem).metadata().appType;
	var app = $(elem).metadata().app;
	var username = $(elem).metadata().username;
	var ipaddress = $(elem).metadata().ipaddress;
	var hostingid = $(elem).metadata().hostingid;
	var server = $(elem).metadata().server;
	var domain = $(elem).metadata().domain;
	var apphomedir = '';
	
	if(document.getElementById('apphomedirfld')) {
		if($("#apphomedirfld").attr('checked') == true) {
			apphomedir = $("#apphomedirfld").val();
		}
	}
	
	var processReply = function(response) {
		if(response.status == 'OK') {
			//window.location = 'http://' + ipaddress + '/~' + username + '/wp-admin/?whmcsID=1';
			GabeUtil.screenDimLoading(true, "<div class='infopopup'><form method='post' action='clientarea.php?action=productdetails' target='_top'><input type='hidden' name='id' value='" + pid + "' />Your web package was successfully installed!<br /><input type='submit' name='submitnow' value='Click here to start building your website!' /></form></div>");
		} else {
			alert("An error occurred during the installation of your web package. ");
			GabeUtil.screenDimLoading(false);
		}
		
	}
	
	GabeUtil.screenDimLoading(true, "<div class='infopopup'><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />We are now installing your chosen web program.<br />This may take a moment.<br />Please wait.</div>");
	var url = 'http://www.websitelogin.org/vwzclientarea.php?action=addpackagecommand&command=' + command + '&app_type=' + appType + '&app=' + app + '&username=' + username + '&hostingid=' + hostingid + '&server=' + server + '&ipaddress=' + ipaddress + '&domain=' + domain + '&apphomedir=' + apphomedir;
	try {
		jQuery.get(url, {}, processReply, 'json')
	} catch(e) {
	}	
	
}

Webzone.registerScheduleEvent = function(selector, option) {
	if(!option) {
		option = {};	
	}
	//alert(selector);
	$(selector).click(function(event) {
		Webzone.processScheduleEvent(this, option);
	});
}

Webzone.processScheduleEvent = function(element, option) {
	
	if(!option) {
		option = {};	
	}
	
	var query = '';
	if(option.noschedule) {
		query += '&noschedule=' + option.noschedule;
	}
	if(option.parentid) {
		query += '&parentid=' + option.parentid;
		option.parent = $("#" + option.parentid);
	}
	
	var relid = $(element).metadata().relid;
	var title = encodeURIComponent($(element).metadata().title);
	var description = encodeURIComponent($(element).metadata().description);
	var nonwebid = $(element).metadata().nonwebid;
	var userid = $(element).metadata().userid;
	
	var url = '/vwz-files/webzone/client.php?scheduleevent=1&relid=' + relid + '&ts=' + Math.random() + '&title=' + title + '&description=' + description + '&nonwebid=' + nonwebid + '&userid=' + userid + query;
	//alert(url);
	
	var process = function(response) {
		
		if(option.parentid) {
			// GabeUtil.screenDimLoading(false);
			$(option.parent).html(response);
			$("#" + option.parentid + " .closewindow").hide();
		} else {
			GabeUtil.screenDimLoading(true, response);
		}
		
		if(document.getElementById('togglesummarygcal')) {
			$("#togglesummarygcal").click(function(event) {
				$(this).next().toggle();									   
			}).next().hide();
		}
		
		if(document.getElementById('fulldayfld')) {
			$("#fulldayfld").click(function(event) {
				if($("#fulldayfld").attr('checked') == true) {
					alert("Setting this option on will schedule this event for\nthe entire day(s) within your chosen date range.");
					$("#scheduleeventform span.timefield").hide();
				} else {
					$("#scheduleeventform span.timefield").show();
				}
			});
		}
		
		if(document.getElementById('setgoogleinfoform')) {
			var origval = $("#setgoogleinfoform input[type='submit']").val();
			$("#setgoogleinfoform").ajaxForm({
				dataType : 'json',
				beforeSubmit : function(odata, oform, opt) {
					$("#setgoogleinfoform input[type='submit']").val("Please wait...");
					$("#setgoogleinfoform input[type='submit']").attr('disabled', true);
				},
				success : function(response) {
					$("#setgoogleinfoform input[type='submit']").val(origval);
					$("#setgoogleinfoform input[type='submit']").attr('disabled', false);
					alert(response.message);
					Webzone.processScheduleEvent(element, option);
				}
			});
		}
		
		if(document.getElementById("scheduleeventform")) {
			var origval = $("#scheduleeventform input[type='submit']").val();
			/* I set datepicker css to z-index:100 so that datepicker will appear */
			$("#scheduleeventform .datepickerfld").datepicker({
				dateFormat : 'yy-mm-dd'
			});
			
			$("#scheduleeventform input[name='startdate']").change(function(event) {
				$("#scheduleeventform input[name='enddate']").val($("#scheduleeventform input[name='startdate']").val());
			});
			
			$("#scheduleeventform").ajaxForm({
				beforeSubmit : function(oform, odata, opt) {
					$("input[type='submit']").val('Please wait...').attr('disabled', true);
				},
				success : function(response) {
					$("input[type='submit']").val(origval).attr('disabled', false);
					alert(response.message);
					jQuery.each($(".gcaliframe"), function(i, val) {
						var src = $(val).attr('src') + '&ts=' + Math.random();
						$(val).attr('src', src);
					});
				},
				dataType : 'json'
			});
		}
		Webzone.registerCloseButton(response, option);	
	}
	
	var getopt = {};
	getopt.onLoad = function(response) {
		process(response);	
	}
	if(option.parent) {
		$(option.parent).html("Loading Google Calendar Scheduler...<br />Please wait...");		
	}
	// GabeUtil.screenDimLoading(true);
	GabeUtil.ajaxRequest('get', url, getopt);	
}

Webzone.registerManageNonWebzone = function(selector, option) {
	if(!option) {
		option = {};
	}
	$(selector).click(function(event) {
		
		var query = '';
		
		if(option.parent) {
			// load in parent div and not in floating div
			if($(option.parent).html() != '') {
				// don't need to load it anymore because it's already loaded/has content.
				return;
			}
			query = '&parent=1';
		}
		
		GabeUtil.screenDimLoading(true);
		var nonwebid = $(this).metadata().nonwebid;
		var url = '/vwz-files/webzone/migration.php?managenonwebzone=1&nonwebid=' + nonwebid + '&ts=' + Math.random() + query;
		var opt = {};
		opt.onLoad = function(response) {
			if(option.parent) {
				GabeUtil.screenDimLoading(false);
				$(option.parent).html(response);
			} else {
				GabeUtil.screenDimLoading(true, response);
			}
			Webzone.processManageNonWebzone(response, option);
		}
		GabeUtil.ajaxRequest('get', url, opt);
	});
} 

Webzone.processManageNonWebzone = function(response, option) {
	$("#managenonwebzoneform").ajaxForm({
		success : function(response) {
			if(option.parent) {
				// reload window
				$(option.parent).html(response);
				if(document.getElementById('nonwebzoneeditsuccess')) {
					alert($("#nonwebzoneeditsuccess").html());
					window.location.reload(true);
				}
			} else {
				GabeUtil.screenDimLoading(true, response);
			}
			Webzone.processManageNonWebzone(response, option);
		}									
	});
	if(option.onLoad) {
		option.onLoad(response);
	}
	Webzone.registerCloseButton(response, option);
}

Webzone.registerNonWebzoneNotes = function(selector, option) {
	
	if(!option) {
		option = {};	
	}
	
	$(selector).click(function(event) {
		GabeUtil.screenDimLoading(true);
		var query = '';
		if(option.parent) {
			query += '&parent=1';	
		}
		var nonwebid = $(this).metadata().nonwebid;
		var url = '/vwz-files/webzone/migration.php?getnonwebzonenotes=1&nonwebid=' + nonwebid + '&ts=' + Math.random() + query;
		var opt = {};
		opt.onLoad = function(response) {
			if(option.parent) {
				$(option.parent).html(response);
				GabeUtil.screenDimLoading(false);
			} else {
				GabeUtil.screenDimLoading(true, response);
			}
			Webzone.processNonWebzoneNotes(response, option);
		}
		
		GabeUtil.ajaxRequest('get', url, opt);
	});
}

Webzone.processNonWebzoneNotes = function(response, option) {
	if(!option) {
		option = {};	
	}
	Webzone.registerCloseButton(response);
	$(".addnonwebzonenotebutton").click(function(event) {
		$(this).next().toggle();
	}).next().hide();
	
	$("#addnonwebzonenoteform").ajaxForm({
		success : function(response) {
			if(option.parent) {
				$(option.parent).html(response);
				GabeUtil.screenDimLoading(false);
			} else {
				GabeUtil.screenDimLoading(true, response);
			}
			Webzone.processNonWebzoneNotes(response, option);
		}									 
	});
}

Webzone.validateCardInfo = function(parent, requirecard) {
	
	if(!requirecard) {
		requirecard = false;	
	}
	
	var cardnum = $(parent + " input[name='cardnum']:first").val();
	var expmonth = $(parent + " input[name='ccexpdatemonth']:first").val();
	var expyear = $(parent + " input[name='ccexpdateyear']:first").val();
	var issuenumber = $(parent + " input[name='issuenumber']:first").val();
	
	var firstname = $(parent + " input[name='ccfirstname']:first").val();
	var lastname = $(parent + " input[name='cclastname']:first").val();
	var email = $(parent + " input[name='ccemail']:first").val();
	
	var address1 = $(parent + " input[name='ccaddress1']:first").val();
	var address2 = $(parent + " input[name='ccaddress2']:first").val();
	var city = $(parent + " input[name='cccity']:first").val();
	var state = $(parent + " input[name='ccstate']:first").val();
	var postcode = $(parent + " input[name='ccpostcode']:first").val();
	
	var response = {};
	try {
		if(requirecard) {
			if(lastname == '' || firstname == '' || email == '' || address1 == '' || city == '' || state == '' || postcode == '') {
				throw new Error("Please enter a billing firstname, lastname, email address, city, state and postal code.");
			}
			
			if(cardnum.length < 14) {
				throw new Error("Please enter a valid credit card number");
			}
			
			if(issuenumber.length < 3) {
				throw new Error("Please enter at least 3 numeric digits for the CVV/CVC2 Card Number");
			}
			
			if(expmonth == '') {
				throw new Error("Please enter a valid expiry month");	
			}
			if(expyear == '') {
				throw new Error("Please enter a valid expiry year");
			}
			
		}
		response.status = 'OK';
	} catch(err) {
		response.status = 'ERROR';
		response.message = err.message;
	}
	
	return response;
}

Webzone.sameCardBillingInfo = function(cardparent, infoparent) {
	
	$(cardparent + " input[name='ccfirstname']").val($(infoparent + " input[name='firstname']").val());
	$(cardparent + " input[name='cclastname']").val($(infoparent + " input[name='lastname']").val());
	$(cardparent + " input[name='ccemail']").val($(infoparent + " input[name='email']").val());
	$(cardparent + " input[name='ccphonenumber']").val($(infoparent + " input[name='phonenumber']").val());
	$(cardparent + " input[name='cccompanyname']").val($(infoparent + " input[name='companyname']").val());
	
	$(cardparent + " input[name='ccaddress1']").val($(infoparent + " input[name='address1']").val());
	$(cardparent + " input[name='ccaddress2']").val($(infoparent + " input[name='address2']").val());
	$(cardparent + " input[name='cccity']").val($(infoparent + " input[name='city']").val());
	$(cardparent + " input[name='ccstate']").val($(infoparent + " *[name='state']").val());
	$(cardparent + " input[name='ccpostcode']").val($(infoparent + " input[name='postcode']").val());
	$(cardparent + " select[name='cccountry'] option[value='" + $(infoparent + " select[name='country'] option:selected").val() + "']").attr('selected', true);
	
}

Webzone.registerShiftSessionsButton = function(selector, option) {
	
	if(!option) {
		option = {};	
	}
	
	$(selector).click(function(event) {
		var adopt = {};
		adopt.info = "You are about to shift this client's schedule forward by 1 week.";
		
		var conf = confirm(adopt.info);
		if(!conf) {
			return false;	
		}
		
		var thisbutton = this;
		
		adopt.successCallback = function() {
		
			GabeUtil.screenDimLoading(true, "Please wait while we shift this session's schedule.");
			
			var startsessionid = $(thisbutton).metadata().sessionid;
			var userid = $(thisbutton).metadata().userid;
			var hostingid = $(thisbutton).metadata().hostingid;
			
			var obj = {};
			obj.startsessionid = startsessionid;
			obj.userid = userid;
			obj.hostingid = hostingid;
			obj.shiftweek = 1;
			//alert(userid);
			//alert(hostingid);
			jQuery.post('/vwz-files/coaching/schedcalendar.php', obj, function(response) {
				//alert(response);
				response = eval("(" + response + ")");
				//alert(GabeUtil.htmlDecode(response.message));
				if(response.status == 'OK') {
					GabeUtil.screenDimLoading(true, GabeUtil.htmlDecode(response.message));
					var closeopt = {};
					closeopt.closeCallback = function(r) {
						if(option.closeCallback) {
							option.closeCallback(r);
						}
					}
					Webzone.registerCloseButton(response, closeopt);
				} else {
					alert(response.message);
					GabeUtil.screenDimLoading(false);
				}
			});
		}
		
		adopt.successCallback();
		//Webzone.displayAdminPasswordPanel("Shift Session Forward", adopt);
		
	});	
	
}

Webzone.getMigrationForm = function(targetdiv, option) {
	
	if(!option) {
		option = {};	
	}
	var query = '';
	if(option.admin) {
		query += '&admin=1';		
	}
	if(option.coachid) {
		query += '&coachid=' + option.coachid;		
		query += '&coach=1';
	}
	if(option.isclient) {
		query += '&isclient=1';	
	}
	if(option.isclientrelations) {
		query += '&is_clientrelations=1';
	}
	if(option.fromwebzonesales) {
		query += '&fromwebzonesales=1';
	}
	if(option.nonwebid) {
		query += '&nonwebid=' + option.nonwebid;
	}
	var migrationid = '';
	if(option.migrationid) {
		query += '&migrationid=' + option.migrationid;
		migrationid = option.migrationid;
	}
	targetdiv = $("#" + targetdiv);
	
	$(targetdiv).html("<center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Loading Migration Form<br />Please wait</center>");
	var url = '/vwz-files/webzone/migration.php?getmigrationform=1' + query + '&ts=' + Math.random();
	//alert(url);
	var getopt = {};
	getopt.onLoad = function(response) {
		
		//alert(response);
		
		$(targetdiv).html(response);
		
		if(option.loadedCallback) {
			option.loadedCallback(response);
		}
		
		if($(".datepickerfld", $(targetdiv)).length > 0) {
			//var origdate = $(".datepickerfld:eq(0)", $(targetdiv)).val();
			$(".datepickerfld").datepicker({
				dateFormat : 'yy-mm-dd'
			});
			//$(".datepickerfld:eq(0)", $(targetdiv)).val(origdate);
		}
		
		var submitopt = {
			beforeSubmit : function(odata, oform, opt) {
				
				if($("input[name='status']:eq(0)", "#addmigrationformform").val() == 'pendingtransfer') {
					var conf = confirm("You are about to submit this client for transfer. Continue?");
					if(!conf) {
						return false;	
					}
				}
				
				/*
				jQuery.each($("#addmigrationformform *[name='salesuser_id']"), function(i, val) {
					alert($(val).attr('disabled'));
				});
				return false;
				*/
				
				/*
				alert('Coming Soon ;)!');
				return false;
				*/
				try {
					
					if($("#clientsource").val() == 'servermc') {
						if($("#smcfolder").val() == '') {
							throw new Error("Please enter the Server MC folder.");	
						}
					}
					
					if(!option.nocreditcard) {
						var cardstatus = Webzone.validateCardInfo("#addmigrationformform", true);
						if(cardstatus.status == 'ERROR') {
							throw new Error(cardstatus.message);	
						}
					}
					
					var required = "firstname,lastname,email,phonenumber,address1,city,postcode";
					required = required.split(',');
					for(var i = 0; i < required.length; i++) {
						if($("#addmigrationformform input[name='" + required[i] + "']").val() == '') {
							$("#addmigrationformform input[name='" + required[i] + "']").focus();
							throw new Error("Please enter a value for " + required[i] + ".");	
						}	
					}
					
					jQuery.each($("input[name='file[]']"), function(i, val) {
						if($(val).val().length < 1) {
							throw new Error("Please select the file to upload.");
						}
					});
					
					jQuery.each($("input[name='filename[]']"), function(i, val) {
						if($(val).val().length < 1) {
							throw new Error("Please enter the client file's name/title.");
						}
					});
					
					jQuery.each($("input[name='domain[]']"), function(i, val) {
						if($(val).val().length < 1) {
							throw new Error("Please enter the domain name of the domain name record.");
						}
					});
				} catch(e) {
					alert(e.message);
					return false;
				}
				
				GabeUtil.screenDimLoading(true);
				return true;
				
			},
			success : function(response) {
				GabeUtil.screenDimLoading(false);
				//alert(response);
				alert(response.message);
				if(response.status == 'OK') {
					if(option.successCallback) {
						option.successCallback(response);
					}	
				}
			},
			dataType : 'json'
		};
		
		$(".savemigrationformbutton").click(function(event) {
			$("#addmigrationformform input[name='status']").val('pendingreview');
			$("#addmigrationformform *[name='state']:gt(0)").remove();
			$("#addmigrationformform").ajaxSubmit(submitopt);
		});
		
		$("#addmigrationformform").submit(function(event) {
			event.preventDefault();
			$("#addmigrationformform *[name='state']:gt(0)").remove();
			$("#addmigrationformform").ajaxSubmit(submitopt);
		});
		
		var lastchosenapp = null;
		var setCurricOptions = function() {
	
			var appid = $("#origappidfld option:selected").val();
			if(!appid) {
				return;
			}
			
			var sessoptions = sesslists[appid];
			var lastoption = null;
			jQuery.each($(".sessioncurricspan"), function(i, val) {
				if(($(val).html()).length < 20 || lastchosenapp != appid) {
					$(val).html(sessoptions);
					if($(val).metadata().sesslistid) {
						$("select option[value='" + $(val).metadata().sesslistid + "']", $(val)).attr('selected', true);
					}
				}
				if(lastoption) {
					var found = false;
					jQuery.each($("select option", $(val)), function(i2, val2) {
						var thisorderlist = parseInt($(val2).metadata().orderlist);
						if(found == false) {
							$(val2).attr('selected', true);
						}
						if(thisorderlist > lastoption) {
							found = true
							return;
						}
					});
				}
				lastoption = parseInt($("select:eq(0) option:selected", $(val)).metadata().orderlist);
			});
			
			lastchosenapp = appid;
			
		}
		
		var addSessionRow = function() {
			$("#sessionstable tr:last").after(sessRowTemp);
			setCurricOptions();
			$(".removesession:last").click(function(event) {
				$(this).closest("tr").remove();
				setCurricOptions();
			});
		}
		
		
		var addDomainRow = function() {
			$("#domainstable tr:last").after(domRowTemp);
			setCurricOptions();
			$(".removedomain:last").click(function(event) {
				$(this).closest("tr").remove();
			});
		}
		
		
		var addFileRow = function() {
			$("#filestable tr:last").after(fileRowTemp);
			$(".removefile:last").click(function(event) {
				$(this).closest("tr").remove();
			});
		}
		
		$(".removesession").click(function(event) {
			$(this).closest("tr").remove();
			setCurricOptions();
		});
		
		$(".removedomain").click(function(event) {
			$(this).closest("tr").remove();
		});
		
		$(".removefile").click(function(event) {
			$(this).closest("tr").remove();
		});
		
		$("#addsessrowbutton").click(function(event) {
			addSessionRow();
		});
		
		$("#adddomrowbutton").click(function(event) {
			addDomainRow();
		});
		
		$("#addfilerowbutton").click(function(event) {
			addFileRow();
		});
		
		$("#origappidfld").change(function(event) {
			setCurricOptions();
		});
		
		var triggerSourceOptions = function() {
			var clientsource = $("#clientsource option:selected").val();
			if(clientsource == 'servermc') {
				$("#origappidfld").closest("table").closest("tr").hide();
				$("#smcfolder").closest("table").closest("tr").show();
			} else {
				$("#origappidfld").closest("table").closest("tr").show();
				$("#smcfolder").closest("table").closest("tr").hide();
			}
		}
		
		$("#clientsource").change(function(event) {
			triggerSourceOptions();							   
		});
		
		triggerSourceOptions();
		
		var triggerCoachTimezone = function() {
			var mycoachid = $("#coachidfld").val();
			var coachtz = $("#coachtimezone" + mycoachid).html();
			//alert(coachtz);
			$("#sessiontimezone option[value='" + coachtz + "']").attr('selected', true);
		}
		
		triggerCoachTimezone();
		$("#coachidfld").change(function(event) {
			triggerCoachTimezone();								 
		});
		
		$("#coachidfld").keyup(function(event) {
			triggerCoachTimezone();								 
		});
	
		var triggerDivisions = function() {
			var sfid = $("#salesfloor_id option:selected").val();
			currSalesfloorId = sfid;
			$(".salesdivisiondropdown").hide();
			$(".salesdivisiondropdown").attr('disabled', true);
			if(document.getElementById("salesdivision_id" + currSalesfloorId)) {
				$("#salesdivision_id" + currSalesfloorId).show();
				$("#salesdivision_id" + currSalesfloorId).attr('disabled', false);
				currSalesDivisionId = $("#salesdivision_id" + currSalesfloorId + " option:selected").val();
			}
			triggerSalesUsers();
		}
	
		var triggerSalesUsers = function() {
			$(".salesuserdropdown").hide();
			$(".salesuserdropdown").attr('disabled', true);
			if(document.getElementById('salesuser_id' + currSalesfloorId)) {
				$("#salesuser_id" + currSalesfloorId).show();
				$("#salesuser_id" + currSalesfloorId).attr('disabled', false);
			}
		}
		
		triggerDivisions();
		
		$("#salesfloor_id").change(function(event) {
			triggerDivisions();
			Webzone.getSfLeadDropdown($("#salesfloor_id option:selected").val());
		});
		
		$(".salesdivisiondropdown").click(function(event) {
			triggerDivisions();
		});
		
		$("#signupproducts-container").tabs();
		
		$(".selectsalesprod, #addclientform select").click(function(event) {
			Webzone.computeTotalOrder();
		});
		
		// hide salesuser dropdown since it only has admin in it
		// $(".salesuserdropdown").closest("tr").hide();
		
		
		$("#ccaddresssame").click(function(event) {
			if($("#ccaddresssame").attr('checked') == true) {
				/*
				$("#addmigrationformform input[name='ccaddress1']").val($("#addmigrationformform input[name='address1']").val());
				$("#addmigrationformform input[name='cccity']").val($("#addmigrationformform input[name='city']").val());
				$("#addmigrationformform input[name='ccstate']").val($("#addmigrationformform *[name='state']:eq(0)").val());
				$("#addmigrationformform input[name='ccpostcode']").val($("#addmigrationformform input[name='postcode']").val());
				$("#addmigrationformform select[name='cccountry'] option[value='" + $("#addmigrationformform select[name='country'] option:selected").val() + "']").attr('selected', true);
				*/
				Webzone.sameCardBillingInfo("#addmigrationformform", "#addmigrationformform");
			}
		});
		
		$("#addclientform").ajaxForm({
			beforeSubmit : function(odata, oform, opt) {
				GabeUtil.screenDimLoading(true);
				return true;
			},
			success : function(response) {
				GabeUtil.screenDimLoading(false);
				//alert(response);
				response = eval("(" + response + ")");
				alert(response.message);
				//alert(response.data);
				if(response.status == 'OK') {
					// if forcompliance, set getclients to forcompliance
					Webzone.clearAddClientForm();
				}
			}
		});
		
		
		var salesrepname = $("input[name='salesrep_name']:eq(0)").attr('value');
		
		var cformopt = {};
		cformopt.state = $("#savedstate").val();
		Webzone.clearAddClientForm(cformopt);
		
		
		$("input[name='salesrep_name']").val(salesrepname);
		
		var triggerCoachType = function() {
			if(document.getElementById('unknowncoach')) {
				if(document.getElementById('unknowncoach').checked) {
					$("input[name='coachtype'][value='previous']").attr('checked', true);
					$("input[name='prevcoachname']").val('Unknown');
					$("input[name='prevcoachemail']").val('Unknown');
				}
			}
			var selcoachtype = $("input[name='coachtype']:checked").val();
			$(".coachtypediv").hide();
			$("#coachtypediv-" + selcoachtype).show();
		}
		
		if(document.getElementById('unknowncoach')) {
			$("#unknowncoach").click(function(event) {
				triggerCoachType();
			});
		}
		
		triggerCoachType();
		$("input[name='coachtype']").click(function(event) {
			triggerCoachType();
		});
		
		if(option.coachid) {
			// coach is already set
			$("input[name='coachtype'][value='previous']").closest("span").hide();
			$("input[name='coachtype'][value='current']").attr('checked', true).closest("span").hide();
		}
		
		if($("#origappidfld option:selected").val() == '') {
			$("#origappidfld option:eq(1)").attr('selected', true);
			setCurricOptions();	
		}
		
		if(!migrationid) {
			// don't have empty/new rows by default
			/*
			addSessionRow();
			addDomainRow();
			addFileRow();
			*/
		} else {
			setCurricOptions();		
			if($("#savedsessiontimezone").val() != '') {
				$("#sessiontimezone option[value='" + $("#savedsessiontimezone").val() + "']").attr('selected', true);
			}
		}
		
	}
	
	GabeUtil.ajaxRequest('get', url, getopt);
}

Webzone.getAddContentForm = function(userid, option) {
	if(!option) {
		option = {};
	}
	var url = '/vwz-files/contentfile/index.php?addcontentform=1&userid=' + userid;
	var opt = {};
	opt.onLoad = function(response) {
		$("#addcontentformdiv").html(response);
		$("#addcontentform").ajaxForm({
			success : function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					$("#addcontentform input[type='text']").val('');
					if(option.successCallback) {
						option.successCallback(response);
					}
					//$("#addcontentform").hide();
				}
			},
			dataType : 'json'
		});
	}
	GabeUtil.ajaxRequest('get', url, opt);
}

Webzone.registerSendSfWelcomeEmailButton = function() {
	jQuery.each($(".sendsfwelcomeemailbutton"), function(i, val) {
		if($(val).metadata().assigned == true) {
			return;
		}
		$(val).metadata().assigned = true;
		$(val).after("<span>Sending welcome email. Please wait...</span>");
		$(val).next().hide();
		$(val).click(function(event) {
			var conf = confirm('Would you like to re-send the welcome email to this client?');					  
			if(!conf) {
				return false;	
			}
			$(val).hide();
			$(val).next().show();
			var userid = $(val).metadata().userid;
			var url = '/vwz-files/webzone/client.php?sendsfwelcomeemail=1&userid=' + userid;
			//alert(url);
			var thisopt = {};
			var emailsent = function(response) {
				$(val).show();
				$(val).next().hide();
			}
			thisopt.onOK = emailsent;
			thisopt.onERROR = emailsent;
			GabeUtil.ajaxRequest('get', url, thisopt, 'json');
		});
	});	
}

Webzone.tooltips = null;
Webzone.initTooltips = function(selector, forcerefresh) {
	if(!selector) {
		selector = document.body;
	}
	if(typeof forcerefresh == 'undefined') {
		forcerefresh = false;	
	}
	
	var initTooltips = function() {
		/*
		var html = $(selector).html().replace(/<tooltip>([0-9]+)<\/tooltip>/g, "<img src='/vwz-files/image/icon/question.png' class=\"webz-tooltipicon {id:'$1'} \" style='vertical-align:middle;height:25px' />");
		var html = html.replace(/<TOOLTIP>([0-9]+)<\/TOOLTIP>/g, "<img src='/vwz-files/image/icon/question.png' class=\"webz-tooltipicon {id:'$1'} \" style='vertical-align:middle;height:25px' />");
		*/
		// TOOLTIP FORMAT: <span class='webztooltip'>(tooltipid)</span>
		jQuery.each($(".webztooltip", $(selector)), function(i, val) {
			if($(val).hasClass('webztooltip-initiated')) {
				return;
			}
			$(val).addClass('webztooltip-initiated');
			var tipid = $(val).html();
			$(val).metadata().id = tipid;
			$(val).html("<img src='" + Webzone.tooltips[tipid].iconurl + "' style='vertical-align:baseline' class=\"{id:'" + tipid + "'}\" />");
			$(val).tooltip({
				bodyHandler : function() {
					if(!Webzone.tooltips[tipid]) {
						return '';	
					}
					return GabeUtil.htmlDecode("Tip # " + tipid + " : " + Webzone.tooltips[tipid].description);
				},
				showURL : false
			});
		});
	}
	
	if(Webzone.tooltips === null || forcerefresh == true) {
		var url = '/vwz-files/webzone/tooltips.php?ts=' + Math.random();
		var opt = {};
		opt.onLoad = function(response) {
			Webzone.tooltips = response;
			initTooltips();
		}
		GabeUtil.ajaxRequest('get', url, opt, 'json');
	} else {
		initTooltips();	
	}
	
}

Webzone.initCreditCardPanel = function() {
	
	$(".addnewbutton").click(function(event) {
		$(this).next().toggle();
	}).next().hide();
	
	var cardsopt = {};
	cardsopt.successCallback = function(response) {
		GabeUtil.registerToggleButtons("#getcardsdiv .editbutton", { hide : false });
		
		var cceditopt = {
			beforeSubmit : function(odata, oform, opt) {
				GabeUtil.screenDimLoading(true);
			},
			success : function(response) {
				GabeUtil.screenDimLoading(false);
				alert(response.message);
				if(response.status == 'OK') {
					getccards();
				}
			},
			dataType : 'json'
		};
		
		$(".cceditform").ajaxForm(cceditopt);
		$(".deletecardbutton").click(function(event) {
			var conf = confirm("Would you like to delete this credit card?");
			if(!conf) {
				return false;
			}
			var ccid = $(this).metadata().id;
			var url = '/vwz-files/webzone/client.php?deleteccard=1&ccid=' + ccid;
			var delopt = {};
			delopt.onOK = function(response) {
				getccards();
			}
			GabeUtil.ajaxRequest('get', url, delopt, 'json');
		});
		
		$(".defaultcardbutton").click(function(event) {
			var conf = confirm("Would you like to delete this credit card?");
			if(!conf) {
				return false;
			}
			var formdiv = $(this).metadata().formdiv;
			$("#" + formdiv + " input[name='ccdefault']").attr('checked', true);
			$("#" + formdiv + " form:eq(0)").ajaxSubmit(cceditopt);
		});
	}
	
	var getccards = GabeUtil.registerActiveSearchForm('getcardsform', 'getcardsdiv', cardsopt);
	$("#creditcard-tab").click(function(event) {
		getccards();
	});
	
	$("#addccform").ajaxForm({
		beforeSubmit : function(odata, oform, opt) {
			var cardstatus = Webzone.validateCardInfo("#addccform", true);
			if(cardstatus.status == 'ERROR') {
				alert(cardstatus.message);
				return false;
			}
			GabeUtil.screenDimLoading(true);
		},
		success : function(response) {
			GabeUtil.screenDimLoading(false);
			//alert(response);
			alert(response.message);
			if(response.status == 'OK') {
				getccards();
				$("#addccform input[type='text']").val('');
				$("#addccform").closest("div").toggle('normal');
			}
		},
		dataType : 'json'
	});
	
}

Webzone.registerMarketingUser = function(formsel) {
	$("input[name='admin']", $(formsel)).click(function(event) {
		Webzone.triggerMarketingUser(formsel);
	});
}

Webzone.triggerMarketingUser = function(formsel) {
	if($("input[name='admin']:checked", $(formsel)).val() == 'yes') {
		$("input[name='editor'][value='yes']", $(formsel)).attr('checked', true);
		$("input[name='editor']:eq(0)", $(formsel)).closest("tr").hide();
	} else {
		$("input[name='editor'][value='no']", $(formsel)).attr('checked', true);
		$("input[name='editor']:eq(0)", $(formsel)).closest("tr").show();
	}
}

Webzone.getLeadCamps = function(leadid) {
	var date = new Date();
	var url = '/vwz-files/webzone/salesfloor.php?getcamps=1&sflead_id=' + leadid + '&ts=' + date.getTime();	
	jQuery.get(url, {}, function(response) {
		$("#sfcamps" + leadid).html(response);
		$(".deletesfcamp", $("#sfcamps" + leadid)).click(function(event) {
			var leadid = $(this).metadata().sflead_id;
			var campid = $(this).metadata().id;
			var url = '/vwz-files/webzone/salesfloor.php?deletecamp=1&campid=' + campid + '&sflead_id=' + leadid;
			var conf = confirm("Would you like to delete this campaign?");
			if(!conf) {
				return;
			}
			jQuery.get(url, {}, function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					Webzone.getLeadCamps(leadid);
				}
			}, 'json');
		});
	});
}

Webzone.getleads = null;

Webzone.processGetLeadsForm = function(response) {
	
	$(".quickeditlead").click(function(event) {
	
		var thisbtn = this;
		this.value = 'Please wait';
		this.disabled = true;
		
		var name = $(this).prev().val();
		var leadid = $(this).metadata().id;
		if(!name) {
			alert("Please enter a name.");
			return;
		}
		var url = '/vwz-files/webzone/salesfloor.php?editlead=1&leadid=' + leadid + '&name=' + encodeURIComponent(name);
		//alert(url);
		jQuery.get(url, {}, function(response) {
			alert(response.message);
			
			thisbtn.value = 'Edit';
			thisbtn.disabled = false;
			
			if(response.status == 'OK') {
				Webzone.getleads();
			}
		}, 'json');
	});
	
	$(".deletelead").click(function(event) {
		var conf = confirm("Would you like to delete this lead source?");
		if(!conf) {
			return false;
		}
		var leadid = $(this).metadata().id;
		var url = '/vwz-files/webzone/salesfloor.php?deletelead=1&leadid=' + leadid;
		//alert(url);
		jQuery.get(url, {}, function(response) {
			alert(response.message);
			if(response.status == 'OK') {
				Webzone.getleads();
			}
		}, 'json');
	});
	
	/*
	$(".sfleadheader").click(function(event) {
		$(this).next().toggle();
	});
	*/
	
	jQuery.each($(".sfleadheader"), function(i, val) {
		var leadid = $(val).metadata().id;
		Webzone.getLeadCamps(leadid);
	});
	
	$(".addcampform").ajaxForm({
		beforeSubmit : function(odata, oform, opt) {
			if($("input[name='name']", $(oform)).val() == '') {
				alert("Please enter the campaign name.");
				return false;
			}
		},
		success : function(response) {
			alert(response.message);
			if(response.status == 'OK') {
				Webzone.getLeadCamps(response.data);
				$("input[name='name']", $("#getleadsdiv")).val('');
			}
		},
		dataType : 'json'
	});
}

Webzone.initOcThemePanel = function(html) {
	/*
	var dimloading = GabeUtil.screenDimLoading(true, html);	
	var dim = GabeUtil.scDim;
	dimloading.style.display = 'none';
	dim.style.display = 'none';
	*/
}

// SALESFLOOR FUNCTION
Webzone.triggerCampDropdown = function(element, selected) {
	if(!selected) {
		selected = '';
	}
	$("select", $(element).next()).attr('disabled', true);
	$("select", $(element).next()).hide();
	var leadid = $("option:selected", $(element)).val();
	//alert(leadid);
	jQuery.each($("select", $(element).next()), function(i, val) {
		if($(val).metadata().sflead_id == leadid) {
			$(val).show();
			$(val).attr('disabled', false);
			return;
		}
	});
}

// SALESFLOOR FUNCTION
Webzone.getSfLeadDropdown = function(sfid) {
	var date = new Date();
	var url = '/vwz-files/webzone/salesfloor.php?getsfleaddropdown=1&salesfloor_id=' + sfid + '&ts=' + date.getTime();
	$(".sfleaddropdownspan").html("Loading sales company campaigns...");
	jQuery.get(url, {}, function(response) {
		$(".sfleaddropdownspan").html(response);
		Webzone.triggerCampDropdown(".sfleaddropdownspan select[name='sflead_id']");
		$(".sfleaddropdownspan select[name='sflead_id']").change(function(event) {
			Webzone.triggerCampDropdown(this);
		});
	});
}

// SALESFLOOR FUNCTION
Webzone.loadClientInfo = function(clientid, opt) {
	
	if(!opt) {
		opt = {};
	}
	
	var url = '/vwz-files/webzone/client.php?getclientinfo=1&userid=' + clientid;
	
	jQuery.get(url, {}, function(response) {
		//alert(response.timezone);
		//alert(response.salesdivision_id);
		Webzone.loadClientInfoToOrderForm(response);
		//alert(response.salesrep_name);
		
	}, 'json');

}

Webzone.loadClientInfoToOrderForm = function(response) {
	
	$("#addclientform input[name='firstname']").val(response.firstname);
	$("#addclientform input[name='lastname']").val(response.lastname);
	$("#addclientform input[name='name2']").val(response.name2);
	$("#addclientform input[name='companyname']").val(response.companyname);
	$("#addclientform input[name='email']").val(response.email);
	$("#addclientform input[name='phonenumber']").val(response.phonenumber);
	$("#addclientform input[name='phonenumber2']").val(response.phonenumber2);
	$("#addclientform input[name='address1']").val(response.address1);
	$("#addclientform input[name='address2']").val(response.address2);
	$("#addclientform input[name='city']").val(response.city);
	$("#addclientform input[name='postcode']").val(response.postcode);
	$("#addclientform select[name='country'] option[value='" + response.country + "']").attr('selected', true);
	$("#addclientform select[name='timezone'] option[value='" + response.timezone + "']").attr('selected', true);
	$("#addclientform select[name='salesdivision_id'] option[value='" + response.salesdivision_id + "']").attr('selected', true);
	$("#addclientform input[name='salesrep_name']").val(response.salesrep_name);
	
	if(response.nonwebid) {
		$("#addclientform input[name='nonwebid']").val(response.nonwebid);
	}
	if(response.notes) {
		$("#addclientform textarea[name='comments']").html(GabeUtil.htmlDecode(response.notes).replace(/<br \/>/ig, '\n'));
	}
	
	Webzone.triggerStateProvince(response.state);
	
	if(response.sflead_id != '') {
		$("#addclientform select[name='sflead_id'] option[value='" + response.sflead_id + "']").attr('selected', true);
		Webzone.triggerCampDropdown(".sfleaddropdownspan select[name='sflead_id']");
	}
	
	if(response.sfcamp_id != '') {
		$("#addclientform select[name='sfcamp_id'] option[value='" + response.sfcamp_id + "']").attr('selected', true);
	}
	
}

// SALESFLOOR FUNCTION
Webzone.triggerStateProvince = function(selstate, option) {
	
	if(!option) {
		option = {};		
	}
	
	if(!option.countrySelector) {
		option.countrySelector = '#addordercountryfield'		
	}
	
	if(!option.stateFieldSelector) {
		option.stateFieldSelector = '#statefieldspan';
	}
	
	if(!option.stateLabelSelector) {
		option.stateLabelSelector = '#statefieldlabelspan';
	}
	
	if(!selstate) {
		selstate = '';	
	}
	
	var country = $(option.countrySelector + " option:selected").val();
	//alert(country);
	if(country == 'US') {
		$(option.stateFieldSelector).html($("#statefieldspanselect").html());
		//alert($(option.stateFieldSelector).html());
		$(option.stateLabelSelector).html("State");
	} else {
		$(option.stateFieldSelector).html($("#statefieldspantext").html());
		$(option.stateLabelSelector).html("Providence/Province");
		Webzone.registerEnterToNext(option.stateFieldSelector + " input[type='text']");
	}
	
	if(country == 'US') {
		if(!selstate) {
			selstate = 'AK';	
		}
		$("#statefieldspan select[name='state'] option[value='" + selstate + "']").attr('selected', true);
	} else {
		$("#statefieldspan input[name='state']").val(selstate);
	}
}

Webzone.triggerClientType = function(form) {
	if(!form) {
		form = '*';
	}
	
	// addorderclienttype
	if($("input[name='addorderclienttype']:checked").val() == 'new') {
		$("input, select", $("#addorderclienttable")).attr('disabled', false);
		$("input, select", $("#addorderclienttable")).css('color', '#000000');
		$("#addclientform .addorderclientsdropdown").closest("tr").hide();
		$(".addorder-clientname").html("New Client");
	} else {
		// display existing client
		$("input, select", $("#addorderclienttable")).attr('disabled', true);
		$("select[name='salesdivision_id']", $("#addorderclienttable")).attr('disabled', false);
		Webzone.loadClientInfo($(".addorderclientsdropdown option:selected").val());
		$("input, select", $("#addorderclienttable")).css('color', '#CCCCCC');
		$("#addclientform .addorderclientsdropdown").closest("tr").show();
		$(".addorder-clientname").html($(".addorderclientsdropdown option:selected").html());
		//$("#addclientform input[name='addorderclienttype'][value='existing']").attr('checked', true);
	}
	
}

Webzone.registerEnterToNext = function(selector) {
	$(selector).keydown(function(e) {
		var thisfield = this;
		if(e.keyCode == 13) {
			var lastfound = false;
			var nextfound = false;
			jQuery.each($("input[type='text']", $(thisfield).closest("form")), function(i, val) {
				if(nextfound == true) {
					return;	
				}
				if(lastfound == true) {
					val.focus();
					nextfound = true;
				}
				if(val == thisfield) {
					lastfound = true;
				}
			});
			return false;
		}		
	});	
}

// SALESFLOOR FUNCTION 
Webzone.addClientFormInitiated = false;

Webzone.clearAddClientForm = function(opt) {

	if(!opt) {
		opt = {};		
	}
	
	if(!opt.state) {
		opt.state = 'MO';
	}
	//alert('!');
	
	if(Webzone.addClientFormInitiated == false) {
		// initiate form
		// when enter is pressed, move to next line
		Webzone.registerEnterToNext("#addclientform input[type='text']");
		Webzone.addClientFormInitiated = true;
	}
	
	$("#addclientform .addorder-productnoteslink").next().val('');
	$("#addclientform .addorder-productnoteslink").next().hide();
	$("#addclientform input[type='text']").val('');
	$("#addclientform input[name='nonwebid']").val('');
	$("#addclientform input[name='product_id[]']").attr('checked', false);
	$("#addclientform .freeprodcheckbox").attr('checked', false);
	$("#addclientform input[name='complianceid']").val('');
	$("input[name='addorderclienttype'][value='new']").attr('checked', true);
	Webzone.computeTotalOrder();
	Webzone.triggerClientType();
	
	if(document.getElementById('addorder-1')) {
		$(".addorderdiv").hide();
		$("#addorder-1").show();
	}
	
	// uncheck all products
	$("#addclientform input[name='product_id[]']").attr('checked', false);
	
	Webzone.triggerStateProvince(opt.state);
	$("#addordercountryfield").change(function(event) {
		Webzone.triggerStateProvince();
	});
	
}
	
// SALESFLOOR FUNCTION 
Webzone.computeTotalOrder = function() {
	var total = 0;
	jQuery.each($(".selectsalesprod:checked"), function(i, val) {
		var billingtype = $(".billingcyclefld", $(val).closest("tr")).val();
		if(billingtype == 'onetime') {
			var price = parseFloat($(".pricescell", $(this).closest("tr")).html().match(/[0-9]+\.[0-9]+/i));
		} else {
			var price = parseFloat($(".billingcyclefld option:selected", $(this).closest("tr")).html().match(/[0-9]+\.[0-9]+/i));
		}
		var prodid = $(val).val();
		//alert(prodid);
		var quantity = parseInt($("select[name='quantity[" + prodid + "]']").val(), 10);
		if(quantity) {
			price =  parseFloat(price) * quantity;	
		}
		total += price;
	});
	total = new String((Math.round(total * 100) / 100));
	if(total.indexOf('.') > 0) {
		total = total.split('.');
		if(total[1].length < 2) {
			total[1] = total[1] + '0';
		}
		total = total[0] + '.' + total[1];
	} else {
		total = total + '.00';
	}
	$(".totalinorder").html("$ " + total);
}

Webzone.triggerAdminCompliance = function(aform, opt) {
	if(!opt) {
		opt = {};	
	}
	//alert('1');
	if($("select[name='position'] option:selected", $(aform)).val() == 'admin') {
		
		// position is admin
		if($("input[name='compliance']:checked", $(aform)).val() == 'no') {
			$("input[name='compliance'][value='local']", $(aform)).attr('checked', true);
		}
		if($("input[name='savespec']:checked", $(aform)).val() == 'no') {
			$("input[name='savespec'][value='local']", $(aform)).attr('checked', true);
		}
		if($("input[name='accounting']:checked", $(aform)).val() == 'no') {
			$("input[name='accounting'][value='local']", $(aform)).attr('checked', true);
		}
		
		$("input[name='compliance'][value='no']", $(aform)).closest("span").hide();
		$("input[name='savespec'][value='no']", $(aform)).closest("span").hide();
		$("input[name='accounting'][value='no']", $(aform)).closest("span").hide();
		
	} else {
		
		$("input[name='compliance'][value='no']", $(aform)).closest("span").show();
		$("input[name='savespec'][value='no']", $(aform)).closest("span").show();
		$("input[name='accounting'][value='no']", $(aform)).closest("span").show();
		
	}
}

Webzone.renderGradientField = function(element) {
	var val = element;
	$(val).before('<span class="webz-inputwrapper"><img src="/vwz-files/image/txtinput-l.png" /><span class="webz-inputtext-c"></span><img src="/vwz-files/image/txtinput-r.png" /></span>');
	$(".webz-inputtext-c", $(val).prev()).append($(val));	
}


Webzone.renderGradientButton = function(selector, image) {
	
	jQuery.each($(selector), function(i, val) {
		$(val).before('<span class="txtinputwrapper"><img src="/vwz-files/image/' + image + '-l.png" /><span class="btninside"></span><img src="/vwz-files/image/' + image + '-r.png" /></span>');
		$(val).addClass(image + '-c');
		$(".btninside", $(val).prev()).append($(val));
	});
	
}

Webzone.renderPrice = function(selector, option) {
	if(!option) {
		option = {};	
	}
	jQuery.each($(selector), function(i, val) {
		$(val).html($(val).html().replace(/USD/ig, ''));
		$(val).html($(val).html().replace(/\$/ig, "<span class='floatprice'>$</span>"));
		$(val).html($(val).html().replace(/(\.[0-9]{2})\s*([a-zA-Z ]+)?/ig, "<span class='floatprice'>$1</span><span class='prodpayperiod'>$2</span>"));
		$(val).html($(val).html().replace(/<br>/ig, ''));
		//alert($(val).html());
	});
}


Webzone.registerCancelControlButton = function(selector, option) {
	
	if(!selector) {
		selector = "";	
	} else {
		selector = selector + " ";	
	}
	
	if(!option) {
		option = {};	
		option.closeCallback = function(response) {
			
		}
	}
	
	var displayPanel = function(element) {
		GabeUtil.screenDimLoading(true);
		var thisbutton = element;
		var date = new Date();
		var clientid = $(thisbutton).metadata().clientid;
		var url = '/vwz-files/webzone/client.php?cancelcontrol=1&ts=' + date.getTime() + '&clientid=' + clientid;
		jQuery.get(url, {}, function(response) {
			GabeUtil.screenDimLoading(true, response);
			var closeopt = option;
			Webzone.registerCloseButton(response, closeopt);
			$("#cancelcontrolform").ajaxForm({
				success : function(response) {
					alert(response.message);
					if(response.status == 'OK') {
						displayPanel(thisbutton);
					}
				},
				dataType : 'json'
			});
		});	
	}
	
	$(selector + ".cancelcontrolbutton").click(function(event) {
		displayPanel(this);
	});
	
}

Webzone.registerCheckDomain = function(element, target, option) {
	if(!option) {
		option = {};	
	}
	
	if(!option.noform) {
		option.noform = 0;	
	}
	
	if(!option.successCallback) {
		option.successCallback = function(response) {
				
		}
	}
	if(!option.loadingCallback) {
		option.loadingCallback = function(response) {
				
		}
	}
	var intid = 0;
	element.onkeyup = function(event) {
		
		clearTimeout(intid);
		intid = setTimeout(function() {
									
			element.disabled = true;
			
			element.value = element.value.replace(/http\:\/\//ig, '');
			element.value = element.value.replace(/^www\./ig, '');
			element.value = element.value.replace(/(.+)(\..+)/ig, "$1");
			element.value = element.value.replace(/[^a-zA-Z0-9\-]+/, '').toLowerCase();
			
			if(element.value.length < 1) {
				return;
			}
			
			target.innerHTML = "<center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Please wait while we check the availability of this domain name.</center>";
			
			var query = '';
			if(option.noform) {
				query += '&noform=1';	
			}
			var url = '/vwz-files/lib/domain/get.php?domainname=' + element.value + query;
			jQuery.get(url, {}, function(response) {
				//alert(response);
				element.disabled = false;
				target.innerHTML = response;
				option.successCallback(response);
			});
		}, 1000);
		
	}
	//alert(element.id);
}

Webzone.addSessionReportCallback = function(callback) {
	Webzone.submitSessionReportCallback.push(callback);	
}

Webzone.getTimezoneClocks = function(option) {
	
	if(!option) {
		option = {};	
	}
	
	var calhtml = '';
	if(option.calibrate) {
		calhtml = 'Is your timezone clock off?  <a href="javascript:void(0)" id="tzclockcalibratebtn">Click here to calibrate it now!</a><div id="tzclockcalibratesettings" style="display:none"><form method="post" action="/vwz-files/webzone/client.php" id="settzclockoffsetform"><input type="hidden" name="settzclockoffset" value="1" />Choose the number of hours to add or subtract from your timezone clock: <select name="offset"><option value="0">0</option><option value="1">+1</option><option value="2">+2</option><option value="3">+3</option><option value="4">+4</option><option value="5">+5</option><option value="6">+6</option><option value="7">+7</option><option value="8">+8</option><option value="9">+9</option><option value="-1">-1</option><option value="-2">-2</option><option value="-3">-3</option><option value="-4">-4</option><option value="-5">-5</option><option value="-6">-6</option><option value="-7">-7</option><option value="-8">-8</option><option value="-9">-9</option></select><input type="submit" name="submitbutton" value="Calibrate Clocks" /></form></div>';
	}
	
	var url = '/vwz-files/webzone/client.php?timezonests=1';
	
	jQuery.get(url, {}, function(response) {
		//alert(response);
		response = eval("(" + response + ")");
		var tmp = '';
		var cells = '';
		for(var key in response) {
			tmp = Webzone.adminClockTmp.replace(/\{timezonename\}/g, key);
			tmp = tmp.replace(/\{ts\}/g, response[key].ts);
			tmp = "<td>" + tmp + "</td>";
			cells = cells + tmp;
		}
		
		$("#timezonesdiv").html("<table cellspacing='0' cellpadding='0' border='0'><tr>" + cells + "</tr></table>" + calhtml);
		
		if(document.getElementById('settzclockoffsetform')) {
			$("#timezonesdiv").css('background-color', '#ffffff');
			$("#tzclockcalibratebtn").click(function(event) {
				$("#tzclockcalibratesettings").show();
			});
			$("#settzclockoffsetform").ajaxForm({
				success : function(response) {
					alert(response.message);
					if(response.status == 'OK') {
						Webzone.getTimezoneClocks(option);
					}
				},
				dataType : 'json'
			});
		}
		
		jQuery.each($(".timezonetime"), function(i, val) {
			Webzone.initTimezoneClock(val);
		});
		
	});
	
	
}

Webzone.initTimezoneClock = function(element, option) {
	
	if(!option) {
		option = {};	
	}
	
	var range = 'AM';
	var currts = $(element).metadata().ts;
	
	var updateTime = function() {
		var date = new Date(currts * 1000);
		var hours = date.getHours();
		if(hours == 12) {
			range = 'PM';
		} else if(hours >= 13 && hours <= 23) {
			hours = hours - 12;
			range = 'PM';
		} else {
			range = 'AM';	
		}
		var time = {};
		time.hours = hours;
		time.minutes = GabeUtil.padding(date.getMinutes(), 2);
		time.seconds = GabeUtil.padding(date.getSeconds(), 2);
		time.dayofweek = GabeUtil.getDayOfWeek(date.getDay());
		$(element).html("<span class='dayofweek'>" + time.dayofweek + "</span><br />" + time.hours + ":" + time.minutes + ":" + time.seconds + " " + range);
		currts++;
	}
	
	var intid = setInterval(updateTime, 1000);
	updateTime();
	
}

Webzone.initAdminArea = function() {
	$(document).ready(function(event) {
		
		document.title = "VianetWebzone System";
		
		/*
		if(window.location.href.indexOf("admin/clientsinvoices.php?userid=") > 0) {
			jQuery.each($("table.admindatatable img"), function(i, val) {
				if($(val).attr('src').indexOf('edit') > 0) {
					$(val).after('.');
				}											
			});	
		}
		*/
		
		$(".numericfield").keyup(function(event) {
			this.value = this.value.replace(/[^0-9]+/ig, '');
		});
		
		$("img:eq(0)").hide();
		
		if($(".navbar").length > 0) {
			$(".navbar").html("<div id='timesheetbuttondiv'></div>" + $(".navbar").html());
			//$("#timesheetbuttondiv").html("COMING SOON!!!");
			Webzone.getTimesheetButton({});
		}
		
		if($(".navbar").length > 0) {
			var tzdiv = document.createElement("div");
			tzdiv.id = "timezonesdiv";
			tzdiv.style.right = '40px';
			tzdiv.style.top = '10px';
			tzdiv.style.position = "absolute";
			tzdiv.style.border = '#FFFFFF 2px solid';
			document.body.appendChild(tzdiv);
			tzdiv.innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="950" height="60" id="TimezoneClocks" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="wmode" value="opaque" /><param name="movie" value="http://websitelogin.org/flash/TimezoneClocks.swf?ts=' + Math.random() + '" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />	<embed src="http://websitelogin.org/flash/TimezoneClocks.swf?ts=<?php echo mktime(); ?>" quality="high" bgcolor="#ffffff" width="950" height="60" name="TimezoneClocks" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="opaque" /></object>';
			//Webzone.getTimezoneClocks();
		}
							   
		
		
		if($(".datepickerfld").length > 0) {
			$(".datepickerfld").datepicker({
				dateFormat : 'yy-mm-dd'
			});
		}
		
		if($("input[name='customfield[11]']:eq(0)").val() && $("input[name='customfield[12]']:eq(0)").val()) {
			// EDIT CLIENT PROFILE AREA IN ADMIN	
			var userurl = '/vwz-files/webzone/client.php?getclientinfo=1&userid=' + $("select[name='userid']:eq(0) option:selected").val();
			var useropt = {};
			useropt.onLoad = function(response) {
				$("input[name='customfield[11]']:eq(0)").after("<span> " + response.sflead_name + "</span>");
				$("input[name='customfield[12]']:eq(0)").after("<span> " + response.sfcamp_name + "</span>");
			}
			GabeUtil.ajaxRequest('get', userurl, useropt, 'json');
			
		}
		
		// if this is within the clientprofileiframe in manage clients
		if(window.name == 'clientprofileiframe') {
			document.body.style.marginLeft = '-180px';
			document.body.style.marginTop = '-200px';
			document.body.removeChild(document.getElementById('timezonesdiv'));
		}
		
	});
	
}

Webzone.getTimesheetButton = function(option) {
	if(!option) {
		option = {};	
	}
	var url = '/vwz-files/webzone/employee.php?timesheetdiv=1';
	jQuery.get(url, {}, function(response) {
		$("#timesheetbuttondiv").html(response);
		
		$(".timeinbutton").click(function(event) {
			var adminid = $(this).metadata().adminid;
			var conf = confirm("You are about to time-in.  Continue?");
			if(!conf) {
				return false;		
			}
			var url = '/vwz-files/webzone/employee.php?emptimein=1&adminid=' + adminid;
			jQuery.get(url, {}, function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					Webzone.getTimesheetButton({});
				}
			}, 'json');
		});
		
		$(".timeoutbutton").click(function(event) {
			var adminid = $(this).metadata().adminid;
			var conf = confirm("You are about to time-out.  Continue?");
			if(!conf) {
				return false;		
			}
			var url = '/vwz-files/webzone/employee.php?emptimeout=1&adminid=' + adminid;
			jQuery.get(url, {}, function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					Webzone.getTimesheetButton({});
				}
			}, 'json');
		});
		
	});
}

Webzone.displayUpcomingWebinars = function(result, option) {
	
	var currentId = option.userid;
	var query = '';
	
	if(option.hidehistory) {
		query += "&hidehistory=1";
	}
	
	if(!option.registerCallback) {
		option.registerCallback = function(response) {}	
	}
	
	if(option.isadmin) {
		query += '&isadmin=1';	
	}
	
	//var clientUrl = "<?php echo WEBZONE_URI; ?>modules/admin/manage_clients/getclients.php?getclientinfo=1&userid=" + currentId + query;
	var clientUrl = "/vwz-files/webzone/client.php?getupcomingwebinars=1&userid=" + currentId + query;
	//alert(clientUrl);
		
	jQuery.get(clientUrl, {}, function(response) {
	
		$("#" + result).html(response);
		
		Webzone.renderGradientButton("#" + result + " .btnSubmitGreen", "btngreen");
		Webzone.renderGradientButton("#" + result + " .btnSubmitGray", "btngray");
		
		if(!option.hidehistory) {
			$(".deleteclientwebinar").click(function(event) {
				var conf = confirm("Would you like to delete this webinar from your list of upcoming webinars?");
				if(!conf) {
					return false;	
				}
				GabeUtil.screenDimLoading(true);
				var userid = $(this).metadata().userid;
				var webinarid = $(this).metadata().webinarid;
				var url = '/vwz-files/webzone/client.php?deleteclientwebinar=1&userid=' + userid + '&webinarid=' + webinarid;
				var getopt = {};
				getopt.onOK = function(response) {
					Webzone.displayUpcomingWebinars(result, option);
					GabeUtil.screenDimLoading(false);
				}
				getopt.onERROR = function(response) {
					GabeUtil.screenDimLoading(false);
				}
				GabeUtil.ajaxRequest('get', url, getopt, 'json');
			});
		}
		
		$(".resendwebinarlink").click(function(response) {
			GabeUtil.screenDimLoading(true);
			var webinarid = $(this).metadata().webinarid;
			var userid = $(this).metadata().userid;
			var webid = $(this).metadata().id;
			var url = '/vwz-files/webzone/register.php?resendlink=1&webid=' + webid + '&userid=' + userid;
			
			jQuery.get(url, {}, function(response) {
				GabeUtil.screenDimLoading(false);
				alert(response.message);
			}, 'json');
			/*
			jQuery.get(url, {}, function(response) {
				alert(response);
			});*/
			
		});
		
		$(".viewwebinarnowbutton").click(function(event) {
			var id = $(this).metadata().id;
			//var win = window.open('/webinars/' + webinar + '.swf', 'viewwebinarwindow', 'width=600,height=500');
			var win = window.open('/webinars/viewwebinar.php?f=' + id, 'viewwebinarwindow', 'width=600,height=500');
			win.focus();
		});
		
		$(".webinarbutton").mouseup(function(event) {
			event.preventDefault();
		});
		
		$(".webinarbutton").click(function(event) {
			event.preventDefault();
		});
		
		// Don't really need this anymore because the user clicks on the list item rather than the radio button
		$(".webinarbutton").mousedown(function(event) {
			
			if($(this).attr('checked')) {
				$(this).attr('checked', false);
			} else {
				$(this).attr('checked', true);
				var maxwebinars = parseInt($("#initialwebinarsfield").val());
				var numcounted = parseInt($("#numcountedfld").val());
				var allowed = maxwebinars - numcounted;
				/*
				alert(numcounted);
				alert(allowed);
				*/
				var currentselected = $(".webinarbutton:checked").length;
				/*
				if(currentselected > maxwebinars) {
					alert("This client is only set to have " + maxwebinars + " webinars.");
					$(this).attr('checked', false);
				}
				*/
				if(currentselected > allowed) {
					alert("This account can only schedule upto " + allowed + " more webinars.");
					$(this).attr('checked', false);	
				}
			}
			
		});
		
		var currentwebinars = '';
		$(".webinarTimes li").click(function(event) {
			
			var input = $("input", $(this));
			//alert($(input).attr('checked'));
			var element = this;
			
			jQuery.each( $("li", $(this).parent()), function(i, val) {	
				if(val != element) {
					$(val).removeClass('selectedWebinarTime');
				}
			});
			
			//$(this).toggleClass('selectedWebinarTime');
			if($(this).hasClass('selectedWebinarTime')) {
				
				$(this).removeClass('selectedWebinarTime');
				$(input).attr('checked', false);
				
			} else {
				
				$(this).addClass('selectedWebinarTime');
				$(input).attr('checked', true);
				
				var maxwebinars = parseInt($("#initialwebinarsfield").val()) + parseInt($("#extrawebinarsfield").val());
				var numcounted = parseInt($("#numcountedfld").val());
				var allowed = maxwebinars - numcounted;
				if(allowed < 0) {
					allowed = 0;	
				}
				var currentselected = $(".webinarbutton:checked").length;
				
				/*
				alert(currentselected);
				alert(numcounted);
				alert(allowed);
				*/
				
				if(currentselected > maxwebinars) {
					$(this).removeClass('selectedWebinarTime');
					alert("This client is only set to have " + maxwebinars + " webinars.");
					$(input).attr('checked', false);
				}
				if(currentselected > allowed) {
					$(this).removeClass('selectedWebinarTime');
					alert("This account can only schedule upto " + allowed + " more webinars.");
					$(input).attr('checked', false);	
				}
				
			}
			
			
			
			currentwebinars = '<ul>';
			jQuery.each($(".webinarbutton:checked"), function(i, val) {
				var name = $(val).metadata().name;
				var startdatetext = $(val).metadata().startdatetext;
				var startdatets = $(val).metadata().startdatets;
				currentwebinars += '<li class="{startdatets:\'' + startdatets + '\'}"><strong>' + name + '</strong><br />' + startdatetext + '</li>';
			});
			currentwebinars += '</ul>';
			$("#selectedwebinarsdiv").html(currentwebinars);

			jQuery.each($("#selectedwebinarsdiv li"), function(i, val) {
				var thists = $(val).metadata().startdatets;
				var foundbefore = false;
				jQuery.each($("#selectedwebinarsdiv li"), function(i2, val2) {
												
					if(val2 == val || foundbefore == true) {
						return;	
					}
					var thists2 = $(val2).metadata().startdatets;
					if(thists < thists2) {
						$(val2).before(val);
						foundbefore = true;
					}
				});
			});
			
		});
		
		$("#allowwebinarsform").ajaxForm({
			success : function(response) {
				alert(response.message);
			}, dataType : 'json'	 
		});
		
		$("#webinarregisterform").submit(function(event) {
			GabeUtil.screenDimLoading(true, "<div class='popupinfo'><center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Please wait while we register the selected webinars.</center></div>");
			return false;
		});
		
		$("#webinarregisterform").ajaxForm({
			
			success:function(response) {
				GabeUtil.screenDimLoading(false);
				//alert(response);
				//$("#clientmapdivwrapper").html(response);
				alert(response.message);
				// reload webinars
				if(response.status == 'OK') {
					//loadClientWebinars();
					option.registerCallback(response);
					Webzone.displayUpcomingWebinars(result, option);
				}
				//selectClient(currentClient, '.clientSelectButton');
			}, 
			dataType:'json'
		});
		
		// make this selectedwebinarswrapper scroll
		if(window.location) {
			
			var mydiv = document.getElementById('selectedwebinarswrapper');
			var mytable = document.getElementById('upcomingwebinarstable');
			var origtableheight = 0;
			var lasttableheight = 0;
			var lastscrolltop = 0;
			
			$(window).scroll(function(event) {

				if(origtableheight == 0 && lasttableheight != 0) {
					origtableheight = lasttableheight;
				}
				
				var tableheight = mytable.scrollHeight;				
				var scrolltop = $(document).scrollTop();
				var mypos = GabeUtil.getAbsolutePos(document.getElementById('selectedwebinarswrapper'));
				var tablepos = GabeUtil.getAbsolutePos(document.getElementById('upcomingwebinarstable'));
				
				lasttableheight = tableheight;
				
				if(scrolltop > mypos.y && mypos.y > 0) {
					//alert(mydiv.style.paddingTop);
					//alert(tableheight);
					var diff = scrolltop - mypos.y;
					if(tableheight == origtableheight && (mypos.y + mydiv.scrollHeight + 100) < tablepos.y + tableheight) {
						mydiv.style.paddingTop = diff + 'px';
					} else if(scrolltop < lastscrolltop && scrolltop < (tablepos.y + tableheight)) {
						mydiv.style.paddingTop = diff + 'px';
					}
				}
				
				lastscrolltop = scrolltop;
				
			});		
		}
		
		
	});
}

Webzone.fckeditors = {};

Webzone.initCampaignEditor = function(instance, opt) {
	
	if(!opt) {
		opt = {};	
	}

	var myname = instance.Name;
	var mydiv = Webzone.fckeditors[myname];
	var parent = $(mydiv).metadata().parent;
	parent = $(mydiv).closest(parent);
	
	/*
	var getSavedEmailCamps = function(instance, selectedsubject, parent) {

		if(!selectedsubject) {
			selectedsubject = '';
		}
		if(!parent) {
			parent = document.body;
		}
		
		var deleteEmailCamp = function(id) {
			var conf = confirm("Do you want to delete this email campaign?");
			if(!conf) {
				return false;
			}
			var url = '/vwz-files/webzone/marketing.php?deleteecamp=1&id=' + id;
			var opt = {};
			opt.onOK = function(response) {
				getSavedEmailCamps('');
			}
			GabeUtil.ajaxRequest('get', url, opt, 'json');
		}
		
		var url = '/vwz-files/webzone/marketing.php?getsavedemailcamps=1&userid=<?php echo $userid; ?>&subject=' + encodeURIComponent(selectedsubject);
		var opt = {};
		opt.onLoad = function(response) {
			//alert(response);
			
			$(".savedemailcampsdiv", $(parent)).html(response);
			$(".savedemailcampsdiv select:eq(0)", $(parent)).change(function(event) {
				var id = $(".savedemailcampsdiv select:eq(0) option:selected", $(parent)).val();
				if(id == 'none') {
					return;
				}
				var html = $("#" + id).html();
				html = GabeUtil.htmlDecode(decodeURIComponent(html));
				instance.SetHTML(html);
				$("input[name='tmpecampsubject']", $(parent)).val($(".savedemailcampsdiv select:eq(0) option:selected", $(parent)).html());
			});
			
			$("input[name='deleteemailcamp']", $(parent)).click(function(event) {
				var id = $(".savedemailcampsdiv select:eq(0) option:selected", $(parent)).val() + '';
				id = id.replace(/[^0-9]+/g, '');
				if(id) {
					deleteEmailCamp(id);
				}
			});
		}
		GabeUtil.ajaxRequest('get', url, opt);
	}
	*/
	
	asktotal = false;
	
	var submitCampaign = function() {
	
		var emailhtml = instance.GetHTML();
		var emailsubject = $("input[name='tmpsubject']:eq(0)", $(parent));
		if(emailsubject.val() == '' || emailhtml.length < 20) {
			alert("Please enter the subject and content.");
			if(asktotal == true) {
				$(parent).show();
				$(parent).next().remove();
			}
			asktotal = false;
			return;
		}
		
		$("form input[name='name']", $(parent)).val(emailsubject.val());
		$("form textarea[name='content']", $(parent)).val(emailhtml);
		
		$("form", $(parent)).ajaxSubmit({
			beforeSubmit : function(odata, oform, opt) {
				GabeUtil.screenDimLoading(true);
			},
			dataType : 'json', 
			success : function(response) {
				//alert(response);
				GabeUtil.screenDimLoading(false);
				alert(response.message);
				if(response.status == 'OK') {
					//getSavedEmailCamps(instance, emailsubject.value, parent);
					if(opt.saveCallback) {
						opt.saveCallback(response);
					}
				}
			},
			//Added to get around the "Dim not going away" issue in the marketing platform
			complete : function() {
				//alert("Complete");
				window.location.reload();
			}
		});
		
	}
	
	// getSavedEmailCamps(instance, '', parent);
	// alert('...');
	$("input[name='savecampaignbutton']", $(parent)).click(function(event) {
		if($("form input[name='status']", $(parent)).val() == '') {
			$("form input[name='status']", $(parent)).val('new');
		}
		submitCampaign();
	});
	
	$("input[name='reviewcampaignbutton']", $(parent)).click(function(event) {
																	  
		asktotal = true;
		
		$("form input[name='status']", $(parent)).val('review');
		if($("form input[name='category']", $(parent)).val() == 'email') {
			
			var allowed = $(this).metadata().allowed;
			$(parent).hide();
			
			/*
			var totalhtml = "<div id='campaigntotalwrapper'><input type='hidden' id='campaigntotaldropdownlink' /><h3>How many emails?</h3><p>Send this out to how many emails?</p><center><span id='campaigntotaldiv'>Loading...</span><br /><input type='button' value='Submit and Continue' class='submittotal' /></center></div>";
			$(parent).after(totalhtml);
			document.getElementById('campaigntotaldropdownlink').focus();
			*/
			
			var totalhtml = "<div id='campaigntotalwrapper'><input type='hidden' id='campaigntotaldropdownlink' /><h3>How many emails?<br />You currently have <span id='allowedemailsspan'></span> emails available!</h3><p>Send this out to how many emails?</p><center><span id='campaigntotaldiv'>Loading...</span><br /><input type='button' value='Submit and Continue' class='submittotal' /><input type='button' value='Cancel and Go Back' class='canceltotal' /></center></div>";
			
			var loadafter = false;
			
			if(GabeUtil.scDimLoading) {
				if(GabeUtil.scDimLoading.style.display == 'none') {
					GabeUtil.screenDimLoading(true, totalhtml);
				} else {
					loadafter = true;		
				}
			} else {
				// scdimloading is not even loaded, so load it!
				GabeUtil.screenDimLoading(true, totalhtml);
			}
			
			if(loadafter) {
				$(parent).after(totalhtml);
				document.getElementById('campaigntotaldropdownlink').focus();		
			}
		
			$("#allowedemailsspan").html(allowed);
			Webzone.getCampaignTotalDropdown($("form input[name='userid']", $(parent)).val(), "#campaigntotaldiv");
			$(".submittotal", $("#campaigntotalwrapper")).click(function(event) {
				$("form input[name='total']", $(parent)).val($("select:eq(0) option:selected", $("#campaigntotalwrapper")).val());
				submitCampaign();
			});
			$(".canceltotal", $("#campaigntotalwrapper")).click(function(event) {
				$(parent).show();
				if(!loadafter) {
					// close scdimloading
					GabeUtil.screenDimLoading(false);
				} else {
					$(parent).after('');
				}
			});
		} else {
			submitCampaign();
		}
	});
	
	$("input[name='submitcampaignbutton']", $(parent)).click(function(event) {
		$("form input[name='status']", $(parent)).val('processing');
		submitCampaign();
	});

}

Webzone.getCampaignTotalDropdown = function(userid, selector) {
	var url = '/vwz-files/webzone/marketing.php?getcampaigntotaldropdown=1&userid=' + userid + '&ts=' + Math.random();
	//alert(url);
	var opt = {};
	opt.onLoad = function(response) {
		$(selector).html(response);
	}
	GabeUtil.ajaxRequest('get', url, opt);
}

Webzone.createEditor = function(element) {
	var val = element;
	var ecampdiv = document.getElementById(val.id);
	var ecampf = new FCKeditor(val.id);
	ecampf.BasePath = '/vwz-files/controls/fckeditor/';
	ecampf.Height = '250';
	ecampf.Config['LinkBrowser'] = false;
	ecampf.Config['ImageBrowser'] = false;
	ecampf.Config['FlashBrowser'] = false;
	ecampf.Config['ImageUpload'] = false;
	ecampf.Config['FlashUpload'] = false;
	ecampf.Value = ecampdiv.innerHTML;
	ecampdiv.innerHTML = ecampf.CreateHtml();
	Webzone.fckeditors[val.id] = ecampdiv;
}

Webzone.registerCampaignSearch = function(formid, resultid, option) {
	
	if(!option) {
		option = {};	
	}
	
	var getemails = null;
	var getemailsopt = {};
	
	getemailsopt.successCallback = function(response) {
		
		$("#" + resultid + " .editcampaign").click(function(event) {
			
			GabeUtil.screenDimLoading(true);
			var id = $(this).metadata().id;
			var category = $(this).metadata().category;
			var url = '/vwz-files/webzone/marketing.php?editcampaign=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			opt.onLoad = function(response) {
				GabeUtil.screenDimLoading(false);
				var div = GabeUtil.screenDimLoading(true, response);
				var divid = 'edit' + category + 'campaignform';
				//alert(divid);
				Webzone.createEditor(document.getElementById(divid));
				Webzone.registerCloseButton(response);
				
				// getlinkspinnerform
				var url = '/vwz-files/webzone/marketing.php?getlinkspinnerform=1&campaignid=' + id + '&ts=' + Math.random();
				var opt = {};
				opt.onLoad = function(response) {
					$("#camplinkspinnerdiv").html(response);
					$("#camplinkspinnerform").ajaxForm({
						beforeSubmit : function(odata, oform, opt) {
							$("#camplinkspinnerformresult").html("Retrieving new link...");
							$("#camplinkspinnerform input[type='submit']").attr('disabled', true);
						},
						success : function(response) {
							$("#camplinkspinnerform input[type='submit']").attr('disabled', false);
							$("#camplinkspinnerformresult").html(response);
						}
					});
				}
				GabeUtil.ajaxRequest('get', url, opt); 
			}
			GabeUtil.ajaxRequest('get', url, opt); 
		});
		
		$("#" + resultid + " .viewcampaign").click(function(event) {
			var id = $(this).metadata().id;
			var category = $(this).metadata().category;
			var url = '/vwz-files/webzone/marketing.php?viewcampaign=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			opt.onLoad = function(response) {
				var div = GabeUtil.screenDimLoading(true, response);
				Webzone.registerCloseButton(response);
				
				if(document.getElementById('viewcampaigndiv')) {
					//alert($("#viewcampaigndiv").html());
					/*
					$("#viewcamp-html").hide();
					$("ul li a", $(div)).click(function(event) {
						event.preventDefault();
						$("#viewcamp-preview").hide();
						$("#viewcamp-html").hide();
						$($(this).attr('href')).show();
					});
					*/
					
					//$("#viewcampaigndiv").tabs();
					
					$("#viewcampaigndiv #viewcamp-html textarea").click(function(event) {
						this.select();															 
					});
					
				}
			}
			GabeUtil.ajaxRequest('get', url, opt); 
		});
		
		$("#" + resultid + " .deletecampaign").click(function(event) {
			var conf = confirm('Would you like to delete this?');
			if(!conf) {
				return;
			}
			var id = $(this).metadata().id;
			var category = $(this).metadata().category;
			var url = '/vwz-files/webzone/marketing.php?deletecampaign=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			opt.onOK = function(response) {
				getemails();
				if(option.deleteCallback) {
					option.deleteCallback(response);
				}
			}
			GabeUtil.ajaxRequest('get', url, opt, 'json'); 
		});
		
		$("#" + resultid + " .processcampaign").click(function(event) {
			var conf = confirm('You are about to mark this campaign for processing.  Continue?');
			if(!conf) {
				return;
			}
			var id = $(this).metadata().campaignid;
			var url = '/vwz-files/webzone/marketing.php?processcampaign=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			opt.onOK = function(response) {
				if(option.processCallback) {
					option.processCallback(response);
				}
			}
			GabeUtil.ajaxRequest('get', url, opt, 'json'); 
		});
		
		$("#" + resultid + " .updatereport").click(function(event) {
			var id = $(this).metadata().campaignid;
			var url = '/vwz-files/webzone/marketing.php?updatecampaignreport=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			opt.onLoad = function(response) {
				GabeUtil.screenDimLoading(true, response);
				Webzone.registerCloseButton(response);
				$("#updatecampreportform").ajaxForm({
					dataType : 'json',
					beforeSubmit : function(odata, oform, opt) {
						GabeUtil.screenDimLoading(true);	
					},
					success : function(response) {
						GabeUtil.screenDimLoading(false);
						alert(response.message);
						if(response.status == 'OK') {
							if(option.updateCallback) {
								option.updateCallback(response);
							}	
						}
					}
				});
			}
			GabeUtil.ajaxRequest('get', url, opt); 
		});
		
		$("#" + resultid + " .viewreport").click(function(event) {
			var id = $(this).metadata().campaignid;
			var url = '/vwz-files/webzone/marketing.php?viewcampaignreport=1&campaignid=' + id + '&ts=' + Math.random();
			//alert(url);
			var opt = {};
			GabeUtil.screenDimLoading(true);
			opt.onLoad = function(response) {
				GabeUtil.screenDimLoading(true, response);
				Webzone.registerCloseButton(response);
			}
			GabeUtil.ajaxRequest('get', url, opt); 
		});
		
		
		$("#" + resultid + " .assigntouserbtn").click(function(event) {
			var html = "<form method='post' action='/vwz-files/webzone/marketing.php' id='assigntouserform'><h3 align='center'>Assign this Campaign to a Marketing User</h3><p align='center'>Please select the Marketing User below.<br />This campaign will be assigned to the chosen user and its status will be set to <strong>BROADCASTING</strong>.<br />" + $("#assigntouserformtmp").html() + "</p></form>";
			var userid = $(this).metadata().userid;
			var hostingid = $(this).metadata().hostingid;
			var campaignid = $(this).metadata().campaignid;
			// alert(campaignid);
			GabeUtil.screenDimLoading(true, html);
			
			$("#assigntouserform input[name='userid']").val(userid);
			$("#assigntouserform input[name='hostingid']").val(hostingid);
			$("#assigntouserform input[name='campaignid']").val(campaignid);
			
			$("#assigntouserform").ajaxForm({
				beforeSubmit : function(odata, oform, opt) {
					// alert("This feature coming soon!");
					// return false;
					return true;
				},
				dataType : 'json',
				success : function(response) {
					alert(response.message);
					if(response.status == 'OK') {
						GabeUtil.screenDimLoading(false);
						option.assignToUserCallback(response);
					}
				}
			});
			var closeopt = {};
			closeopt.closeCallback = function(response) {};
			closeopt.parent = GabeUtil.scDimLoading;
			Webzone.registerCloseButton(response, closeopt);
		});
		
		$(".viewclientscout").click(function(event) {
			Webzone.displayClientScoutDiv(this);
		});
		
	}
	
	getemails = GabeUtil.registerActiveSearchForm(formid, resultid, getemailsopt);
	return getemails;

}


Webzone.getEmailCampPanel = function(uid, divid, opt) {
}

Webzone.initClientareahome = function(uid, callback) {
	
	$(document).ready(function(event) {
										
		// check if viewftoinfopanel is on
		if(document.getElementById('viewftpinfopanel')) {
			$("#viewftpinfopanel").click(function(event) {
				$(this).closest("p").next().toggle('normal');									  
			});
		}
		
		// check if the upgradepackageform form is there
		// alert('...');
		if(document.getElementById('upgradepackageform')) {
			var pid = $("#upgradepackageform input[name='pid']").val();
			$("#upgradepackageform").ajaxForm({
				beforeSubmit : function(odata, oform, opt) {
					var conf = confirm("Would you like to change your version to the selected version?");
					if(!conf) {
						return false;	
					}
					GabeUtil.screenDimLoading(true);
				},
				dataType : 'json',
				success : function(response) {
					if(response.status != 'OK') {
						// error occurred	
						alert(response.message);
						GabeUtil.screenDimLoading(false);
					} else {
						var myhtml = '<div class="popupinfo"><center><form method="post" action="/clientarea.php?action=productdetails">' + response.message + '<br /><input type="hidden" name="id" value="' + pid + '" /><input type="submit" name="submitbutton" value="Click here to Continue" /></form></center></div>';
						GabeUtil.screenDimLoading(true, myhtml);
					}
				}
			});
		}
		
		// LOAD TIMEZONESDIV HERE
		if(document.getElementById('timezonesdiv')) {
			Webzone.getTimezoneClocks({calibrate : true});
		}
		
		// check if we are in the clientareahome page
		if(document.getElementById('clientmapdivwrapper')) {
			// if so, then dim the page (since we need to check their agreed status)
			GabeUtil.screenDimLoading(true);
			//alert('1');
		}
		
		if(!callback) {
			callback = function(response) {
				
			}	
		}
		
		if(!uid) {
			uid = '';
		}
		
		var userurl = '/vwz-files/webzone/client.php?getclientinfo=1&userid=' + uid;
		
		/*
		if(document.getElementById('settingshomebutton')) {
			$("#settingshomebutton").mouseover(function(event) {
															
			});
		}
		*/
		
		// check if cpanelhomebutton exists
		if(document.getElementById('cpanelhomebutton')) {
			$("#cpanelhomebutton").click(function(event) {
				var ipaddress = $(this).metadata().ipaddress;
				var username = $(this).metadata().username;
				var password = $(this).metadata().password;
				var url = "http://" + ipaddress + ":2082/login/?user=" + username + "&pass=" + password;
				var cpanelwin = Webzone.openControlWindow(url);
			});
		}
		
		// check if settingshomebutton exists
		if(document.getElementById('settingshomebutton')) {
			$("#settingshomebutton").click(function(event) {
				var pid = $(this).metadata().pid;
				var url = "/vwzclientarea.php?action=wpdashboard";
				var cpanelwin = Webzone.openControlWindow(url);
			});
		}
		
		// check if websitepreview links are up
		if(document.getElementById('websitepreview-admin')) {
			
			$("#websitepreview-open").click(function(event) {
				var url = $(this).metadata().url;
				window.open(url, '_blank');									
			});
			
			$("#websitepreview-reload").click(function(event) {
				document.getElementById('websitePreviewFrame').src = document.getElementById('websitePreviewFrame').src;
			});
			
			$("#websitepreview-home").click(function(event) {
				var url = $(this).metadata().url;
				window.open(url, "_blank");
				//$("#websitePreviewFrame").attr('src', url);
			});
			
			$("#websitepreview-admin").click(function(event) {
				document.getElementById('websitepreview-adminform').submit();								
			});
		}
		
		// register uninstall package button
		if(document.getElementById('uninstallWebsitePackage')) {
	
			$("#uninstallWebsitePackage").click(function(event) {
			
				var conf = confirm("Do you want to uninstall your current website package?\nThis action will delete all of your files and data in this web package.");
				if(!conf) {
					return;
				}
				var pid = $(this).metadata().hostingid;
				var command = $(this).metadata().command;
				var app = $(this).metadata().app;
				var appType = $(this).metadata().appType;
				var password = $(this).metadata().password;
				var username = $(this).metadata().username;
				var ipaddress = $(this).metadata().ipaddress;
				var hostingid = $(this).metadata().hostingid;
				var server = $(this).metadata().server;
				var domain = $(this).metadata().domain;
				
				var processReply = function(response) {
					if(response.status == 'OK') {
						//window.location = 'http://' + ipaddress + '/~' + username + '/wp-admin/?whmcsID=1';
						GabeUtil.screenDimLoading(true, "<div class='infopopup'><form method='post' action='clientarea.php?action=productdetails' target='_top'><input type='hidden' name='id' value='" + pid + "' />Your web package was successfully uninstalled!<br /><input type='submit' name='submitnow' value='Click here to refresh this page' /></form></div>");
					}					
				}
				
				GabeUtil.screenDimLoading(true, "<div class='popupinfo'><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />We are now uninstalling your web program.<br />This may take a moment.<br />Please wait.</div>");
				var url = 'http://www.websitelogin.org/vwzclientarea.php?action=addpackagecommand&command=' + command + '&app_type=' + appType + '&app=' + app + '&username=' + username + '&password=' + password + '&hostingid=' + hostingid + '&server=' + server + '&ipaddress=' + ipaddress + '&domain=' + domain;
				//url += '&format=json&callback=?&c=?';
				//alert(url);
				try {
					jQuery.get(url, {}, processReply, 'json')
				} catch(e) {
				}
	
			});
		}
	
		// register the togglebuttons
		$("h2 img.togglebutton").click(function(event) {
			$(this).closest("h2").next().toggle('normal');
			$(this).attr('src', $(this).attr('src') == '/vwz-files/image/icon/del.png' ? '/vwz-files/image/icon/add.png' : '/vwz-files/image/icon/del.png');
		});
		
		// CHAT WITH LIVE HELP
		if(document.getElementById('chatwithlivehelp')) {
			$("#chatwithlivehelp").click(function(event) {								  
				var win = window.open('http://livechat.vianetwebzone.com/livehelp.php?eo=1&department=20&serversession=1&pingtimes=15', 'chatwithlivehelp', 'width=550,height=600');
				win.focus();								  
			});
			
		}
		
		//alert(userurl);
		
		jQuery.get(userurl, {}, function(response) {
			
			if(response.id) {
				
				Webzone.clientareaUser = response;
				var user = Webzone.clientareaUser;
				var client = Webzone.clientareaUser;
				
				if(user.total_sessions > 0) {
					$("#mycoaching-tab").css('display', 'inline');
				}
				
				// START CHECK IF THE CLIENT IS IN THE MYCOACHINGPAGE PAGE
				if(document.getElementById('mycoachingpage')) {
					
					if(client.total_sessions > 0) {
						var option = {};
						$("input[name='userid']", $("#coachsessionhistoryform")).val(Webzone.clientareaUser.id);
						getallcoaching = Webzone.registerCoachSessionHistorySearch("coachsessionhistoryform", "coachsessionhistoryresult", {});
						getallcoaching();
						$("#coachingdiv").show();
					}
					
					if(client.scheduled_sessions > 0) {
						
						var sessoption = option;
						if(!sessoption) {
							sessoption = {};	
						}
						sessoption.endSessionCallback = function(response) {
							//alert("Refreshing upcoming sessions list");
							if(getallcoaching) {
								getallcoaching();	
							}
						}
						Webzone.displayNextSessionClient(Webzone.clientareaUser.id, sessoption);
					}	
				}
				// END CHECK IF THE CLIENT IS IN THE MYCOACHINGPAGE PAGE
				
				//check their toa/agreed status if salesfloor_id is set
				var triggerToaButtons = function() {
					var clicked = $("#toacheckbox", $(GabeUtil.scDimLoading)).attr('checked');
					if(clicked) {
						$("#toaagree", $(GabeUtil.scDimLoading)).attr('disabled', false);
						$("#toaclosewindow", $(GabeUtil.scDimLoading)).attr('disabled', true);
					} else {
						$("#toaagree", $(GabeUtil.scDimLoading)).attr('disabled', true);
						$("#toaclosewindow", $(GabeUtil.scDimLoading)).attr('disabled', false);	
					}
				}
				
				if(	user.salesfloor_id 
				   	&& user.agreed != 'on' 
					&& document.getElementById('clientmapdivwrapper') 
					&& document.getElementById('displaytoa')) 
				{
					// DISPLAY TERMS OF SERVICE
					if($("#displaytoa").val() == 'yes') {
						GabeUtil.screenDimLoading(true, "<div class='popupinfo' id='toapopupdiv'>" + $("#termsofagreementdoc").html() + "</div>");
						GabeUtil.scDimLoading.style.top = '50px';
						$("#toaclosewindow", $(GabeUtil.scDimLoading)).click(function(event) {
							window.location = '/logout.php';									
						});
						
						$("#toaagree", $(GabeUtil.scDimLoading)).click(function(event) {
							var url = '/vwz-files/webzone/client.php?toaagree=1&userid=' + user.id;
							var toaopt = {};
							toaopt.onOK = function(response) {
								GabeUtil.screenDimLoading(false);
							}
							GabeUtil.ajaxRequest('get', url, toaopt, 'json');
							
						});
						$("#toacheckbox", $(GabeUtil.scDimLoading)).click(function(event) {
							//alert('1');
							triggerToaButtons();						 
						});
					} else {
						GabeUtil.screenDimLoading(false);
					}
				} else {
					GabeUtil.screenDimLoading(false);					
				}

				// If user is a coach and current page is clientarea.php, go to /coaching/admin.php
				if(user.usertype == 'coach' && window.location.pathname.indexOf("/clientarea.php") > -1 && window.location.search.length < 3) {
					window.location = '/coaching/admin.php';	
				}
				
				// START CLIENT ACCOUNT HOMEPAGE CODE
				
				if(document.getElementById('clientmapdivwrapper')) {
					$("#coachingdiv").hide();
					$("#webinarsdiv").hide();
					
					if($("#webinarsdonestatfld").length > 0) {
						
						var getall = null;
						
						if(client.total_sessions > 0) {
							var option = {};
							$("input[name='userid']", $("#coachsessionhistoryform")).val(Webzone.clientareaUser.id);
							getall = Webzone.registerCoachSessionHistorySearch("coachsessionhistoryform", "coachsessionhistoryresult", {});
							getall();
							$("#coachingdiv").show();
						}
						
						
						if(client.scheduled_sessions > 0) {
							// Disabled because now we will only display the nextsession in the MyCoaching page
							/*
							var sessoption = option;
							if(!sessoption) {
								sessoption = {};	
							}
							sessoption.endSessionCallback = function(response) {
								if(getall) {
									getall();	
								}
							}
							Webzone.displayNextSessionClient(Webzone.clientareaUser.id, sessoption);
							*/
							$("#coachschedulingbuttons").hide();	
						}
						
					}
					
					if($("#clientwebinarsform").length > 0) {
						
						if(client.total_webinars > 0) {
							$("input[name='userid']", $("#clientwebinarsform")).val(Webzone.clientareaUser.id);
							var getwebsopt = {};
							getwebsopt.successCallback = function(response) {
								$(".deleteclientwebinar").click(function(event) {
									var conf = confirm("Would you like to delete this webinar from your list of webinars?");
									if(!conf) {
										return false;	
									}
									GabeUtil.screenDimLoading(true);
									var userid = $(this).metadata().userid;
									var webinarid = $(this).metadata().webinarid;
									var url = '/vwz-files/webzone/client.php?deleteclientwebinar=1&userid=' + userid + '&webinarid=' + webinarid;
									var getopt = {};
									getopt.onOK = function(response) {
										getwebs();
										GabeUtil.screenDimLoading(false);
									}
									getopt.onERROR = function(response) {
										GabeUtil.screenDimLoading(false);
									}
									GabeUtil.ajaxRequest('get', url, getopt, 'json');
								});		
							}
							var getwebs = Webzone.registerClientWebinarsSearch("clientwebinarsform", "clientwebinarsresult", getwebsopt);
							getwebs();
							
							var option = {};
							option.userid = Webzone.clientareaUser.id;
							option.hidehistory = 1;
							option.registerCallback = function(response) {
								getwebs();
								Webzone.displayUpcomingWebinars('upcomingwebinarsdiv', option);
								$("#upcomingwebinarsdiv").hide();
								// reload the clientmap
								Webzone.loadClientMap();
							}
							Webzone.displayUpcomingWebinars('upcomingwebinarsdiv', option);
							
							$("#webinarsdiv").show();
						}
						
					}
	
					// END CLIENT ACCOUNT HOMEPAGE CODE
					 
					//alert(Webzone.clientareaUser.firstname);
			
					$("#sessionsdonestatfld").html(user.done_sessions);
					$("#sessionstotalstatfld").html(user.total_sessions);
					
					$("#webinarsdonestatfld").html(user.done_webinars);
					$("#webinarstotalstatfld").html(user.total_webinars);
					
					// display register to coaching button, if webinars more than 3
					if($("#clientareasignupcoaching").length > 0 && parseInt(user.taken_webinars) > 1) {
						$("#clientareasignupcoaching").show();
						$("#clientareasignupcoaching input").click(function(event) {
							var url = '/vwz-files/webzone/timedriverscheduler.php?linktype=coachscheduling';
							var win = window.open(url, 'coachschedulingwindow', '');
							win.focus();
						});
						$("#clientareasignupcoachingdisabled").hide();
					}
					
					// display webinar instructions area if the client has not yet taken any webinars
					if($("#webinarinstructionsdiv").length > 0 && parseInt(user.registered_webinars) < 1) {
						$("#webinarinstructionsdiv").show();
					}
					
					// LOAD THE CLIENTMAP HERE
					if(document.getElementById('clientmapdivwrapper')) {
						Webzone.loadClientMap();
					}
				}
				
				if($("#clientButtonsWrapper").length > 0) {
					if(user.usertype == 'coach') {
						var url = '/vwz-files/webzone/client.php?getclientbuttons=1&userid=' + user.id + '&usertype=' + user.usertype;
						//alert(url);
						jQuery.get(url, {}, function(response) {
							$("#clientButtonsWrapper").html(response);
							$("#clientButtonsWrapper").show();
						});
					} else {
						$("#clientButtonsWrapper").show();
					}
				}
			
				// CALLBACK FUNCTION OF INITCLIENTAREAHOME
				callback(response);
			}
			
		}, 'json');
		
		if($("#displayupcomingwebinars").length > 0) {
			$("#upcomingwebinarsdiv").hide();
			$("#displayupcomingwebinars").click(function(event) {
				//event.preventDefault();	
				$("#upcomingwebinarsdiv").toggle('normal');
			});
		}
	
	});
	
}

Webzone.loadClientMap = function() {
	
	var user = Webzone.clientareaUser;
	var client = Webzone.clientareaUser;
	
	if(!user.id) {
		return;
	}
	
	// LOAD CLIENTMAP DIV
	if(	document.getElementById('clientmapdiv') 
		//&& parseInt(user.total_sessions) > 0
		//&& parseInt(user.total_webinars) > 0
		) {
    
    //LISA EDIT - ^^^^^^^^^^^^^^^^^^^ REMOVED THE NEED FOR INITIAL SESSIONS AND INITIAL WEBINARS 
		
		$("#clientmapdivwrapper").show();
		var cmapurl = '/vwz-files/webzone/client.php?getclientmap=1&clientid=' + user.id;
		//alert(cmapurl);
		jQuery.get(cmapurl, {}, function(response) {
										 
			//alert(response);
			$("#clientmapdiv").html(response);
			
			if(document.getElementById('browserinfo-safari')) {
				$(".clientmaptable").css('padding-top', '31px');
			}
			
			// open the mywebinarsarea upcomingwebinarsdiv
			$("a[href='/clientarea.php#mywebinarsarea'], a[href='#mywebinarsarea']").click(function(event) {
				$("#upcomingwebinarsdiv").show('normal');
			});
			
			$(".moreinfolink").click(function(event) {
				var targetdiv = $(this).metadata().targetdiv;
				$("#" + targetdiv).toggle('normal');
			});
			
			$(".skipcheckpoint").click(function(event) {
				
				var clientid = $(this).metadata().clientid;
				var stepid = $(this).metadata().stepid;
				var pointid = $(this).metadata().pointid;
				var laststepid = $(this).metadata().laststepid;
				var url = '/vwz-files/webzone/clientmap.php?skipclientpoint=1&clientid=' + clientid + '&pointid=' + pointid + '&stepid=' + stepid + '&laststepid=' + laststepid;
				//alert(url);
				
				var conf = confirm("Would you like to skip this checkpoint and move it to the next step?");
				if(!conf) {
					return false;		
				}
				
				var skipopt = {};
				skipopt.onOK = function(response) {
					Webzone.loadClientMap();
				}
				GabeUtil.ajaxRequest('get', url, skipopt, 'json');
			});
			
			$(".checkcheckpoint").click(function(event) {
				/*
				var conf = confirm("Continue?");
				
				if(!conf) {
					return false;		
				}
				*/
				var clientid = $(this).metadata().clientid;
				var stepid = $(this).metadata().stepid;
				var pointid = $(this).metadata().pointid;
				/*
				// moved to /vwz-files/webzone/pointlink.php
				var url = '/vwz-files/webzone/clientmap.php?addclientpoint=1&clientid=' + clientid + '&pointid=' + pointid + '&stepid=' + stepid;
				*/
				var url = '/vwz-files/webzone/pointlink.php?pointid=' + pointid + '&clientid=' + clientid + '&stepid=' + stepid;
				var pointwindow = window.open(url, '_blank', 'width=750,height=500,scrollbars=yes');
				pointwindow.focus();
				/*
				GabeUtil.screenDimLoading(true);
				setTimeout(function() {
									Webzone.loadClientMap();
									GabeUtil.screenDimLoading(false);
									}, 4000);
				*/
				/*
				jQuery.get(url, {}, function(response) {
					alert(response.message);
					
				}, 'json');
				*/
			});
			
			$(".upcomingstepcell").mouseover(function(event) {
				var previewtable = $(this).metadata().previewtable;
				$(".steppointstable").hide();
				$("#" + previewtable).show();
			});
			
			$(".upcomingstepcell").mouseout(function(event) {
				$(".steppointstable").hide();
				$("#currentsteppointstable").show();
			});
			
			//$(".")
			
			Webzone.renderGradientButton("#clientmapdiv .btnSubmitGreen", "btngreensm");
			Webzone.renderGradientButton("#clientmapdiv .btnSubmitBlue", "btnbluesm");
			
			
		});
	}
	
}

Webzone.registerViewSalesClient = function(selector) {
	$(selector).click(function(event) {
		event.preventDefault();
		var clientid = $(this).metadata().id;
		var url = '/vwz-files/webzone/salesclient.php?clientid=' + clientid;
		if($(this).metadata().opentab) {
			var win = window.open(url, '_blank');
		} else {
			var win = window.open(url, 'salesfloorClientWindow', 'width=750,height=600,scrollbars=yes');
		}
		win.focus();
	});	
}

Webzone.initClientareaAccountHome = function(uid, callback) {
	Webzone.initClientareahome(false);
}

Webzone.displayAdminPasswordPanel = function(title, option) {
	if(!option.info) {
		option.info = '';
	}
	var html = "<div class='popupinfo'><h3>" + title + "</h3><p>" + option.info + "</p>Please enter an administrator password to continue:<br /><input type='password' name='adminpass' id='adminpasswordfld' /><br /><input type='button' value='Submit' id='submitadminpassbtn' /><br /><input type='button' class='closewindow' value='Cancel and Close' /></div>";
	GabeUtil.screenDimLoading(true, html);
	Webzone.registerCloseButton(html, {});
	$("#submitadminpassbtn").click(function(event) {
		var url = '/vwz-files/webzone/client.php?checkadminpassword=1&adminpass=' + $("#adminpasswordfld").val();
		jQuery.post(url, {}, function(response) {
			if(response.status == 'ERROR') {
				alert(response.message);
			} else {
				GabeUtil.screenDimLoading(false);
				// Submit the form, finally :D!
				option.successCallback(response);
			}
		}, 'json');
	});	
	
}

Webzone.rescheduleSession = function(oldsess, newsess, opt) {
	
	if(!opt) {
		opt = {};
	}
	
	if(!opt.successCallback) {
		opt.successCallback = function(response) {
			
		}	
	}
	
	GabeUtil.screenDimLoading(true, "<center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Please wait while we reschedule this session.</center>");
	
	var oldsessid = oldsess.metadata().sessionid;
	var newsessid = newsess.metadata().sessionid;
	
	var reschedurl = '/vwz-files/coaching/schedcalendar.php?assigntocoach=1&reschedule=1&sessionid[]=' + newsessid + '&cancel_id=' + oldsessid;
	jQuery.get(reschedurl, {}, function(response) {
		//alert(response);
		//return;
		response = eval("(" + response + ")");
		if(response.status == 'OK') {
			clearGetCache();
			alert(response.message);
			Webzone.reschedSession = null;
			var month = $(currentDateCell).metadata().month;
			var year = $(currentDateCell).metadata().year;
			var day = $(currentDateCell).metadata().day;
			//alert(year + ' ' + month + ' ' + day);
			loadCoachDateSessions(month, year, day);
			getScheduleCalendar(month, year, day);
			Webzone.displaySessionInfoDiv(newsess, {});
			opt.successCallback(response);
		} else {
			alert("ERROR : " + response.message);		
		}
		GabeUtil.screenDimLoading(false);
	});
	
	/*
	var cancelid = null;
	var cancelurl = '/vwz-files/coaching/schedcalendar.php?cancelsession=1&sessionid=' + oldsessid;
	jQuery.get(cancelurl, {}, function(response) {
									   	if(response.status != 'OK') {
											// An error occurred.
											alert("Error cancelling: " + response.message);
											GabeUtil.screenDimLoading(false);
										} else {
											cancelid = response.data;
											reschedule();	
										}
									   }, 'json')
	var reschedule = function() {
		var query = '';
		if(opt.forceresched) {
			// if reschedule fails, reschedule the cancelled session for the coach!
			query = "&forceresched=1";	
		}
		var reschedurl = '/vwz-files/coaching/schedcalendar.php?assigntocoach=1&reschedule=1&sessionid[]=' + newsessid + '&cancel_id=' + cancelid + query;
		jQuery.get(reschedurl, {}, function(response) {
											//alert(response);
											//return;
											response = eval("(" + response + ")");
											if(response.status == 'OK') {
												alert(response.message);
												Webzone.reschedSession = null;
												var month = $(currentDateCell).metadata().month;
												var year = $(currentDateCell).metadata().year;
												var day = $(currentDateCell).metadata().day;
												//alert(year + ' ' + month + ' ' + day);
												loadCoachDateSessions(month, year, day);
												getScheduleCalendar(month, year, day);
												Webzone.displaySessionInfoDiv(newsess, {});
												opt.successCallback(response);
											} else {
												alert("ERROR : " + response.message);		
											}
											GabeUtil.screenDimLoading(false);
											});
	}
	
	*/
	
}

Webzone.secondsToTime = function(secsbef) {
	//secsbef = Math.abs(-45000);
	var days = Math.floor( secsbef / 86400 );
	var seconds = secsbef % 86400;
	var hours = Math.floor( seconds / 3600 );
	var seconds = secsbef % 3600;
	var minutes = Math.floor( seconds / 60 );
	var seconds = seconds % 60;
	
	var time = 	{
					'days' : parseInt(days),
					'hours' : parseInt(hours),
					'minutes' : parseInt(minutes),
					'seconds' : parseInt(seconds)
				}
	return time;
}

Webzone.countdownWidget = function(secs) {
	var times = Webzone.secondsToTime(secs);
	times.hours = GabeUtil.padding(times.hours + '', 2);
	times.minutes = GabeUtil.padding(times.minutes + '', 2);
	times.seconds = GabeUtil.padding(times.seconds + '', 2);
	var html = "<table class='countdowntable' cellspacing='0' cellpadding='0'><tbody><tr><td><div class='timeelementday'><span class='timeelement'>" + times.days + "</span>Day(s)</div></td><td><div class='timeelementhours'><table cellspacing='0' cellpadding='0'><tr><td><span class='timeelement'>" + times.hours + "</span>Hour(s)</td><td><span class='timeelement'>:</span></td><td><span class='timeelement'>" + times.minutes + "</span>Min(s)</td><td><span class='timeelement'>:</span></td><td><span class='timeelement'>" + times.seconds + "</span>Sec(s)</td></tr></table></div></td></tr></tbody></table>";
	return html;
}

Webzone.checkConnection = function() {
	var url = 'http://www.websitelogin.org/vwz-files/image/rpan_tr.gif?ts=' + Math.random();	
	var img = new Image();
	img.src = url;
	img.onerror = function(event) {
		// alert("Your internet connection has been lost.  Please check your internet connection, reload the page, or restart your browser.");
		return;
	}
}

Webzone.checkNextSession = function(element, callback, option) {
	
	Webzone.checkConnection();
	
	//alert(callback);
	if(!option) {
		option = {};
	}
	
	if(option.withouthosting) {
		option.without_hosting = option.withouthosting;	
	}
	
	var query = '';
		   
	if(option.userid) {
		/*
		alert(option.userid);
		alert(option.withouthosting);
		alert(option.hostingid);
		*/
		if(!option.without_hosting) {
			option.without_hosting = 0;	
		}
		query = 'userid=' + option.userid + '&without_hosting=' + option.without_hosting + '&hostingid=' + option.hostingid;
	}
	
	if(option.coachid) {
		//alert(option.coachid);	
		query = 'coachid=' + option.coachid;
	}
	
	if(option.currentSessionId) {
		query += '&currentSessionId=' + option.currentSessionId;
	}
	
	var rand = Math.random();
	//var url = '/vwz-files/coaching/schedcalendar.php?ts=' + rand;
	var url = '/vwz-files/coaching/schedcalendar.php?checknextsession=1&' + query + '&ts=' + rand;
	option.checknextsession = 1;
	option.intCallback = '';
	
	/*
	for(var key in option) {
		alert(key + " " + option[key]);	
	}
	*/
	
	jQuery.post(url, {}, function(response) {	
									  
		//alert(response.client_firstname);
		//alert(response.firstname);
		//alert(response.session_date);
		//alert(response.newsessionjson);
		
		//alert(response);
		//response = eval("(" + response + ")");
		callback(response);
		
	}, 'json');
	
	/*
	jQuery.get(url, {}, function(response) {
		//var resp = eval("(" + response + ")");
		//alert(response);
		//response = response.replace(/\\n/g, '.....');
		//response = eval("(" + response + ")");
		alert(response);
	});*/

}

Webzone.onclickSessionReportForm = function(element, userid, usertype, origoption, countdownIntId) {
		
	var option = {};
	option.editCallback = function(resp) {
		clearInterval(countdownIntId);
		if(usertype == 'coach') {
			loadCoachSummary();
			loadCoachSessionHistory();
		}
		if(usertype == 'coach') {
			// Comment this one out because it's already called in loadCoachSummary functionss
			// Webzone.displayNextSession(userid);
		} else {
			Webzone.displayNextSessionClient(userid, origoption);
		}
		var callbacks = Webzone.submitSessionReportCallback;
		for(var i = 0; i < callbacks.length; i++) {
			callbacks[i]();
		}
	}
	
	// if errors out, call editcallback also
	option.errorCallback = function(response) {
		GabeUtil.screenDimLoading(false);
		option.editCallback(response);
	}
	
	option.usertype = usertype;
	if(option.usertype == 'coach') {
		option.userid = origoption.coachid;
	} else {
		option.userid = userid;
	}
	Webzone.displaySessionReportForm($(element), option);
	
};

Webzone.processNextSession = function(response, option) {
	
	var usertype = option.usertype;
	var userid = option.userid;
	var currentSessionId = option.currentSessionId;
	
	if(!option.intCallback) {
		option.intCallback = function(intid) {}	
	}
	
	if(!option.endSessionCallback) {
		option.endSessionCallback = function(response) {
				
		}
	}
	
	var origoption = option;
	
	var intCallback = option.intCallback;
	var sessionid = $("#nextsessioninfo").metadata().sessionid;
	
	//alert(sessionid);
	
	//alert(usertype);
	var countdownIntId = null;
	var checkCallback;
	
	$(".coachprofilebutton").click(function(event) {
		Webzone.displayCoachProfile($(this));
	});
	
	if($("img.tooltipElement").length > 0) {
		$("img.tooltipElement").tooltip({
			bodyHandler : function() {
				return "<img src='" + $(this).attr('src') + "' />";
			},
			top : -100
		});
	}
	
	$(".submitbutton", $("#initiatesessionform")).click(function(event) {
		$("#initiatesessionform").ajaxSubmit({
			beforeSubmit : function(adata, aform, option) {
				var conf = confirm("You are about to initiate this session.  Continue?");
				if(!conf) {
					return false;	
				}
				return true;
			},
			success : function(response) {
				//alert(response);
				response = eval("(" + response + ")");
				if(response.status == 'OK') {
					Webzone.checkNextSession($("#nextsessioninfo"), checkCallback, origoption);
				} else {
					alert(response.message);
					Webzone.checkNextSession($("#nextsessioninfo"), checkCallback, origoption);
				}
			}
		});
	});
	
	$("#initiatesessionform").submit(function(event) {
		event.preventDefault();										  
	});
	
	$(".submitbutton", $("#endsessionform")).click(function(event) {
		$("#endsessionform").ajaxSubmit({
			beforeSubmit : function(adata, aform, option) {
				var conf = confirm("You are about to END this session.  Continue?");
				if(!conf) {
					return false;	
				}
				$("#endsessionform .submitbutton").attr('disabled', true);
				return true;
			},
			success : function(response) {
				alert(response.message);
				$("#endsessionform .submitbutton").attr('disabled', false);
				if(response.status == 'OK') {
					Webzone.checkNextSession($("#nextsessioninfo"), checkCallback, origoption);
					origoption.endSessionCallback(response);
				}
			},
			dataType : 'json'
		});
	});
		
	$(".viewclientscoutbutton", $("#nextsessiondiv")).click(function(event) {
		Webzone.displayClientScoutDiv($(this), {});
	});
	
	$($(".getsessionreportform"), $("#nextsessiondiv")).click(function(event) {
		Webzone.onclickSessionReportForm(this, userid, usertype, origoption, countdownIntId);													   
	});
	
	/*
	$($(".viewsessionreportform"), $("#nextsessiondiv")).click(function(event) {
		var option = {};
		option.editCallback = function(resp) {
			clearInterval(countdownIntId);
			if(usertype == 'coach') {
				Webzone.displayNextSession(userid);
			} else {
				Webzone.displayNextSessionClient(userid);
			}
			
		}
		option.userid = userid;
		option.usertype = usertype;
		Webzone.displaySessionReportView($(this), option);
	});
	*/
	
	var secsbef = parseInt($("#secondsbeforesession").val());
	$("#countdowndiv").html(Webzone.countdownWidget(Math.abs(secsbef)));
	
	var interval = 0;
	
	checkCallback = function(response) {
		var nextsession = response;
		//alert(nextsession.id == sessionid);
		//alert(nextsession.session_startdate);
		//alert(response.client_firstname);
		//alert(nextsession.session_startdate);
		if(nextsession.id != sessionid) {
			clearInterval(countdownIntId);
			if(usertype == 'coach') {
				loadCoachSummary();
				loadCoachSessionHistory();
			}
			if(usertype == 'coach') {
				// Comment this one out because it's already called in loadCoachSummary functionss
				// Webzone.displayNextSession(userid);
			} else {
				Webzone.displayNextSessionClient(userid, origoption);
			}
			var callbacks = Webzone.submitSessionReportCallback;
			for(var i = 0; i < callbacks.length; i++) {
				callbacks[i]();
			}
		}
		
		if(nextsession.session_startdate) {
			// Session has been initiated
			
			// Hide session control button
			$("#nextsessiondiv div.controlbuttons").hide();
			
			if($("#sessionstartdatefld").val() == '') {
				// Set this session's seconds timer to and increment from this point on!
				secsbef = nextsession.duration;
				$("#sessionstartdatefld").val(nextsession.session_startdate);
				$("#timeleftinfo").html("This session is now ongoing!");
				$("#sessionpindiv").hide();
				$("#endsessiondiv").show();
			}
			
			if(nextsession.session_enddate) {
				var autoendtext = '';
				if(nextsession.autoend == 'yes') {
					autoendtext = '<br />(Automatically, after going beyond 1h and 15m)';
				}
				clearInterval(countdownIntId);
				$("#countdowndiv").html(Webzone.countdownWidget(nextsession.duration));
				$("#endsessiondiv").hide();
				$("#timeleftinfo").html("This session has ended " + autoendtext + "!<br />Submit the Summary Report to complete it!");
				$("#sessionpindiv").hide();
				$("#countdowndiv td").css('color', '#003366');
				$("#timeleftinfo").css('color', '#003366');
				if(nextsession.session_status == 'done') {
					$("#nextsessionviewreportdiv").show();
				} else {
					$("#nextsessionreportdiv").show();
					if(usertype != 'coach') {
						Webzone.onclickSessionReportForm($("#nextsessiondiv .getsessionreportform:first"), userid, 'client', origoption, countdownIntId);
					}
				}
			}
		} else {
			// Display session control buttons because this session has not yet ended
			$("#nextsessiondiv div.controlbuttons").show();	
		}	
	}

	Webzone.checkNextSession($("#nextsessioninfo"), checkCallback, origoption);
	
	countdownIntId = setInterval(function() {
		
		$("#countdowndiv").html(Webzone.countdownWidget(Math.abs(secsbef)));
		
		interval = secsbef % 5;
		if(interval == 0) {
			// alert(countdownIntId);
			// Check the status of this ongoing session
			//alert(userid);
			if(option.coachid == 13) {
				// alert(origoption.currentSessionId);
			}
			Webzone.checkNextSession($("#nextsessioninfo"), checkCallback, origoption);
		}
		
		if($("#sessionstartdatefld").val() == '') {
			// Waiting for session to begin!
			
			secsbef--;
			
			if(secsbef < 300) {
				
				$("#timeleftinfo").html("Countdown to this Session");
				
				$("#countdowndiv td").css('color', '#990000');
				$("#timeleftinfo").css('color', '#990000');
				
				if(secsbef < 0) {
					if(usertype == 'client') {
						$("#timeleftinfo").css('color', '#307B00');
						$("#timeleftinfo").html("Enter the SESSION PIN below to begin the session.<br />The pin will be provided to you by your coach.<br />");
					} else {
						$("#timeleftinfo").html("Please begin your session!<br />Initiate this session by asking your client to enter the SESSION PIN below.");
					}
					
				} else if(secsbef < 60) {
					$("#timeleftinfo").html("You are less than a minute away from your session.<br />Initiate this session by asking your client to enter the SESSION PIN below.");
				}
					
			}
			
			
		} else {
			// The session is already ongoing!
			$("#countdowndiv td").css('color', '#006600');
			$("#timeleftinfo").css('color', '#006600');
			secsbef++;
		}
	}, 1000);	
	
	intCallback(countdownIntId);
	
	// returns process to end the countdown
	return function() {
		clearInterval(countdownIntId);	
	}
	//alert('process called!');
}

Webzone.displayNextSession = function(coachid, opt) {
	if(!opt) {
		opt = {};
	}
	if(!opt.intCallback) {
		opt.intCallback = function(intid) {}	
	}
	if(!opt.coachTimezone) {
		opt.coachTimezone = '';	
	}
	if(!opt.endSessionCallback) {
		opt.endSessionCallback = function(response) {
		}	
	}
	var query = '&ts=' + Math.random();
	query += '&coachtimezone=' + opt.coachTimezone;
	var url = '/vwz-files/coaching/schedcalendar.php?getnextsession=1&coachid=' + coachid + query;
	
	jQuery.get(url, {}, function(response) {
		
		// display just in case hidden by missed session button
		// $("#nextsessiondivcontainer").show();
		
		if(response == 'NONE' || response == '') {
			return;	
		}
		$("#nextsessiondivcontainer").html(response);
		
		var currentSessionId = $("#nextsessioninfo").metadata().sessionid;
		var option = {};
		option.usertype = 'coach';
		option.coachid = coachid;
		option.intCallback = opt.intCallback;
		option.currentSessionId = currentSessionId;
		option.endSessionCallback = opt.endSessionCallback;
		var endCountdown = Webzone.processNextSession(response, option);
		Webzone.registerCancelControlButton();
		
		// shift sessions forward one week button
		var shiftopt = {};
		if(opt.shiftCloseCallback) {
			shiftopt.closeCallback = function(response) {
				opt.shiftCloseCallback(response);	
			}	
		}
		Webzone.registerShiftSessionsButton("#nextsessiondivcontainer .moveSession:first", shiftopt);
		
		// mark missed session button
		if(document.getElementById('markmissedsessionbtn')) {
			$("#nextsessiondivcontainer #markmissedsessionbtn, #nextsessiondivcontainer #markmissedreschedsessionbtn").click(function(event) {
				var resched = $(this).metadata().resched;
				var query = '';
				var conf = false;
				if(!resched) {
					conf = confirm("Are you sure you would like to mark this session as a MISSED SESSION?\nThis means that the client completely loses this session and you will be compensated.");
				} else {
					// for reschedule
					query += '&missedresched=1';
					conf = confirm("Are you sure you would like to mark this session as a MISSED SESSION for RESCHEDULE?\nThe client is currently not available and this session may be moved to another date and time.");
				}
				
				if(!conf) {
					return false;	
				}
				var misopt = {};
				misopt.onOK = function(response) {
					alert("Please wait while your timer refreshes.");
					// hide as it refreshes
					endCountdown();
					opt.endSessionCallback();
					$("#nextsessiondivcontainer").html('');
					Webzone.displayNextSession(coachid, opt);
				}
				var sessionid = $(this).metadata().sessionid;
				var misurl = '/vwz-files/coaching/schedcalendar.php?markmissedsession=1&sessionid=' + sessionid + query;
				GabeUtil.ajaxRequest('get', misurl, misopt, 'json');
			});
		}
		
	});
	
}

Webzone.displayNextSessionClient = function(userid, option) {
	
	var query = '&ts=' + Math.random();
	
	if(!option) {
		option = {};
	}
	
	if(!option.withouthosting) {
		option.withouthosting = '';	
	}
	
	if(!option.hostingid) {
		option.hostingid = '';	
	}
	
	if(option.withouthosting) {
		query += '&without_hosting=1';	
	}
	
	if(option.hostingid) {
		query += '&hostingid=' + option.hostingid;	
	}
	
	var url = '/vwz-files/coaching/schedcalendar.php?getnextsessionclient=1&userid=' + userid + query;
	//alert(url);
	
	jQuery.get(url, {}, function(response) {	
		if(response == 'NONE' || response == '') {
			$("#nextsessiondivcontainer").html("");
			return;	
		}
		$("#nextsessiondivcontainer").html(response);
		$("form input[name='sessionpin']").click(function(event) {
			$(this).val(this.value.replace(/[^0-9]+/ig, ''));
		});
		
		var opt = {};
		opt.usertype = 'client';
		opt.userid = userid;
		opt.withouthosting = option.withouthosting;
		opt.hostingid = option.hostingid;
		opt.endSessionCallback = function(response) {
			option.endSessionCallback(response);
		}
		
		//{ 'usertype' : 'client', 'userid' : userid }
		Webzone.processNextSession(response, opt);
		//Webzone.renderGradientField($("#nextsessiondivcontainer input[type='text']"));
	});	
	
}

Webzone.displayCoachProfile = function(element, option) {
	
	if(!option) {
		option = {};	
	}
	
	if(!option.loadCallback) {
		option.loadCallback = function(response) {}
	}
	
	var coachid = $(element).metadata().coachid;
	var date = new Date();
	var url = '/vwz-files/coaching/schedcalendar.php?getcoachprofile=1&coachid=' + coachid + '&ts=' + date.getTime();
	jQuery.get(url, {}, function(response) {		
		GabeUtil.screenDimLoading(true, response);
		option.loadCallback(response);
		Webzone.registerCloseButton(response, option);
	});
	
}

Webzone.processSessionReportForm = function(response, option) {
	
	if(!option) {
		option = {};
	}
	
	if(!option.editCallback) {
		option.editCallback = function(response) {};	
	}
	
	if(!option.errorCallback) {
		option.errorCallback = function(response) {};
	}
	
	
	$("#sessionreportform").ajaxForm({
		beforeSubmit : function(adata, aform, aoption) {
			if($("#submitnewsessionreport").length > 0) {
				var conf = confirm("You are about to submit your report for this session.\nWould you like to continue?");
				if(!conf) {
					return false;
				}
			}
			$("#sessionreportform input[type='submit']").attr('disabled', true);
			return true;
		},
		success : function(response) {
			//alert(response);
			//return;
			$("#sessionreportform input[type='submit']").attr('disabled', false);
			response = eval("(" + response + ")");
			alert(response.message);
			if(response.status == 'OK') {
				//GabeUtil.screenDimLoading(false);
				if($("#submitnewsessionreport").length > 0) {
					GabeUtil.screenDimLoading(false);
				}
				if($("#adminnotesfld").length > 0) {
					Webzone.displaySessionReportView(option.element, option);
				}
				option.editCallback(response);
			} else {
				option.errorCallback(response);	
			}
		}
	});
	
	if($("#submitnewsessionreport").length > 0) {
		
		var chooseStarRating = function(starimg) {
			
			var thisstar = starimg;
			var parent = $(thisstar).closest(".starrating");
			var ratingfld = $("input[name='rating[]']", $(parent));
			var ratingtext = $(".ratingtext", $(parent));
			var stopit = false;
			jQuery.each($("img", $(parent)), function(i, val) {
				var rating = i + 1;
				var rtext = "Average";
				var rtextcolor = "#6497e3";
				if(stopit == false) {
					if(val != thisstar) {
						$(val).attr('src', '/vwz-files/image/gstar.png');	
					} else if(val == thisstar) {
						$(val).attr('src', '/vwz-files/image/gstar.png');	
						$(ratingfld).val(rating);
						//alert($(ratingfld).val())
						stopit = true;
						
						if(rating >= 0 && rating <= 2) {
							rtext = "Bad";
							rtextcolor = "#ac1627";
						} else if(rating >= 3 && rating <= 4) {
							rtext = "Poor";
							rtextcolor = "#de5103";
						} else if(rating >= 5 && rating <= 6) {
							rtext = "Average";
							rtextcolor = "#2e40f3";
						} else if(rating >= 7 && rating <= 8) {
							rtext = "Good";
							rtextcolor = "#78f32e";
						} else if(rating > 8) {
							rtext = "Great!";
							rtextcolor = "#43ab05";
						}
						$(ratingtext).html(rtext);
						$(ratingtext).css("color", rtextcolor);
					}
				} else {
					$(val).attr('src', '/vwz-files/image/bstar.png');		
				}
			});
			
			var total = 0;
			var counter = 0;
			jQuery.each($("input[name='rating[]']"), function(i, val) {
				//alert(val);
				total += parseInt($(val).val());
				counter++;
			});
			//alert(total);
			$("#genratingfld").val(Math.ceil(total / counter));
			//alert($("#genratingfld").val());	
			
		}
		
		var starRatingFunction = function(event) {
			chooseStarRating(this);
		}
		
		$(".starrating img").click(starRatingFunction);
		
		$(".starrating img").mouseover(starRatingFunction);
		
		jQuery.each($(".starrating"), function(i, val) {
			var thispanel = val;
			var currrating = $("input[name='rating[]']", $(thispanel)).val();
			// alert(currrating);
			var imgsel = "img:eq(" + (currrating - 1) + ")";
			jQuery.each($("img", $(thispanel)), function(j, val2) {
				if(j == (currrating - 1)) {
					chooseStarRating(val2);
				}
			});
		});
		
	}
	
	$(".moreinfolink").click(function(event) {
		var descid = $(this).metadata().descdivid;
		//alert(descid);
		$("#" + descid).toggle();
	});
	
	$(".listItemDescription").hide();

}

Webzone.displaySessionReportForm = function(element, option) {
	
	GabeUtil.screenDimLoading(true);
	
	if(!option) {
		option = {};	
	}
	
	option.element = element;
	
	var sessionid = $(element).metadata().id;
	var sesslistid = $(element).metadata().sesslistid;
	var userid = option.userid;
	var usertype = option.usertype;
	
	var url = '/vwz-files/curriculum/index.php?getsessionreportform=1&userid=' + userid + '&sessionid=' + sessionid + '&usertype=' + usertype + '&sess_list_id=' + sesslistid;
	
	jQuery.get(url, {}, function(response) {
		GabeUtil.screenDimLoading(true, response, function(div) {
			$(div).addClass('sessionreportdiv');						   
		});
		
		Webzone.processSessionReportForm(response, option);
		Webzone.registerCloseButton(response, option);
	});
	
}

Webzone.displaySessionReportView = function(element, option) {
	
	if(!option) {
		option = {};	
	}
	
	option.element = element;
	
	var sessionid = $(element).metadata().id;
	var sesslistid = $(element).metadata().sesslistid;
	var userid = option.userid;
	var usertype = option.usertype;
	
	/*
	alert(userid);
	alert(usertype);
	*/
	
	//alert('enter');
	if(usertype == 'admin') {
		var url = '/vwz-files/curriculum/index.php?viewsessionreportadmin=1&session_id=' + sessionid + '&sessionid=' + sessionid + '&usertype=' + usertype;
	} else {
		var url = '/vwz-files/curriculum/index.php?viewsessionreportform=1&userid=' + userid + '&session_id=' + sessionid + '&sessionid=' + sessionid + '&usertype=' + usertype + '&sess_list_id=' + sesslistid;
	}
	
	jQuery.get(url, {}, function(response) {
		GabeUtil.screenDimLoading(true, response, function(div) {
			$(div).addClass('sessionreportdiv');		   
		});
		Webzone.processSessionReportForm(response, option);
		Webzone.registerCloseButton(response, option);
	});
}

Webzone.displayClientWebinarInfoDiv = function(element, option) {
	if(!option) {
		option = {};	
	}
	GabeUtil.screenDimLoading(true);
	var id = $(element).metadata().id;
	var url = '/vwz-files/webzone/client.php?clientwebinarinfo=1&cwid=' + id;
	jQuery.get(url, {}, function(response) {
		GabeUtil.screenDimLoading(true, response);
		$(".closeinfodiv").click(function(event) {
			GabeUtil.screenDimLoading(false);
		});
	});
}

Webzone.registerClientWebinarsSearch = function(form, result, option) {
	
	if(!option) {
		option = {};
	}
	
	var userid = Webzone.clientareaUser.id;
	var usertype = Webzone.clientareaUser.usertype;
	
	var func;
	
	var callback = {};
	
	callback.successCallback = function(response) {
		$(".clientwebinarinfobutton", $("#" + result)).click(function(event) {
			Webzone.displayClientWebinarInfoDiv($(this));
		});
		
		if(option.successCallback) {
			option.successCallback(response);
		}
	}
	
	func = GabeUtil.registerActiveSearchForm(form, result, callback);
	return func;
	
}

Webzone.registerCoachSessionHistorySearch = function(form, result, option) {
	
	if(!option) {
		option = {};
	}
	
	var userid = Webzone.clientareaUser.id;
	var usertype = Webzone.clientareaUser.usertype;
	
	var loadSessionReportForm;
	var func;
	
	var callback = {};
	
	callback.successCallback = function(response) {
		
		//alert(response);
		
		$(".clientsessioncell", $("#" + result)).click(function(event) {
			event.preventDefault();
			Webzone.displayClientScoutDiv($(this), {});
		});
		
		$(".coachprofilebutton", $("#" + result)).click(function(event) {
			event.preventDefault();
			Webzone.displayCoachProfile($(this), {});
		});
		
		$(".viewsessioninfobutton", $("#" + result)).click(function(event) {
			Webzone.displaySessionInfoDiv($(this), {});
		});
		
		$(".getsessionreportform", $("#" + result)).click(function(event) {
			var option = {};
			option.editCallback = function(resp) {
				func();
			}
			option.userid = userid;
			option.usertype = usertype;
			Webzone.displaySessionReportForm($(this), option);
		});
		
		$(".viewsessionreportform", $("#" + result)).click(function(event) {
			//alert(result);
			var option = {};
			option.editCallback = function(resp) {
			}
			option.closeCallback = function(resp) {
				func();	
			}
			option.userid = userid;
			option.usertype = usertype;
			Webzone.displaySessionReportView($(this), option);
		});
		
		if(option.loadCallback) {
			option.loadCallback(response);		
		}
	}
	
	
	
	func = GabeUtil.registerActiveSearchForm(form, result, callback);
	return func;
}

Webzone.displaySessionInfoDiv = function(element, option) {
	
	if(!option) {
		option = {};	
	}
	
	if(!option.editCallback) {
		option.editCallback = function(response) {}	
	}
	
	if(!option.loadCallback) {
		option.loadCallback = function(response) {}	
	}
	
	if(!option.cacheCallback) {
		option.cacheCallback = function(url) {
			return false;
		}	
	}
	
	var targetdiv = $(element).metadata().targetdiv;
	var sessionid = $(element).metadata().sessionid;
	var reschedule = $(element).metadata().reschedule;
	
	var query;
	if(reschedule) {
		query = '&reschedule=1';
	} else {
		GabeUtil.screenDimLoading(true);	
	}
	
	if(Webzone.clientareaUser.usertype == 'admin') {
		var url = "/vwz-files/coaching/schedcalendar.php?getsessioninfoadmin=1&sessionid=" + sessionid + query;
	} else {
		var url = "/vwz-files/coaching/schedcalendar.php?getsessioninfo=1&sessionid=" + sessionid + query;
	}
	
	var container;
	//alert(url);
	
	var processInfo = function(response) {
	
		if(targetdiv) {
			container = $("#" + targetdiv);
			$(container).html(response);
			$(".sessioninfodiv").css('margin', '0px auto');
			$(container).addClass('sessioninfodiv');
			
		} else {
			GabeUtil.screenDimLoading(true, response, function(container) {
				$(container).addClass('sessioninfodiv');				   
			});	
		}
		
		option.loadCallback(response);
		
		if(!Webzone.clientareaUser.usertype) {
			$("#coachnotesdiv").hide();
		}
		
		$(".reschedulebutton").click(function(event) {
			var sessionid = $(this).metadata().sessionid;
			var userid = $(this).metadata().userid;
			var coachid = $(this).metadata().coachid;
			Webzone.reschedSession = element;
			$(".sessioninfodivalert").html("<div class='reschedulealert'>You have chosen to reschedule this session.<br />Please click on a date/timeslot to replace this session.<br /><input type='button' value='Cancel Reschedule' class='cancelreschedule' /></div>");
			$(this).hide();
			
			$(".cancelreschedule").click(function(event) {
				Webzone.reschedSession = null;
				$(".sessioninfodivalert").html('');
				$(".reschedulebutton").show();
			});
		
		});
		
		$(".viewsesslistcheckpointsbutton").click(function(event) {
			event.preventDefault();
			Webzone.displayListCheckpoints($(this), { /*closeCallback : function(response) {
																				Webzone.displaySessionInfoDiv(element, option);	   
																			   }*/});
		});
	
		$("#editsessionform").ajaxForm({
			success : function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					if(Webzone.clientareaUser.usertype == 'admin') {
						Webzone.displaySessionInfoDiv(element, option);
					}
					option.editCallback(response);
				}
			},
			dataType : 'json'
		});
		
		var closeoption = {};
		if(targetdiv) {
			closeoption.closeCallback = function(response) {
				$("#" + targetdiv).html('');
			}	
		}
		Webzone.registerCloseButton(response, closeoption);
		
		$(".clientsessioncell, .viewclientscoutbutton", $(container)).click(function(event) {
			//event.preventDefault();
			Webzone.displayClientScoutDiv($(this), {});
		});
	
	}
	
	if(option.cacheCallback(url)) {
		processInfo(option.cacheCallback(url));
	} else {
		//alert('get info!');
		jQuery.get(url, {}, processInfo);
	}

}

Webzone.displayClientScoutDiv = function(element, option) {
	
	//alert(element);
	
	GabeUtil.screenDimLoading(true);
	if(!option) {
		option = {};	
	}	
	
	var userid = $(element).metadata().userid;
	var sessionid = $(element).metadata().sessionid;
	
	var url = '/vwz-files/webzone/client.php?viewclientscout=1&userid=' + userid + '&sessionid=' + sessionid;
	//alert(url);
	jQuery.get(url, {}, function(response) {
								 
		GabeUtil.screenDimLoading(true, response + "<center><input type='button' name='closeform' value='Close' /></center>", function(div) {
			$(div).addClass('clientscoutdivsched');				   
		});
		
		if(document.getElementById('viewclientcurricbtn' + userid)) {
			$("#viewclientcurricbtn" + userid).click(function(event) {
				ClientCurric.loadClientCurricPanel(userid, GabeUtil.scDimLoading.id, true);	
				GabeUtil.scDimLoading.style.width = '750px';
			});
		}
		
		$(".viewsessioninfobutton").click(function(event) {
			//event.preventDefault();
			Webzone.displaySessionInfoDiv($(this), {});
		});
		
		Webzone.registerCloseButton(response, option);
	});
	
}

Webzone.displayListCheckpoints = function(element, option) {
	GabeUtil.screenDimLoading(true);
	var sesslistid = $(element).metadata().sesslistid;
	var url = '/vwz-files/curriculum/index.php?getcheckpointslist=1&sess_list_id=' + sesslistid;
	jQuery.get(url, {}, function(response) {
		GabeUtil.screenDimLoading(true, response);
		Webzone.registerCloseButton(response, option);
	});
	
}

Webzone.registerCloseButton = function(response, option) {
	if(!option) {
		option = {};	
	}
	if(!option.closeCallback) {
		option.closeCallback = function(response) {
			
		}	
	}
	var parent = document.body;
	if(option.parent) {
		parent = option.parent;
	}
	$("input[name='closeform'], .closewindow, .closeform", $(parent)).click(function(event) {
		//alert('closing!');
		GabeUtil.screenDimLoading(false);
		option.closeCallback(response);
	});
	
}

var getSessionEditForm = function(sessionid, callback, option) {
	
	if(!callback) {
		callback = function(response) {
			
		}
	}
	
	if(!option) {
		option = '';	
	}
		
	var url = '/vwz-files/coaching/schedcalendar.php?sessionformadmin=1&sessionid=' + sessionid + option;
	jQuery.get(url, {}, function(response) {
								 
		scDim = GabeUtil.screenDimLoading(true, response);
		
		$(".hiddendivbutton").click(function(event) {
			$(this).next().toggle();									 
		}).next().hide();
		
		
		$("select[name='sess_list_id[]']").change(function(event) {
			var masterid = $("option:selected", $(this)).metadata().masterid;
			//alert(masterid);
			$(this).next().val(masterid);
		});
		
		$(".sessionformadmin").ajaxForm({
			dataType : 'json',
			success : function(response) {
				alert(response.message);
				if(response.status == 'OK') {
					//GabeUtil.screenDimLoading(false);
					getSessionEditForm(sessionid, callback);
				}
			}
		});
		
		$("input[name='cancelform']", $("#editsessiondiv")).click(function(event) {
			GabeUtil.screenDimLoading(false);
			//alert(callback);
			callback(response);
		});
		
		if($(".sessionformadmin").length == 0) {
			//$(".sessionAdminNotes").css('width', '400px');
		}
		
	});	
	
}

Webzone.processClientSessionsViewList = function(callback) {
	$(".viewsessionbutton").click(function(event) {
		var sessionid = $(this).metadata().sessionid;
		GabeUtil.screenDimLoading(true);
		var opt = "&viewonly=1";
		if($(this).hasClass('cancelledsession')) {
			opt += "&cancel=1";	
		}
		//alert(opt);
		getSessionEditForm(sessionid, function(response) {}, opt);
	});
}

Webzone.processClientSessionsList = function(callback, parent) {
	
	if(!parent) {
		parent = '*';	
	}
	
	if(!callback) {
		callback = function(response) {
				
		}	
	}
	
	if(Webzone.clientareaUser != null) {
		if(Webzone.clientareaUser.usertype) {
			var usertype = Webzone.clientareaUser.usertype;
		}
	}
	
	
	$(".editsessionbutton").click(function(event) {
		var sessionid = $(this).metadata().sessionid;
		GabeUtil.screenDimLoading(true);
		//alert(callback);
		getSessionEditForm(sessionid, callback);
	});
	
	$(".cancelSession").click(function(event) {
		var conf = confirm("Would you like to cancel this session?");
		if(!conf) {
			return false;
		}
		var id = $(this).metadata().id;
		//alert(id);
		var cancelUrl = "/vwz-files/coaching/schedcalendar.php?cancelsession=1&session_id=" + id;
		jQuery.get(cancelUrl, {}, function(response) {
			//alert(response.message);
			if(response.status == 'OK') {
				//getClientCoachInfo();
				callback(response);
			}
		}, 'json');
	});	
	
	$(".viewsessionreportform", $(parent)).click(function(event) {
		var thisbutton = this;
		var option = {};
		option.editCallback = function(response) {
			Webzone.displaySessionReportView($(thisbutton), option);
		}
		option.userid = '';
		option.usertype = usertype;
		Webzone.displaySessionReportView($(this), option);
	});
	
}

Webzone.getPreviewWindow = function() {
	return null;
	// return window.top.document.getElementById('websitePreviewFrame').contentWindow;
}

Webzone.applyTheme = function(theme) {
	GabeUtil.screenDimLoading(true, "<div class='popupinfo'><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Please wait while we change your website's theme.</div>");
	var tid = $(theme).metadata().tid;
	var pid = $(theme).metadata().pid;
	var tname = $(theme).metadata().tname;
	//alert($(theme).metadata().screenshot);
	var screenshot = unescape($(theme).metadata().screenshot);
	var url = 'vwzclientarea.php?action=changetheme&pid=' + pid + '&tid=' + tid + '&tname=' + tname;
	// alert(url);
	//alert(screenshot);
	$("#currThemeScreenshot").attr('src', screenshot);
	var processResponse = function(response) {
		GabeUtil.screenDimLoading(false);
		//alert(response);
		alert(response.message);
		if(response.status == 'OK') {
			var date = new Date();
			//window.top.document.getElementById('websitePreviewFrame').src = response.data + '/wp-admin/?whmcsID=1&whmcsLogin=1';
			var url = "/vwzclientarea.php?action=setuppackage&pid=" + pid + "&ts=" + date.getTime();
			//alert(url);
			opener.document.getElementById('websitePreviewFrame').src = opener.document.getElementById('websitePreviewFrame').src;
			opener.document.getElementById('websitePreviewFrame').focus();
		}
		GabeUtil.screenDimLoading(false);
	}
	jQuery.get(url, {}, processResponse, 'json');
	//jQuery.get(url, {}, processResponse);
}

Webzone.registerTimespref = function() {
	$(".addtimesprefbutton").click(function(event) {
		
		var divid = $(this).metadata().divid;
		var div = $("#" + divid);
		
		var hour = $("select[name='newpref-hour']", $(div)).val();
		var minute = $("select[name='newpref-minute']", $(div)).val();
		var range = $("select[name='newpref-range']", $(div)).val();
		
		var error = false;
		
		jQuery.each($("input[name='timespref[]']"), function(i, val) {
			
			var itimetext = $(val).val();
			itime = itimetext.split(' ');
			var irange = itime[1];
			itime = itime[0].split(':');
			var ihour = itime[0];
			var iminute = itime[1];
			
			var lihour = Webzone.longHour(ihour, irange);
			var lhour = Webzone.longHour(hour, range);
			
			var idate = new Date(2009, 1, 1, lihour, iminute, 0);
			var date = new Date(2009, 1, 1, lhour, minute, 0);
			
			var diff = Math.abs(idate.getTime() - date.getTime());
			diff = diff / 1000;
			if(diff < 3600) {
				alert("The time you want to add conflicts with " + itimetext + ".");
				error = true;
				return;
			}
			
		});
		
		if(error == true) {
			return false;		
		}
		
		var time = hour + ':' + minute + ' ' + range;
		$("span[name='timeslist']", $(div)).html($("span[name='timeslist']", $(div)).html() + "<span class='timespreftime'><input type='hidden' name='timespref[]' value='" + time + "' />" + time + " <input type='button' value='Delete' class='deletetime' onclick=\"Webzone.deleteTimespref(this)\" /></span>");
		
	});
}

Webzone.deleteTimespref = function(element) {
	var conf = confirm("Would you like to delete this time?");
	if(!conf) {
		return false;	
	}
	element.parentNode.parentNode.removeChild(element.parentNode);
}

Webzone.longHour = function(hour, range) {
	if(range == 'am') {
		if(hour >= 1 && hour <= 11) {
			hour = hour;
		} else {
			hour = 0;
		}
	} else {
		if(hour >= 1 && hour <= 11) {
			hour = 12 + parseInt(hour);
		} else {
			hour = hour;
		}
	}
	var hour = new String(hour);
	if(hour.length == 1) {
		return '0' + hour;
	}
	return hour;
}

Webzone.registerCustomCategoryArea = function(url) {
	
	var catUrl = url;
	var results = document.getElementById('vCategoriesDiv');
	var categoryType = $(results).metadata().categoryType;
	//alert(categoryType);
	
	var processResult = function(response) {
		$(results).html(response);
		$("input[name='editCustomCategory']").click(function(event) {
		
			var processGetEditForm = function(response) {
				GabeUtil.screenDimLoading(true, response);
				$("input[name='cancelCategory']").click(function(event) {
					GabeUtil.screenDimLoading(false);
				});
				$("#editCategoryForm").submit(function(event) {
					event.preventDefault();
					$(this).ajaxSubmit({
										success : function(response) {
											alert(response.message);
											GabeUtil.screenDimLoading(false);
											getCustomCategories();
										},
										dataType : 'json'
										});
				});
			}
			var id = $(this).metadata().id;
			var url = catUrl + "?id=" + id + "&action=getEditForm";
			jQuery.get(url, {}, processGetEditForm);
			
		});
		
		
		$("input[name='deleteCustomCategory']").click(function(event) {
			if(!confirm("Would you like to delete this category?")) {
				return;
			}
			var processDeleteCategory = function(response) {
				alert(response.message);
				getCustomCategories();
			}
			var id = $(this).metadata().id;
			var url = catUrl + "?id=" + id + "&action=deleteCategory";
			jQuery.get(url, {}, processDeleteCategory, 'json');
			
		});
	}
	
	var refreshDropdown = function() {
		jQuery.get(	catUrl + "?cat_type=" + categoryType + "&action=getCategoriesOptions", {}, 
				   	function(response) {
						$(".categoriesToUpdate").html(response);			   
					});
		
	}
	
	var getCustomCategories = function() {
		var url = catUrl + "?cat_type=" + categoryType + "&action=getCategories";
		jQuery.get(url, {}, processResult);
		refreshDropdown();
	}
	
	$("#addCategoryForm").submit(function(event) {
		event.preventDefault();
		$(this).ajaxSubmit({
										success : function(response) {
											alert(response.message);
											GabeUtil.screenDimLoading(false);
											$("input[name='name']", $("#addCategoryForm")).val('');
											getCustomCategories();
										},
										dataType : 'json'
										});
		
	});
	
	getCustomCategories();	
}
