$(document).ready(function(){
						   
	$.ajaxSetup({
	   contentTypeString: "iso-8859-1"
	 });

						   
	JT_init(); //Init the tooltips
	
	//maxchars = 612; //Was overriding page-specific global
	wappushurl = 0;
	
	/*if ($('.success').length) { //Animate the success message box
		$('.success').animate({opacity: 1.0},3000).animate({backgroundColor:"#ededed",borderTopColor:"#e3e3e3",borderRightColor:"#e3e3e3",borderBottomColor:"#e3e3e3",borderLeftColor:"#e3e3e3"},1000);
	}*/

	if ($("#debug").length) { //Make the "debug" section collapse and toggleable
		$('div#debug pre').toggle();
		$(function () {
			$('div#debug strong').click(function () {
				$('div#debug pre').slideToggle("fast");
			});
		});
	}
	
	if ($(".sendtabs").length) { //We're on the Send page, so handle the tabs
		$('.sendtabs a').each(function() {
			var str = $(this).attr("href");
			var str = str.replace("/send/?recepient=","#send-");
			$(this).attr("href",str);
		});
	}

	if ($("#recepient").length) { //We're on the Send page, so make the tab contents dynamically load via AJAX
		initrecepientlist();		
		$('#recepient').tabs({ //Control the tabs, and AJAX load new tab content
			onClick: function(newtab,newcontent,oldcontent) {
				$(oldcontent).empty();
				$(newcontent).html("<span class=\"loading\"><span>Loading...</span></span>");
				var url = "/content/" + $(newtab).attr("href").replace("#","") + ".php";
				url = url + "?customerID="+$(newtab).attr("rel");
				$.get(url, function(data){
					$(newcontent).html(data);
					if ($('#contactsform').length) {
						var title = $(newtab).attr("href").substring(10);
						var titleA = title.substring(0,1).toUpperCase();
						var titleB = title.substring(1);
						$('#messagedetails h3').text(titleA+titleB+" Manager");
					}
					initrecepientlist();
				});
			},
			onHide: function() {},
			onShow: function() {}
		});
	}
	
	if ($("#message-body").length || $("#message-body-mms").length) { //There's a message box, so handle the limits and alerts
		$('#remainingchars').html("You have used <strong id=\"remainingcharacters\">0</strong> characters.<span id=\"totalmessages\"></span>");		
		//Calculate characters entered
		$('#message-body').keyup(function() {
			if ($("#message-wapurl").length) { //There's a WAP URL box, so handle the limits and alerts
				wappushurl = $("#message-wapurl").val().length;
			}
			countChars();
		});
		
		//Add and control the insert buttons
		if (whitelabelcmr) {
			$('#insertbuttons').html("Insert: <br /><span class=\"button-action\" id=\"insert-FirstName\"><span>Firstname</span></span><span class=\"button-action\" id=\"insert-LastName\"><span>Lastname</span></span><span class=\"button-action\" id=\"insert-Custom1\"><span>Custom 1</span></span><span class=\"button-action\" id=\"insert-Custom2\"><span>Custom 2</span></span><span class=\"button-action\" id=\"insert-Custom3\"><span>Custom 3</span></span>");
		} else {
			$('#insertbuttons').html("Insert: <br /><span class=\"button-action\" rel=\"page\" id=\"insert-Page\"><span>Page</span></span><span class=\"button-action\" id=\"insert-FirstName\"><span>Firstname</span></span><span class=\"button-action\" id=\"insert-LastName\"><span>Lastname</span></span><span class=\"button-action\" id=\"insert-Custom1\"><span>Custom 1</span></span><span class=\"button-action\" id=\"insert-Custom2\"><span>Custom 2</span></span><span class=\"button-action\" id=\"insert-Custom3\"><span>Custom 3</span></span>");
		}
		
		$('#insertbuttons .button-action').bind("click",function() {
			if ($(this).attr("rel")!="page") {
				var insert="#"+$(this).attr("id").substr(7)+"#";
				insertAtCaret('message-body',insert);
				$("#message-body").focus();
				countChars();
			} else {
				var range = $("#message-body").getSelection();
				caretPos = range.start;
				tb_show("Select Page","/content/pages-insert.php?height=240&width=500")
			}
		});
	}
	
	if ($('#insert-GiftAid').length) {
		$('#insert-GiftAid').bind("click",function() {
			var insert="http://tx.vc/g/##giftaid##";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-PageLink').length) {
		$('#insert-PageLink').bind("click",function() {
			var range = $("#message-body").getSelection();
			caretPos = range.start;
			tb_show("Select Page","/content/pages-insert.php?height=240&width=500")
		});
	}

	if ($('#scheduled-autoresponders-new').length) {
		$('#scheduled-autoresponders-new').bind("click",function() {
			var query = document.getElementById('inboxid').value;
			tb_show("Select Page","/messages/scheduled/autoresponders/?id=" + query)
		});
	}
	
	if ($('#insert-Message').length) {
		$('#insert-Message').bind("click",function() {
			var insert="#Message#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-SenderNumber').length) {
		$('#insert-SenderNumber').bind("click",function() {
			var insert="#SenderNumber#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-SenderName').length) {
		$('#insert-SenderName').bind("click",function() {
			var insert="#SenderName#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-SenderCustom1').length) {
		$('#insert-SenderCustom1').bind("click",function() {
			var insert="#SenderCustom1#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-SenderCustom2').length) {
		$('#insert-SenderCustom2').bind("click",function() {
			var insert="#SenderCustom2#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-SenderCustom3').length) {
		$('#insert-SenderCustom3').bind("click",function() {
			var insert="#SenderCustom3#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-UniqueCode').length) {
		$('#insert-UniqueCode').bind("click",function() {
			var insert="#UniqueCode#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-CalendarDate').length) {
		$('#insert-CalendarDate').bind("click",function() {
			var insert="#Date#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-CalendarTime').length) {
		$('#insert-CalendarTime').bind("click",function() {
			var insert="#Time#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}
	
	if ($('#insert-CalendarTitle').length) {
		$('#insert-CalendarTitle').bind("click",function() {
			var insert="#Title#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}

	if ($('#insert-CalendarLocation').length) {
		$('#insert-CalendarLocation').bind("click",function() {
			var insert="#Location#";
			insertAtCaret('message-body',insert);
			$("#message-body").focus();
			countChars();
		});
	}

	if ($("#message-wapurl").length) { //There's a WAP URL box, so handle the limits and alerts
		$('#message-wapurl').keyup(function() {
			wappushurl = $("#message-wapurl").val().length;
			countChars();
		});
	}
	
	if ($("#message-body-160").length) { //There's a message box, so handle the limits and alerts
		$('#remainingchars').html("You have <strong id=\"remainingcharacters\">160</strong> characters remaining.<span id=\"totalmessages\"></span>");		
		$('#message-body-160').keyup(countChars160);
	}
	
	if ($("#message-body-mms").length) { //There's a message box, so handle the limits and alerts
		$('#remainingchars').html("You have used <strong id=\"remainingcharacters\">0</strong> characters.<span id=\"totalmessages\"></span>");		
		$('#message-body-mms').keyup(countCharsMMS);
	}
	
	if ($("#contactsform").length) { //Contacts Form exists, so handle the submission (detect which submit button is pressed - Delete shows a modal window)
		$("#deletegroup").click(function() {
			var count = 0;
			var type = $('#recepientlist').parent('div').attr('id');
			$('#recepientlist input.recepientcheckbox:checked').each(function() {count = count + 1;});
			var message="Are you sure you want to remove ";			
			if (count > 1) {
				if (type=="groups") {message=message+"these "+count+" groups and all their contacts?";}
				if (type=="contacts") {message=message+"these "+count+" contacts?";}
			} else {
				if (type=="groups") {message=message+"this group and all its contacts?";}
				if (type=="contacts") {message=message+"this contact?";}
			}
			if (confirm(message)) {
				return true;
			} else {
				return false;
			}
		});
	}
	
	if ($("#globalcheck").length) { //Checks all checkboxes below
		$("#globalcheck").click(function() {
			if ($('#globalcheck').attr("checked")==true) {
				$('#groupcontacts').find("input:checkbox").attr("checked",true);
			} else {
				$('#groupcontacts').find("input:checkbox").attr("checked",false);
			}
		});
	}
	
	if ($('input.indenttoggle').length) {
		$('input.indenttoggle').each(function() {
			if ($(this).attr("checked")==false) {
				$(this).parent().next('div.indent').hide();	
			}
		});
		$('input.indenttoggle').click(function(){$(this).parent().next('div.indent').slideToggle();});
	};
	
	if ($('input.indenttoggleradio').length) {
		$('input.indenttoggleradio').each(function() {
			if ($(this).attr("checked")==false) {
				$(this).parent().next('div.indent').hide();	
			}
		});
		$('input.indenttoggleradio').click(function(){
			$(this).parent().siblings('div.indent').slideUp();
			$(this).parent().next('div.indent').slideDown();
		});
	};
	
	if ($('form#createuniquecode').length) {
		$("form#createuniquecode").submit(function() {
			var query = $("form#createuniquecode").serializeArray();
			tb_show('','/contactmanager/uniquecode/',null,query);
			return false;
		});
	}
	
	if ($('form#sendtextmessage').length) {
		$("form#sendtextmessage").submit(function() {
			var query = $("form#sendtextmessage").serializeArray();
			tb_show('','/send/confirm/',null,query);
			return false;
		});
	}
	
	if ($('form#sendmmsmessage').length) {
		$("form#sendmmsmessage").submit(function() {
			var query = $("form#sendmmsmessage").serializeArray();
			tb_show('','/send/mms/confirm/',null,query);
			return false;
		});
	}
	
	if ($('#deleteall').length) {
		$("#deleteall").click(function() {
			if (confirm("** WARNING: PLEASE READ THIS CAREFULLY **\r\n\r\nAre you sure you want to delete *ALL* the contacts from this group?\r\n\r\nThis action cannot be undone.")) {
				return true;
			} else {
				return false;
			}
		});
	}
	
	if ($('#deleteallinbox').length) {
		$("#deleteallinbox").click(function() {
			if (confirm("Are you sure you want to delete ALL the messages from this inbox?\r\n\r\nThis action cannot be undone.")) {
				return true;
			} else {
				return false;
			}
		});
	}
	
	if ($('#importcolumnheader').length) {
		removeImportDupes(null);
		$('#importcolumnheader select').change(removeImportDupes);
	}
	
	if ($('#twistiearea').length) {	
		$('div.twisties > h3').addClass("twist");
		$('div.twisties > h3').each(function(element) {
			if ($(this).hasClass("expanded")) {
				$(this).next().show();
				$(this).toggleClass("twist-down");
			} else {
				$(this).next().hide();
			}
		});
		$('div.twisties > h3').click(function() {
			$(this).toggleClass("twist-down");
			$(this).next().slideToggle('fast');
		});
	}
	
});

function removeImportDupes(event) {
	var changed = "";
	var headers=new Array();
	var i = 0;
	$('#importcolumnheader th select').each(function() {headers[i] = $(this).val();i++;});
	dupe = arrHasDupes(headers);
	if (dupe) {
		headers.reverse();
		lim = headers.length;
		if (event) {
			var changed = (event.target.id);
			var changed = lim - changed.substr(3,1) * 1 - 1;			
		}
		for (i=0;i<=lim;i++) {
			if (headers[i]==dupe) {
				if (changed==i) {continue;}
				headers[i]="X";
				i=lim;
			}
		}
		headers.reverse();
		var i = 0;
		$('#importcolumnheader th select').each(function() {
			$(this).val(headers[i]);
			i++;
		});
	}		
}

function arrHasDupes(A) {                 // finds any duplicate array elements using the fewest possible comparison
	var i, j, n;
	n=A.length;                           // to ensure the fewest possible comparisons
	for (i=0; i<n; i++) {                 // outer loop uses each item i at 0 through n
		for (j=i+1; j<n; j++) {           // inner loop only compares items j at i+1 to n
			if (A[j]=="X") continue;	  // ignore "X" as an option
			if (A[i]==A[j]) return (A[j]);  // hit
	}	}
	return false;                         // not hit
}


function countChars() {
	wappushmode = false;
	if ($('#autoresponseurl').length) {
		if ($('#autoresponseurl').attr("checked")==true) {
			wappushurl = $("#message-wapurl").val().length;
			wappushmode = true;
		}
	}
	if ($('#message-wapurl-toggle').length) {
		if ($('#message-wapurl-toggle').attr("checked")==true) {
			wappushurl = $("#message-wapurl").val().length;
			wappushmode = true;
		}
	}
	extrachars = wappushurl;
	addonchars = 0;
	merged = false;
	messageStr = "";
	for(i = 0; i < countInstances("#message-body","#FirstName#"); i++){extrachars=extrachars-11+firstnamechars;merged=true}
	for(i = 0; i < countInstances("#message-body","#LastName#"); i++){extrachars=extrachars-10+lastnamechars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom1#"); i++){extrachars=extrachars-9+custom1chars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom2#"); i++){extrachars=extrachars-9+custom2chars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom3#"); i++){extrachars=extrachars-9+custom3chars;merged=true}
	if (merged) {messageStr="<br />This is only a guide, as merged fields may vary in length.";}
	//add an extra char for all €
	extrachars=extrachars + $("#message-body").val().countOddChars('€');
	if ($('#message-addon').length) {
		 addonchars = $("#message-addon").val().length;
	}
	var chars = $("#message-body").val().length+extrachars+addonchars;
	var charsleft = maxchars - chars;
//	if (charsleft<0) {charsleft=0;}	
	$('#remainingcharacters').text(chars);
	
	if (chars > "114" && wappushmode == true) {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		countChars();
	}
	
	if (maxchars=="140" && chars>"140") {
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		$('#totalmessages').html("");
		countChars();
		return;
	}
	
	if (maxchars=="160" && chars>"160") {
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		$('#totalmessages').html("");
		countChars();
		return;
	}
	
	if (chars < "161") {
		$('#remainingchars').removeClass().addClass("stageone");
		$('#totalmessages').html("");
	}
	if (chars > "160") {
		$('#remainingchars').removeClass().addClass("stagetwo");
		$('#totalmessages').html("<br />Messages over 160 characters will be sent as <strong>2</strong> texts."+messageStr);
	}
	if (chars > "306") {
		$('#remainingchars').removeClass().addClass("stagethree");
		$('#totalmessages').html("<br />Messages over 306 characters will be sent as <strong>3</strong> texts."+messageStr);
	}
	if (chars > "459") {
		$('#remainingchars').removeClass().addClass("stagefour");
		$('#totalmessages').html("<br />Messages over 459 characters will be sent as <strong>4</strong> texts."+messageStr);
	}
	if (chars == "612") {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#totalmessages').html("<br />Messages over 459 characters will be sent as <strong>4</strong> texts."+messageStr);
	}
	if (chars > "612") {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		countChars();
	}
};

function countCharsDown() { //Count the number of chars in the #message-body and handle the count (counts down)
	if ($('#autoresponseurl').length) {
		if ($('#autoresponseurl').attr("checked")==true) {
			wappushurl = $("#message-wapurl").val().length;
		}
	}
	extrachars = wappushurl;
	merged = false;
	message = "";
	for(i = 0; i < countInstances("#message-body","#FirstName#"); i++){extrachars=extrachars-11+firstnamechars;merged=true}
	for(i = 0; i < countInstances("#message-body","#LastName#"); i++){extrachars=extrachars-10+lastnamechars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom1#"); i++){extrachars=extrachars-9+custom1chars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom2#"); i++){extrachars=extrachars-9+custom2chars;merged=true}
	for(i = 0; i < countInstances("#message-body","#Custom3#"); i++){extrachars=extrachars-9+custom3chars;merged=true}
	if (merged) {message="<br />This is only a guide, as merged fields may vary in length.";}
	var chars = $("#message-body").val().length+extrachars;
	var charsleft = maxchars - chars;
//	if (charsleft<0) {charsleft=0;}	
	$('#remainingcharacters').text(charsleft);
	if (chars < "161") {
		$('#remainingchars').removeClass().addClass("stageone");
		$('#totalmessages').html("");
	}
	if (chars > "160") {
		$('#remainingchars').removeClass().addClass("stagetwo");
		$('#totalmessages').html("<br />This message will be sent as 2 text messages."+message);
	}
	if (chars > "306") {
		$('#remainingchars').removeClass().addClass("stagethree");
		$('#totalmessages').html("<br />This message will be sent as 3 text messages."+message);
	}
	if (chars > "459") {
		$('#remainingchars').removeClass().addClass("stagefour");
		$('#totalmessages').html("<br />This message will be sent as 4 text messages."+message);
	}
	if (chars == "612") {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#totalmessages').html("<br />This message will be sent as 4 text messages."+message);
	}
	if (chars > "612") {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		countChars();
	}
	if (charsleft<0) {
		$('#message-body').val($('#message-body').val().substr(0,$("#message-body").val().length-1));
		countChars();
	}
};

function countChars160() { //Count the number of chars in the #message-body and handle the count, limited to only 160 chars with no merged fields
	var chars = $("#message-body-160").val().length;
	var maxchars = "160";
	var charsleft = maxchars - chars;	
	if (charsleft<0) {charsleft=0;}	
	$('#remainingcharacters').text(charsleft);	
	if (chars < "100") {
		$('#remainingchars').removeClass().addClass("stageone");
	}
	if (chars > "0") {
		$('#remainingchars').removeClass().addClass("stagetwo");
	}
	if (chars > "100") {
		$('#remainingchars').removeClass().addClass("stagethree");
	}
	if (chars > "130") {
		$('#remainingchars').removeClass().addClass("stagefour");
	}
	if (chars == "160") {
		$('#remainingchars').removeClass().addClass("stagefive");
	}
	if (chars > "160") {
		$('#remainingchars').removeClass().addClass("stagefive");
		$('#message-body-160').val($('#message-body-160').val().substr(0,$("#message-body-160").val().length-1));
		countChars160();
	}	
};

function countCharsMMS() { //Count the number of chars in the #message-body-mms and handle the count, limited to 612 characters
	var chars = $("#message-body-mms").val().length;
	$('#remainingcharacters').text(chars);	
	
	if (chars > "612") {
		$('#message-body-mms').val($('#message-body-mms').val().substr(0,$("#message-body-mms").val().length-1));
		countCharsMMS();
	}
};

function insertAtCaret(obj, string) { //Insert text in the textarea#areaId where the caret is
	obj = document.getElementById(obj);
	obj.focus();
	if (typeof(document.selection) != 'undefined') {
		var range = document.selection.createRange();
	    if (range.parentElement() != obj)
    	return;
		range.text = string;
		range.select();
	} else if (typeof(obj.selectionStart) != 'undefined') {
		var start = obj.selectionStart;
		obj.value = obj.value.substr(0, start) + string + obj.value.substr(obj.selectionEnd, obj.value.length);
		start += string.length;
		obj.setSelectionRange(start, start);
	}
	else obj.value += string;
	obj.focus();
}

function insertAtCaretOld(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") { 
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart;	
	var front = (txtarea.value).substring(0,strPos);  
	var back = (txtarea.value).substring(strPos,txtarea.value.length); 
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") { 
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function countInstances(target,string) { //Returns how many 'string's appear in 'target'
	var pos = 0;
	var num = -1;
	var i = -1;	
	while (pos != -1) {
		pos = $(target).val().indexOf(string, i + 1);
		num += 1;
		i = pos;
	}	
	return num;
}

function initrecepientlist() { //A group is expanded on the Send page, so set up the defaults and handle events

	var enabled = 0;
	$('#recepientlist input.recepientradio').bind("click",function() { //Toggle group highlighting and auto checkbox control
		confirmed = false;
		$("#recepientlist div").each(function() {
			if ($(this).next("table").children("thead").length) {
				if (confirmed==false) {
					if (confirm("Selecting a new group/inbox will clear any filtering you've made on any open group/inbox listings.\r\n\r\nAre you sure you want to do this?")) {
						confirmed=true;
					} else {
						return false;
					}
				}
			};
		});
		$('.recepientmemberlist').empty();
		$('.recepientmembers').removeClass('recepientmembersexpanded');		
		$("#recepientlist div").each(function() {$(this).removeClass("selected");});
		$('#recepientlist div input:radio:checked').parent().addClass("selected");
		id = $('#recepientlist input.recepientradio:checked').attr("id");
		$.post("/content/send-getorigin.php",{id:id},function(data){
			if (data!="") {
				$('#messagefromreply1l').css("font-weight","normal");
				$('#messagefromreply2l').css("font-weight","normal");
				if (data=="xreplyx") {
					$('#messagefromreply1l').css("font-weight","bold");
					$('#message-from').attr("disabled",true);
					$('#message-from-reply1').attr("checked",true);
				} else {
					$('#messagefromreply2l').css("font-weight","bold");
					$('#message-from').attr("disabled",false);
					$('#message-from-reply2').attr("checked",true);
					$('#message-from').val(data);
				}
			}
		});
	});	
	
	$('.recepientmembers').bind("click",function() {
		var groupid = $(this).parent().next("table").attr("id");
		var groupcount = $(this).prev("span").text();
		if (groupcount>1000 && !$(this).hasClass("recepientmembersexpanded")) { //Warn when expanding large groups
			if (!confirm("Expanding groups over 1000 contacts may cause some computers to slow down.\r\nAre you sure you want to expand this group?\r\n\r\nYou can view the contents of this group by clicking the Edit button.")) {
				return false;
			}
		}		
		hasexpanded = false;
		sameexpand = false;
		if ($(this).parent().next("table").children("tbody").attr("id")) {sameexpand=true;}
		$('.recepientmembers').each(function() {if ($(this).hasClass("recepientmembersexpanded")) {hasexpanded = true;};});
		if (sameexpand) {
			if (confirm("Collapsing this group/inbox will clear any filtering you've done.\r\n\r\nAre you sure you want to do this?")) {
				$('.recepientmemberlist').empty();
				$('.recepientmembers').removeClass('recepientmembersexpanded');	
				$('.recepientmemberlist').hide();
				return true;
			} else {
				return false;
			}
		}
		if (hasexpanded) {
			if (confirm("Selecting a different group/inbox will clear any filtering you've done.\r\n\r\nAre you sure you want to do this?")) {
				$('.recepientmemberlist').empty();
				$('.recepientmembers').removeClass('recepientmembersexpanded');	
			} else {
				return false;
			}
		}
		$(this).toggleClass("recepientmembersexpanded");
		if ($(this).hasClass("recepientmembersexpanded")) {
			$(this).parent().next("table").show();
			$(this).parent().next("table").html("<tbody><tr><td width=\"340\"><span class=\"loading\"><span>Loading...</span></span></td></tr></tbody>");
			$(this).parent().next("table").load("/content/send-groupcontacts.php",{'groupid':groupid},function() {
				$(this).parent().siblings().children().find("input:checkbox").attr("disabled",true).attr("checked",false);
				$(this).parent().siblings().children().find("td").addClass("disabled");
				$(this).parent().siblings().children().removeClass("selected");
				$(this).prev().removeClass("disabled").attr("checked",true).attr("disabled",false).addClass("selected");
				$(this).prev().children("input.recepientradio").attr("checked",true).attr("disabled",false);
				$(this).find("input").attr("disabled",false);
				$(this).find("input").attr("checked",true);
				$(this).find("label").removeClass("disabled");
			});

		}
		
	});
	
	$('#recepientlist input.recepientcheckbox').bind("click",function() { //Toggle group highlighting and auto checkbox control
		var enabled = 0;
		if ($(this).attr("checked")) {
			$(this).parent().addClass("selected");
		}
		else {$(this).parent().removeClass("selected");}		
		$("#recepientlist input.recepientcheckbox:checked").each(function() { //Count how many checkboxes are checked
			enabled=enabled+1;
			$(this).nextAll("a").removeClass("groupmembersexpanded");
		});
		$("#recepientlist input.recepientcheckbox:checked").each(function() {if ($(this).hasClass("offline")) {enabled=0;}});
		if (enabled>0) { //We have checked boxes!
			$('#deletegroup').removeClass("button-disabled").attr("disabled",false);
			$('#editgroup').removeClass("button-disabled").attr("disabled",false);
			$('#mergegroups').removeClass("button-disabled").attr("disabled",false);
			$('#splitgroup').removeClass("button-disabled").attr("disabled",false);
			$('#selectioncount').html(enabled+" ");
			if (enabled == 1) {//One checkbox
				$('#selectioncountplural').empty();
				$('#recepientlist input.recepientcheckbox:checked').nextAll('a.groupmembers').addClass("groupmembersexpanded");
				$('#mergegroups').addClass("button-disabled").attr("disabled",true);
				var groupid = $('#recepientlist .recepientcheckbox:checked').attr("id").substring(15);
				var type = $('#recepientlist li').attr("class");
				var data = new Array();
			}
			if (enabled > 1) {//More than one checkbox
				$('#selectioncountplural').html("s");
				$('#recepientlist input.recepientcheckbox:checked').nextAll("a").removeClass("groupmembersexpanded");
				$('#editgroup').addClass("button-disabled").attr("disabled",true);
				$('#splitgroup').addClass("button-disabled").attr("disabled",true);
			} 
		} else { //Nothing is checked
			$('#selectioncountplural').empty();
			$('#recepientlist a.groupmembersexpanded').removeClass("groupmembersexpanded");
			$('#deletegroup').addClass("button-disabled").attr("disabled",true);
			$('#editgroup').addClass("button-disabled").attr("disabled",true);
			$('#mergegroups').addClass("button-disabled").attr("disabled",true);
			$('#splitgroup').removeClass("button-disabled").attr("disabled",false);
			$('#selectioncount').empty();
		}
	});
	
	$('#recepientlist input.recepientcheckbox').bind("click",function() { //Toggle group highlighting and auto radio control
		var enabled = 0;
		if ($(this).attr("checked")) {
			$(this).parent().addClass("selected");
		}
		else {$(this).parent().removeClass("selected");}		
		$("#recepientlist input.recepientcheckbox:checked").each(function() { //Count how many checkboxes are checked
			enabled=enabled+1;
			$(this).nextAll("a").removeClass("groupmembersexpanded");
		});
		if (enabled>0) { //We have checked boxes!
			$('#deleteseed').removeClass("button-disabled").attr("disabled",false);
			$('#editseed').removeClass("button-disabled").attr("disabled",false);
			$('#printcodes').removeClass("button-disabled").attr("disabled",false);
			$('#emailcodes').removeClass("button-disabled").attr("disabled",false);
			$('#selectioncount').html(enabled+" ");
			if (enabled == 1) {//One checkbox
				$('#selectioncountplural').empty();
				$('#recepientlist input.recepientcheckbox:checked').nextAll('a.groupmembers').addClass("groupmembersexpanded");
				var groupid = $('#recepientlist .recepientcheckbox:checked').attr("id").substring(15);
				var type = $('#recepientlist li').attr("class");
				var data = new Array();
			}
		} else { //Nothing is checked
			$('#selectioncountplural').empty();
			$('#recepientlist a.groupmembersexpanded').removeClass("groupmembersexpanded");
			$('#deleteseed').addClass("button-disabled").attr("disabled",true);
			$('#editseed').addClass("button-disabled").attr("disabled",true);
			$('#printcodes').addClass("button-disabled").attr("disabled",true);
			$('#emailcodes').addClass("button-disabled").attr("disabled",true);
			$('#selectioncount').empty();
		}
	});
	
	function showhide(showid,hideid){
		document.getElementById(showid).style.visibility="visible";
		document.getElementById(hideid).style.visibility="hidden";
	}
	
/*
	$('.recepientmembers').bind("click",function() { //Toggle table of contacts within a group
		var groupid = $(this).parent().next("table").attr("id");
		var groupcount = $(this).prev("span").text();
		confirmed = false;
		expanded = false;
		var rows = $(this).parent().parent().parent().children();
		rows.each(function() {
			if ($(this).hasClass("recepientmembersexpanded")) {
				console.log("HIT");
			} else {
				console.log("MISS");
			}
		});
		if (groupcount>1000 && !$(this).hasClass("recepientmembersexpanded")) { //Warn when expanding large groups
			if (!confirm("Expanding groups over 1000 contacts may cause some computers to slow down.\r\nAre you sure you want to expand this group?\r\n\r\nYou can view the contents of this group by clicking the Edit button.")) {
				return false;
			}
		}
		$(this).toggleClass("recepientmembersexpanded");
		if ($(this).hasClass("recepientmembersexpanded")) {
			$(this).parent().next("table").toggle().html("<tbody><tr><td width=\"340\"><span class=\"loading\"><span>Loading...</span></span></td></tr></tbody>");
			$(this).parent().next("table").load("/content/send-groupcontacts.php",{'groupid':groupid},function() {
				$(this).parent().siblings().children().find("input:checkbox").attr("disabled",true).attr("checked",false);
				$(this).parent().siblings().children().find("td").addClass("disabled");
				$(this).parent().siblings().children().removeClass("selected");
				$(this).prev().removeClass("disabled").attr("checked",true).attr("disabled",false).addClass("selected");
				$(this).prev().children("input.recepientradio").attr("checked",true).attr("disabled",false);
				$(this).find("input").attr("disabled",false);
				$(this).find("input").attr("checked",true);
				$(this).find("label").removeClass("disabled");
			});
		} else {
			if (confirm("If you collapse this group, you will lose any changes you've made to the selection.\r\n\r\nAre you sure?")) {
				$(this).parent().next("table").empty();
				confirmed = true;
			}
			else {
				$(this).toggleClass("recepientmembersexpanded");
			}
		}
	});
*/
}

function JT_init(){ //Look for and control the tooltip spans
   $("span.tooltip")
   .hover(function(){JT_show($(this).attr("id"),this.id,$(this).attr("name"))},function(){$('#JT').remove()})
   .click(function(){return false});	   
}

function JT_show(url,linkId,title){ //Handle the showing of tooltips
	if (!title) {title="&nbsp;";}
	url = url.substr(8);
	url = url.split("+");
	url = url[0];
	var url = "/content/tooltips/"+url+".php?width=250";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}	
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='z-index:5000;width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
	}	
	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').load(url);
}

function getElementWidth(objectId) { //Gets an elements width
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) { //Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) { //Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params;
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
	if(evt.target) {
		evt.preventDefault();
	} else{
		evt.returnValue = false;
	}
}

// START AJAX UPLOAD

function $m(theVar){
	return document.getElementById(theVar)
}
function remove(theVar){
	var theParent = theVar.parentNode;
	theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	    obj.addEventListener(evType, fn, true)
	if(obj.attachEvent)
	    obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
	if(obj.detachEvent){
		obj.detachEvent('on'+type, fn);
	}else{
		obj.removeEventListener(type, fn, false);
	}
}
function isWebKit(){
	return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,id_element,html_show_loading,html_error_http,targetid){
	var detectWebKit = isWebKit();
	form = typeof(form)=="string"?$m(form):form;
	var erro="";
	if(form==null || typeof(form)=="undefined"){
		erro += "The form of 1st parameter does not exists.\n";
	}else if(form.nodeName.toLowerCase()!="form"){
		erro += "The form of 1st parameter its not a form.\n";
	}
	if($m(id_element)==null){
		erro += "The element of 3rd parameter does not exists.\n";
	}
	if(erro.length>0){
		alert("Error in call ajaxUpload:\n" + erro);
		return;
	}
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","ajax-temp");
	iframe.setAttribute("name","ajax-temp");
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	form.parentNode.appendChild(iframe);
	window.frames['ajax-temp'].name="ajax-temp";
	var doUpload = function(){
		removeEvent($m('ajax-temp'),"load", doUpload);
		var cross = "javascript: ";
		cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
		$m(id_element).innerHTML = html_error_http;
		$m('ajax-temp').src = cross;
		if(detectWebKit){
        	remove($m('ajax-temp'));
        } else {
        	setTimeout(function(){remove($m('ajax-temp'))},250);
        }
		setTimeout(function(){doPageImgUpload()},250);
    }
	addEvent($m('ajax-temp'),"load", doUpload);
	form.setAttribute("target","ajax-temp");
	form.setAttribute("action",url_action);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	if(html_show_loading.length > 0){
		$m(id_element).innerHTML = html_show_loading;
	}
	form.submit();
}

function doPageImgUpload() {
	var target = "#"+$('#imageUploadTarget').val();
	var src = $('#imageUploadPath').val();
	if (src !== undefined) {
		$(target).children("img").attr("src",src);
		setTimeout(function(){tb_remove()},750);
		return false;
	}
}

String.prototype.countOddChars=function(s1) {   
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;  
}  
