function GetXmlHttp() {
  var xmlhttp = false;
  if (window.XMLHttpRequest)
  {
    xmlhttp = new XMLHttpRequest()
  }
  else if (window.ActiveXObject)// code for IE

  {
    try
    {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
    } catch (e) {
      try
      {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
      } catch (E) {
        xmlhttp=false
      }
    }
  }
  return xmlhttp;
}

function addCommas(nStr)
{
	nStr += '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + ',' + '$2');
	}
	if(nStr=='3,000,000') nStr+='+'
	return nStr
}

var subTimeout
var okToHide = false
var hideWhenDone = false
var subFocus = false

$(document).ready(function() {
	$(".lightbox").fancybox();
	if($('#partyclient').length) $('#partyclient').autocomplete({
		serviceUrl:'/ajax/clients.php',
		minChars:2,
		width:'auto',
		onSelect: function(value, data){
			$('#partyclient').val(value)
			$('#cli_num').val(data)
			$('#partyclient').addClass('selected')
			initSelected()
			$('#partyclient').focusNextInputField()
		},
		onSearch: function() {
			$('#cli_num').val('')
		}
	})
	if($('#contractcontact').length) $('#contractcontact').autocomplete({
		serviceUrl:'/ajax/contacts.php',
		minChars:2,
		width:'auto',
		onSelect: function(value, data){
			$('#contractcontact').val(value)
			$('#cnt_num').val(data)
			$('#contractcontact').addClass('selected')
			initSelected()
			$('#contractcontact').focusNextInputField()
		},
		onSearch: function() {
			$('#cnt_num').val('')
		}
	})
	$( ".jqdate" ).datepicker({
		changeMonth: true,
		changeYear: true,
		showOn: "button",
		buttonImage: "/assets/images/cal.gif",
		buttonImageOnly: true,
		//altField: "#" + $(this).id + "_disp",
		altFormat: "DD, d MM, yy",
		showAnim: "slideDown",
		dateFormat: "yy-mm-dd",
		beforeShow: function(input, inst) {
			$(this).datepicker("option", "altField", $('#' + input.id + '_disp'))
		}
	});
	initSelected()
});

function initSelected() {
	$("input.selected").focus(function(){
		$(this).removeClass('selected')
	})
	$("input.selected").blur(function(){
		if($('#cli_num').val()) $(this).addClass('selected')
	})
}

function confirmReceive(caller) {
	$( "#dialog-confirm" ).dialog({
		resizable: false,
		height:140,
		width:500,
		modal: true,
		buttons: {
			"Receive and Send Notifications": function() {
				 location.href = caller.href + '&send=1'
			},
			"Receive Only": function() {
				 location.href = caller.href
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		}
	});
	return false
}

function checkEmail(src,usr_num) {
	var emailBox = src
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var ret = xmlHttp.responseText
			if(ret==0) {	
				$('#' + emailBox.id + '_after').html('<img src=\"/assets/images/tick.png\" />')
			} else if (ret==1) {
				$('#' + emailBox.id + '_after').html('<img src=\"/assets/images/cross.png\" />This email address is already in use. If you have forgotten your password, please <a href="/forgot">reset it here</a>.')
				emailBox.className = 'error'
			} else {
				$('#' + emailBox.id + '_after').html('<img src=\"/assets/images/cross.png\" />Please enter a valid email address')
				emailBox.className = 'error'
			}
		}
	}
	xmlHttp.open("GET","/ajax/checkEmail.php?e=" + src.value + '&m=' + usr_num,true)
	xmlHttp.send(null)	
	$('#' + emailBox.id + '_after').html('<div style="text-align:center"><img src="/assets/images/progress.gif" /></div>')
	emailBox.className = ''
}

function changeToProgress() {
	$('#backnext').hide()
	$('#saveprogress').show()
}
function isNumber(evt) {
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	if ((keycode>57 && keycode<127)) {
		return false	
	} else {
		return true
	}
}

function checkLength(obj,len) {
	if (obj.value.length > len) {
		obj.value = obj.value.substring(0,len)	
	}
}
function deleteItem(caller, type, id) {
	if(confirm('Are you sure you want to delete this ' + type + '? This action can not be reversed')) {
		loading(true)
		$.ajax({
			url: '/ajax/delete.php?t=' + type + '&id=' + id,
			dataType: 'json',
			success: function(data){
				if(data.error) {
					alert('Error: ' + data.error)
				} else {
					var table = $(caller).parents('table').first()
					var row = $(caller).parents('tr').first()
					row.remove()
					var i = 0
					var row = 0
					table.find('tr').each(function(){
						$(this).removeClass('row1 row0')
						if(i>0) {
							row = 1-row
							$(this).addClass('row' + row)
						}
						i++
					})
				}
				loading(false)
				if(data.notice) {
					alert(data.notice)
				}
				if(data.refreshpage) {
					document.location.href = document.location.href
				}
			}
		})
	}
	return false
}

function deleteFile(caller, file) {
	if(confirm('Are you sure you want to delete this file? This action can not be reversed')) {
		loading(true)
		$.ajax({
			url: '/ajax/deleteFile.php?f=' + file,
			success: function(){
				if($('#file_num').length) {
					$('#file_num').val('')
					$(caller).parents('span').first().remove()
				} else {
					var table = $(caller).parents('table').first()
					var row = $(caller).parents('tr').first()
					row.remove()
					var i = 0
					var row = 0
					table.find('tr').each(function(){
						$(this).removeClass('row1 row0')
						if(i>0) {
							row = 1-row
							$(this).addClass('row' + row)
						}
						i++
					})
				}
				loading(false)
			}
		})
	}
	return false
	
}

function deleteNote(caller, type, msg) {
	if(confirm('Are you sure you want to delete this note? This action can not be reversed')) {
		loading(true)
		$.ajax({
			url: '/ajax/note.php?delete=1&msg=' + msg + '&t=' + type,
			success: function(){
				$(caller).parents('.note').remove()
				loading(false)
			}
		})
	}
	return false
	
}

function markInvoiced(caller, contract, year) {
	loading(true)
	$.ajax({
		url: '/ajax/markInvoiced.php?c=' + contract + '&y=' + year,
		success: function(){
			$(caller).parent().html('<img src="/assets/images/tick.png" alt="Invoiced" />')
			loading(false)
		}
	})

	return false
	
}

function saveNote(type, id) {
	msg = $('#notenum').val()
	text = encodeURIComponent($('#note').val().replace(/\n/g,'\\n'))
	loading(true)
	$.ajax({
		url: '/ajax/note.php?t=' + type + '&msg=' + msg + '&id=' + id + '&text=' + text,
		success: function(data){
			if(msg && msg>0) {
				$('#note_' + msg).children('.text').html(data)
				closeNote()
			} else {
				$('#notearea').after(data)
				closeNote()
			}
			loading(false)
		}
	})

}

function editNote(caller, type, msg) {
	$('#notenum').val(msg)
	$('#note').val($(caller).parents('.note').first().children('.text').html().replace(/<br ?\/?>\n?/g,"\n"))
	$('#notelink').hide()
	$('#notearea').show()
}

function closeNote() {
	$('#notelink').show()
	$('#notearea').hide()
	$('#notenum').val('')
	$('#note').val('')
}

function loading(on) {
	if($('#overlay').length==0) {
		$('<div id="overlay">&nbsp;</div>').appendTo($('body'))
		$('<div id="loader">&nbsp;</div>').appendTo($('body'))
	}
	if(on) {
		$('#overlay, #loader').show()
	} else {
		$('#overlay, #loader').hide()
	}
}

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button:visible,input:visible,textarea:visible,select:visible');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        return false;
    });
};

function clientAddSubmit() {
	$('#clientAddForm').hide()
	$('#clientAddProgress').show()
}

function clientAddError(err) {
	$('#clientAddForm').show()
	$('#clientAddProgress').hide()
	alert(err)
}

function clientAddSuccess(num, name) {
	$('#partyclient').val(name)
	$('#cli_num').val(num)
	$('#partyclient').focusNextInputField()
	$('#partyclient').addClass('selected')
	$.fancybox.close()
	initSelected()
}

function contactAddSuccess(num, name) {
	$('#contractcontact').val(name)
	$('#cnt_num').val(num)
	$('#contractcontact').focusNextInputField()
	$('#contractcontact').addClass('selected')
	$.fancybox.close()
	initSelected()
}
