var messageTimer;
var mouseX = 0;
var mouseY = 0;

function windowPosition(){
	var x = 0;
	var y = 0;
	if(document.all){
		x = window.screenLeft + 40;
		y = window.screenTop + 40;
	}else{
		x = window.screenX + 40;
		y = window.screenY + 150;
	}
	return [x,y];
}

function windowPositionAbs(){
	var x = 0;
	var y = 0;
	if(document.all){
		x = window.screenLeft;
		y = window.screenTop;
	}else{
		x = window.screenX;
		y = window.screenY;
	}
	return [x,y];
}

function windowSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function centeredWindow(url,name,w,h){
	var pos = windowPositionAbs();
	var siz = windowSize();
	var l = pos[0];
	var t = pos[1];
	if(w < siz[0]){
		l = l + ((siz[0] - w) / 2);
	}
	if(h < siz[1]){
		t = t + ((siz[1] - h) / 2);
	}
	var ret = window.open(url,name,"resizable=1,location=0,scrollbars=1,left=" + l + ",screenX=" + l + ",top=" + t + ",screenY=" + t + ",width=" + w + ",height=" + h);
	return ret;
}

function maxWindow(url,name,padding){
	var pad = padding + 0;
	var pos = windowPositionAbs();
	var siz = windowSize();
	
	var l = pos[0] + pad;
	var t = pos[1] + pad;
	var w = siz[0] - (pad * 2);
	var h = siz[1] - (pad * 2);
	if(w < 100){
		w = 100;
		l = pos[0] + ((siz[0] - w) / 2);
	}
	if(h < 100){
		h = 100;
		t = pos[1] + ((siz[1] - h) / 2);
	}
	var ret = window.open(url,name,"resizable=1,location=0,scrollbars=1,left=" + l + ",screenX=" + l + ",top=" + t + ",screenY=" + t + ",width=" + w + ",height=" + h);
	return ret;
}

function createCookie(name,value,days){
  if(days){
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }else{
    var expires = "";
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++){
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name){
  createCookie(name,"",-1);
}

function toggleAll(theForm, op) {
	for (z=0; z< theForm.elements.length ;z++){
		if(theForm[z].type == "checkbox"){
			theForm[z].checked = op;
		}
	}
}

function showCustomHelp(sTopic){
	helpWin = centeredWindow("Help.asp?Topic="+sTopic,"Help",400,400);
	helpWin.focus();
}

function setupWizard(){
	setupW = centeredWindow("Wizard.asp?Popup=1&Step=1","SetupWiz",640,600);
	setupW.focus();
}

function parseXML(xml,tag){
	if(xml == "" || xml == undefined || tag == "" || tag == undefined){return "";}
	var sData = xml.toUpperCase();
	var sTag = tag.toUpperCase();
	
	iStart = sData.indexOf("<" + sTag + ">");
	if(iStart == -1){return "";}
	
	iStart = sData.indexOf(">", iStart + 1);
	if(iStart == -1){return "";}

	var iEnd = sData.indexOf("</" + sTag + ">");
	if(iEnd == -1){return "";}

	var sRet = xml.substring(iStart + 1, iEnd);
	return sRet;
}

function setupCalendars(){
	$(".calendarBoth").datepicker({ 
	    showOn: "button", 
	    buttonImage: "images/calendar.gif", 
	    buttonImageOnly: true 
		});
	}

function setupMessageChecker(){
	checkForNewMessages();
	messageTimer = setInterval("checkForNewMessages()", 30000);
}

function checkForNewMessages(){
	$.ajax({
		type: "GET",
		url: "ajaxServer.asp?type=messages",
		cache: false,
		dataType: "html",
		success: function(html){
			processNewMessages(html);
		}
	});
}

function showUserMessages(){
	$.ajax({
		type: "GET",
		url: "ajaxServer.asp?type=messages&opt1=all",
		cache: false,
		dataType: "html",
		success: function(html){
			processNewMessages(html);
		}
	});
}

function processNewMessages(h){
	if(h=="" || h==null || h=="null"){return;}
	var siz = windowSize();
	mW = siz[0] - 50;
	mH = siz[1] - 50;
	var res = parseXML(h, "result");
	var d = parseXML(h, "data");
	if(res == "True"){
		clearInterval(messageTimer);
		showMessage("Messages",d,false, mW, mH);
	}
}

function setupTooltips(){
	$('table').tooltip ({track: true, delay: 0, showURL: false, showBody: " - "});
	$('.tooltip').tooltip({track: true, delay: 0, showURL: false, showBody: " - "});
}

function setupCluetips(){
	$('.cluetips').cluetip({
		positionBy: 'mouse',
		showTitle: true,
		width: 180,
		height: 'auto',
		sticky: true,
		waitImage: false,
		mouseOutClose: false,
		activation: 'click',
		cluetipClass: 'rounded',
		titleAttribute: 'cluetiptitle',
		arrows: false,
		closePosition: 'title',
		closeText: '<img src=images/icon_popupClose.png>',
		ajaxCache: false,
		ajaxProcess: function(h){curUserMessage = h; return h;}
	});

	$('.cluetipswide').cluetip({
		positionBy: 'mouse',
		showTitle: true,
		width: 300,
		height: 'auto',
		sticky: true,
		waitImage: false,
		mouseOutClose: false,
		activation: 'click',
		cluetipClass: 'rounded',
		titleAttribute: 'cluetiptitle',
		arrows: false,
		closePosition: 'title',
		closeText: '<img src=images/icon_popupClose.png>',
		ajaxCache: false,
		ajaxProcess: function(h){curUserMessage = h; return h;}
	});
	
	$('.eventtip').cluetip({
		positionBy: 'mouse',
		showTitle: true,
		width: 180,
		height: 'auto',
		sticky: true,
		waitImage: false,
		mouseOutClose: false,
		activation: 'click',
		cluetipClass: 'rounded',
		titleAttribute: 'cluetiptitle',
		arrows: false,
		closePosition: 'title',
		closeText: '<img src=images/icon_popupClose.png>',
		local: true
	});
}

function hideClueTips(){
	$(document).trigger('hideCluetip');
}

function hideModalItem(elName){
	var el = document.getElementById(elName);
	$(el).fadeOut("fast");
}

function infoMessage(sTitle, sMsg){
	var t = "<font style='font-size:20px;'>" + sTitle + "</font>";
	var m = '<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100">';
	m += '<tr><td align="center" valign="middle">';
	m += '<table border="0" cellpadding="2" cellspacing="0"><tr>';
	m += '<td><img src="images/wait.gif" width="32" height="32"/></td>';
	m += '<td><font style="font-size:22px;">' + sMsg + '</font></td>';
	m += '<td><img src="images/spacer.gif" width="32" height="32"/></td>';
	m += '</tr></table></td></tr></table>';
	showMessage(t, m, false, 400, 'auto');
}

function reloadSmallCalendars(pn){
	document.getElementById("smallNavCalendars").innerHTML = document.getElementById("PleaseWaitMessage").innerHTML;
	
	$.ajax({
		type: "GET",
		url: "ajaxSmallCalendars.asp",
		cache: false,
		data: "direction=" + pn,
		success: function(html){
			processSmallCals(html);
		}
	});
}

function saveSettingViaAjax(s,v){
	$.ajax({
		type: "GET",
		url: "ajaxServer.asp?type=savesetting",
		cache: false,
		data: "setting=" + s + "&value=" + v,
		dataType: "html"
	});
}

function processSmallCals(h){
	if(h == ""){return;}
	document.getElementById("smallNavCalendars").innerHTML = h;
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function checkKeyStrokes(e){
	if(navigator.userAgent.match("Gecko")){
		c=e.which;
	}else{
		c=e.keyCode;
	}
	if(c==13){
		//return key
		document.getElementById("messageButton1").click();
	}
	if(c==27){
		//cancel key
		document.getElementById("messageButton2").click();
	}
}

function checkKeyStrokesUserInput(e){
	if(navigator.userAgent.match("Gecko")){
		c=e.which;
	}else{
		c=e.keyCode;
	}
	if(c==13){
		//return key
		var f = document.getElementById("userInputReturnFunction").value;
		$("#getUserInputDialog").dialog("close");
		var v = $("#getUserInputBox").val();
		eval(f + '("' + v + '");');
		return false;
	}
}


function noteTemplate(){
	noteWin = window.open("Events.asp?Action=Note","noteWindow")
	noteWin.focus();
}

function printThisEvent(evid, evx){
	$.ajax({
		type: "GET",
		url: "Events.asp?Action=Print&Popup=1&EventID=" + evid + "&EventX=" + evx,
		cache: false,
		dataType: "html",
		success: function(html){
			processPrint(html);
		}
	});
}

function processPrint(h){
	var t = "<table border='0' cellpadding='0' cellspacing='0'>";
	t += "<tr><td><img src='images/icon_print.png' width='16' height='16'>&nbsp;</td>";
	t += "<td><font color='#ffffff'><b>Select Printing Options</b></font></td></tr></table>";

	showMessage(t,h,false, 600, 'auto', 'generateEventPrint()');
}

function generateEventPrint(){
	var out = "";
	ox = document.getElementById("printEventXML").value;
	it = document.getElementById("printEventItems").value;
	ev = document.getElementById("eventid").value;
	evx = document.getElementById("eventidx").value;
	ctr = document.getElementById("printCount").value;
	pl = document.getElementById("printLayout")[document.getElementById("printLayout").selectedIndex].value;
	
	if(document.getElementById("printServiceOrder").checked==true){
		out += "<printServiceOrder>1</printServiceOrder>";
	}
	
	var ita = it.split(",");
	var ct = 0;
	
	while(ct < ita.length){
		cur = ita[ct];
		if(document.getElementById("capo_" + cur)){
			out += "<capo_" + cur + ">" + document.getElementById("capo_" + cur).value + "</capo_" + cur + ">";
			if(document.getElementById("show_" + cur).checked==true){
				out += "<show_" + cur + ">1</show_" + cur + ">";
			}
		}
		ct+=1;
	}
	
	document.getElementById("print_eventid").value = ev;
	document.getElementById("print_eventx").value = evx;
	document.getElementById("print_count").value = ctr;
	document.getElementById("print_extraxml").value = out;
	document.getElementById("print_eventxml").value = ox;
	document.getElementById("print_layout").value = pl;
	document.getElementById("frmPrint").submit();
}

var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body

function showFloat(){

	var siz = windowSize();
	var h = siz[1];
  if(h > 150){h = h - 60;}


	$("#songSelectionBox").dialog({
		resizable: true,
		width: 500,
		height: h,
		modal: true,
		draggable: true,
		title: "Select a Song"
	});
}

function hideFloat(){
	$("#songSelectionBox").dialog("close");
}

function onlineDemo(){
	document.getElementById("emailAddress").value = "demo";
	document.getElementById("txtPassword").value = "demo";
	document.getElementById("btnLogin").click();
}

function contactUs(){
	var m = "<p>Use the following form to contact us, or email us directly at:<br>support@ministry-manager.com</p>";
	m += "<table border='0' cellpadding='2' cellspacing='0'>";
	m += "<tr><td width='100'>Name</td><td><input type='text' name='contact_name' id='contact_name' style='width:300px;'></tr>";
	m += "<tr><td>Email</td><td><input type='text' name='contact_email' id='contact_email' style='width:300px;'></tr>";
	m += "<tr><td colspan='2'><textarea name='contact_message' id='contact_message' style='width:100%; height:200px;'></textarea></td></tr>";
	m += "</table>";

	document.getElementById("customMessageItem").innerHTML = m;

	$("#customMessageItem").dialog({
		resizable: false,
		width: 420,
		height: "auto",
		modal: true,
		title: "Contact Us",
		draggable: true,
		buttons: {
			Ok: function(){
				processContactUs();
			}
		}
	});
}

function processContactUs(){
	var n = document.getElementById("contact_name").value;
	var e = document.getElementById("contact_email").value;
	var m = document.getElementById("contact_message").value;

	if(n == ""){
		alert("You must enter your name");
		document.getElementById("contact_name").focus();
		return;
	}
	if(e == ""){
		alert("You must enter your email address");
		document.getElementById("contact_email").focus();
		return;
	}
	if(m == ""){
		alert("You must enter a message");
		document.getElementById("contact_message").focus();
		return;
	}

	$.ajax({
		type: "GET",
		url: "ajaxServer.asp?type=contactus&opt1=" + n + "&opt2=" + e + "&opt3=" + escape(m),
		cache: false,
		dataType: "html",
		success: function(html){
			processContactUsSent(html);
		}
	});
}

function processContactUsSent(h){
	var bsent = parseXML(h, "sent");
	if(bsent=="true"){
		$("#customMessageItem").dialog("close");
		showMessage("Message Sent", "Thank you, your message has been sent.", false, 350, "auto");
	}else{
		alert("Sorry, there was a problem sending your message.");
	}
}

function showAbout(){
	var t = "<img src='images/mmlogo_small.png' width='140' height='16'>";
	var m = "<table border='0' cellpadding='2' cellspacing='0'>";
	m += "<tr><td align='left' height='75' colspan='2'>";
	m += "<div style='font-size:12px;'>";
	m += "This program is protected by copyright law and international treaties.  ";
	m += "Unauthorized reproduction or distribution of this program, or any portion of it, may result in severe criminal penalties.";
	m += "</div></td></tr>";
	m += "<tr><td align='center' height='20' colspan='2'><table border='0' cellpadding='2' cellspacing='0'><tr>";
	m += "<td><a href='http://www.facebook.com/pages/Ministry-Manager/101510966583079' target='_new'>";
	m += "<img src='images/icon_facebook.png' width='16' height='16' border='0'></a></td><td style='font-size:12px;'>check us out on Facebook</td></tr></table>";
	m += "<tr><td height='12' colspan='2'></td></tr>";
	m += "<tr><td colspan='2' valign='bottom'>";
	m += "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
	m += "<tr><td valign='bottom'><font style='font-size:12px'>&copy;2005 - 2012 Wickett.NET, LLC</font></td>";
	m += "<td valign='bottom' align='right'><font style='font-size:12px;'>All Rights Reserved</font></td>";
	m += "</tr></table></td></tr></table>";
	showMessage(t,m,false, 400, "auto");
}

function showMessage(t, m, r, w, h, btn){
	//first, hide any open message dialogs
	hideMessage();

	document.getElementById("customMessageItem").innerHTML = m;
	
	btn += "";
	if(btn == "undefined"){btn="";}
	
	if(btn != ""){
		$("#customMessageItem").dialog({
			resizable: r,
			width: w,
			height: h,
			modal: true,
			title: t,
			draggable: true,
			buttons: {
				Ok: function(){
					$(this).dialog("close");
					eval(btn);
				}
			}
		});
	}else{
		$("#customMessageItem").dialog({
			resizable: r,
			width: w,
			height: h,
			modal: true,
			title: t,
			draggable: true,
			buttons: {}
		});
	}
	$("#customMessageItem").dialog("open");
}

function hideMessage(){
	if($("#customMessageItem").dialog("isOpen") == true){
		$("#customMessageItem").dialog("close");
	}
}

function doLogin(){
	var uname = document.getElementById("emailAddress").value;
	if(uname == ""){
		alert("You must enter an email address");
		return false;
	}
	infoMessage("Please Wait", "Processing Login");
	return true;
}

function setLoginFocus(){
	if(document.getElementById("emailAddress")){
		$("#emailAddress").focus();
	}
}

function ieUser(){
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf("msie") != -1){
		return true;
	}else{
		return false;
	}
}

function emailWindow(){
	em = maxWindow("EMail.asp?Action=Mail&Popup=1","emailWindow",50);
	em.focus();
}

function showDocumentation(){
	docs = centeredWindow("Documentation.asp?Popup=1","documentationWindow",640,600);
	docs.focus();
}

function videoTutorials(){
	vids = centeredWindow("Misc.asp?Page=Videos&Popup=1","videos",950,800);
	vids.focus();
}

function createNewSong(){
	var t = "<table border='0' cellpadding='0' cellspacing='0'><tr><td><img src='images/icon_newSong.png' width='16' height='16'></td><td><font color='#ffffff'>&nbsp;<b>Create a New Song</b></font></td></tr></table>";
	getUserInput(t, "Enter the <b>title</b> for the New Song", 300, "auto", "createTheNewSong", "");
}

function createTheNewSong(songName){
	if(document.getElementById("newSongName")){
		songName = document.getElementById("newSongName").value;
	}
	$("#newSongDialog").dialog("close");
	if(songName != ""){
		location = "Songs.asp?Action=New&Title=" + encodeURI(songName);
	}
}

function getUserInput(sTitle, sMessage, iW, iH, handlerFunction, sDefault){
	$("#userInputReturnFunction").val(handlerFunction);
	$("#userInputMessage").html(sMessage);
	$("#getUserInputBox").val(sDefault);
	
	$("#getUserInputDialog").dialog({
		resizable: false,
		width: iW,
		height: iH,
		title: sTitle,
		modal:true,
		draggable: true
	});
	$("#getUserInputBox").focus();
}

function myAvail(){
	uav = centeredWindow("Avail.asp?Popup=1","availWindow",640,600);
	uav.focus();
}

function userPrefs(){
	uprefs = centeredWindow("Prefs.asp?Popup=1","prefsWindow",680,750);
	uprefs.focus();
}

function contactList(){
	clist = maxWindow("Users.asp?Action=ContactList&Popup=1","contactList",50);
	clist.focus();
}

function showMessages(){
	clist = maxWindow("Messages.asp?Popup=1","contactList",50);
	clist.focus();
}

function churchSettings(){
	appPref = centeredWindow("AppPrefs.asp?Popup=1","churchSettings",800,650);
	appPref.focus();
}

function showPricingOptions(){
	$.ajax({
		type: "GET",
		url: "Misc.asp?Page=Renew",
		cache: false,
		dataType: "html",
		success: function(html){
			pricingMessage(html);
		}
	});
}

function pricingMessage(h){
	showMessage("Pricing Information",h,false, 800, 750);
}

function siteMap(){
	siteMap = centeredWindow("Misc.asp?Page=SiteMap&Popup=1","churchSettings",640,600);
	siteMap.focus();
}

function songFormatting(){
	songFormat = maxWindow("SongFormatting.asp?Popup=1","songFormats",50);
	songFormat.focus();
}

function guitarChords(){
	gChords = centeredWindow("Chords.asp?Popup=1","Chords",640,600);
	gChords.focus();
}

