JoopzUpdater = {
	insertConversation: function() {
		bubble = 'conv-' + window.convName;
		if ($(bubble) != undefined) {
			Element.remove('conv-' + window.convName);
		}
		new Insertion.Top('latest-conversations', window.convCode);
		Element.hide('conv-' + window.convName);
		Effect.BlindDown('conv-' + window.convName, {duration: 1.0});
		setTimeout("Effect.Pulsate('conv-' + window.convName)", 1000);
	},

	handleUpdates: function(resp, json) {
		if (json.conv != null) {
			if ($('conv-' + json.conv) != undefined) {
				Effect.Puff('conv-' + json.conv);
			}
			window.convName = json.conv;
			window.convCode = resp.responseText;
			window.latest = json.latest;
			setTimeout("JoopzUpdater.insertConversation()", 1000);
		}
	},

	ping: function(url) {
		new Ajax.Request(url, {
			onSuccess: JoopzUpdater.handleUpdates, 
			parameters: 'since=' + latest
		});
		setTimeout("JoopzUpdater.ping('" + url + "')", 10000);
	}
};

function sendPassword() {
	username = $F('username');
	if (username == '') {
		alert('Please provide your username or phone number.');
		return false;
	} else {
		window.location.href = '/users/send_password/' + username
	}
}

function updateCounter(limit) {
	msg = $('message-field');
	if (msg.value.length > limit) {
		msg.value = msg.value.substring(0, limit);
		alert('Your message cannot exceed ' + limit + ' characters.')
	}
	$$('#counter').first().innerHTML = '<strong>' + (limit  - msg.value.length).toString() + '</strong> characters left';
}

function toggleConversation(conv) {
	new Ajax.Request('/conversations/toggle', {	parameters: 'id=' + conv });
	
	if ($('conv_visibility_' + conv).innerHTML == 'collapse') {
		$('conv-' + conv).addClassName('collapsed');
		$('conv_visibility_' + conv).innerHTML = 'expand';
	} else {
		$('conv-' + conv).removeClassName('collapsed');
		$('conv_visibility_' + conv).innerHTML = 'collapse';
	}

	return false;
}


function checkForm() {
	msg = Form.Element.getValue('message-field');
	if (msg == null || msg == '' || msg == 'Type your message here' || msg == 'Type your reminder here') {
		Effect.Shake('message-field');
	} else if (Element.visible('option-individual') && !Field.present('phone-number')) {
		Effect.Shake('phone-number');
	} else if (Element.visible('option-new-group') && !Field.present('phone-numbers')) {
		Effect.Shake('phone-numbers');
	} else {
		return true;
	}
	return false;
}


/*
	SMS sending class
*/

Messages = {	
	/* Initialization - let's set all elements as they should be*/
	
	Init: function() {
		$("option-existing-group").style.display = "none";
		$("option-new-group").style.display = "none";
		$("option-send-later").style.display = "none";
		/* checking send time status */
		if ($('send_right_now').checked) {
			Element.addClassName($("option-send-now").parentNode.getElementsByTagName("div")[0],"selected");
			Element.removeClassName($("option-send-later").parentNode.getElementsByTagName("div")[0],"selected");
			$('option-send-later').style.display = "none";
		} else {
			Element.addClassName($("option-send-later").parentNode.getElementsByTagName("div")[0],"selected");
			Element.removeClassName($("option-send-now").parentNode.getElementsByTagName("div")[0],"selected");
			$('option-send-later').style.display = "block";
		}
		
		/* checking addressee status */
		var checkedType;
		['individual', 'existing-group', 'new-group'].each(
			function(type){
				Element.removeClassName($('label-' + type).parentNode,"selected");
				$('option-' + type ).style.display = "none";
			}
		);
		['individual', 'existing-group', 'new-group'].each(
			function(type){
				if ($('radio-' + type ).checked) checkedType = type;
				if (type == checkedType) {
					Element.addClassName($('label-' + type ).parentNode,"selected");
					$('option-' + type ).style.display = "block";
				}
			}
		);

		
	},
	
	/* 
		Setting send type. This function is an event handler and is called on click on the proper "send type" element.
		Params:
		(string) target - id of the container holding relevant form elements
	 */
	
	setType: function (target) {
		['individual', 'existing-group', 'new-group'].each(
			function(type) {
				typeDiv = $('option-' + type);
				if (typeDiv == undefined || typeDiv == null) return;
				disp = Element.getStyle('option-' + type, 'display')
				if (type == target) {
					if (disp == 'none') {
						Effect.BlindDown('option-' + type, {duration: 0.15});
					}
					Element.addClassName($("option-"+type).parentNode.getElementsByTagName("div")[0],"selected");
				} else {
					if (disp != 'none') {
						Effect.BlindUp('option-' + type, {duration: 0.15});
					}
					Element.removeClassName($("option-"+type).parentNode.getElementsByTagName("div")[0],"selected");
				}
			}
		);
	},
	
	/* 
		Setting send time. This function is an event handler and is called on click on the proper "send time" element.
	 */
	
	setDelivery: function () {
		var disp = Element.getStyle('option-send-later', 'display');
		if ($('delivery-scheduled').checked) {
			if (disp == 'none') Effect.BlindDown('option-send-later', {duration: 0.15});
			Element.addClassName($("option-send-later").parentNode.getElementsByTagName("div")[0],"selected");
			Element.removeClassName($("option-send-now").parentNode.getElementsByTagName("div")[0],"selected");
		} else {
			Effect.BlindUp('option-send-later', {duration: 0.15});
			Element.addClassName($("option-send-now").parentNode.getElementsByTagName("div")[0],"selected");
			Element.removeClassName($("option-send-later").parentNode.getElementsByTagName("div")[0],"selected");
		}
	}
};



/*
	Scheduled Messages Class
*/

Scheduled = {
	cleanup: function () {		
		if ($('scheduled-reminders') != undefined && $$('#scheduled-reminders dl').findAll(function(obj) { return obj.visible(); }).length == 0) { 
			Effect.Fade('scheduled-reminders');
		}
		if ($('scheduled-messages') != undefined && $$('#scheduled-messages dl').findAll(function(obj) { return obj.visible(); }).length == 0) { 
			Effect.Fade('scheduled-messages');
		}
	}
};

/*
	Group Management Class
*/

Groups = {
	removeContactFromGroup: function(contact_id, group_id) {	
		if(window.confirm("Are you sure you want to remove the contact from this group?")) {
			new Ajax.Request('/groups/remove_contact', {
				onFailure: function(resp) { alert('A failure occured'); },
				method: 'post',
				parameters: 'contact_id=' + encodeURIComponent(contact_id) + '&group_id=' + encodeURIComponent(group_id),
				evalScripts: true
			});
		}
		return false;
		
	},
	
	cleanup: function (contact_id, group_id, num_groups) {
		// page.visual_effect :fade, "group_#{contact.id}_#{group.id}"
        if ($('group_' + contact_id + '_' + group_id)) {
			Effect.Fade('group_' + contact_id + '_' + group_id);
		}
        if ($('group_' + group_id + '_contact_' + contact_id)) {
			Effect.Fade('group_' + group_id + '_contact_' + contact_id);
		}

        if (num_groups == 0 && $("group_status_#{contact.id}")) {
			Element.update('group_status_#{contact.id}', 'not a member of any groups.');
		}
	},
		
	destroy: function(target) {
		if(window.confirm("Deleting this group would also delete all messages associated with the group. Are you sure you want to do this?")) {
			new Ajax.Request('/groups/' + target, {
				onSuccess: function(resp) { 
					Effect.Fade('group_' + target);
				},
				onFailure: function(resp) { alert('A failure occured'); },
				method: 'delete'
			});
		}
		return false;
	}
}

/*
	Contacts Management Class
*/

Contacts = {
	/* Initialization - let's set all elements as they should be */

	destroy: function(target) {
		if(window.confirm("Deleting this contact would also delete all messages associated with him/her. Are you sure you want to do this?")) {
			new Ajax.Request('/contacts/' + target, {
				onSuccess: function(resp, json) { 
					Effect.Fade('contact_' + target, {transition: Effect.Transitions.pulse});
					Element.update('contacts_count', json.contacts_count);
				},
				onFailure: function(resp) { alert('A failure occured'); },
				parameters: 'contact[deleted]=true',
				method: 'put',
				evalScripts: true
			});
		}
		setTimeout("Contacts.fixRows();", 1500);
		return false;
	},

	fixRows: function() {
		var rows = $$('#contacts-table tr');
		var odd = true;
		rows.each( function(row, idx) {
			if (row.style.display != 'none') {
				if (odd) {
					row.addClassName("odd");
				} else {
					row.removeClassName("odd");
				}
				odd = !odd;
			}
		});
	},
	/*
		Enables inline editing of a contact name.
		Params:
		(string) target - id of the container holding relevant form elements
	 */

	editName: function (target) {
		Element.hide('name-link-' + target);
		Element.hide('name-display-' + target);
		Element.show('name-field-' + target);

		text = $('name-' + target).innerHTML;
		if (text == '' || text == null || text == undefined) text = 'Type name here';
		$('name-input-' + target).value = text;

		$('name-input-' + target).onblur = function() { return Contacts.updateName(target); }
		$('name-form-' + target).onsubmit = function() { return Contacts.updateName(target); }
		
		Form.focusFirstElement('name-form-' + target);
		
		return false;
	},


	/*
		Updates a contact name.
		Params:
		(string) target - id of the container holding relevant form elements
	 */

	updateName: function (target) {
		name = $F('name-input-' + target);
		if (name == 'Type name here') {
			Element.show('name-link-' + target); 
		} else {
			Element.show('indicator-' + target);
			new Ajax.Request('/contacts/' + target, {
				onSuccess: function(resp) { 
					Element.hide('indicator-' + target);
					if (name == '') {
						Element.hide('name-' + target);
						Element.show('name-link-' + target);
					} else {	
						Element.update('name-' + target, name); 
						Element.show('name-' + target);
						Element.show('name-display-' + target); 
					}
					$('name-input-' + target).onblur = null;
				},
				onFailure: function(resp) { alert('A failure occured'); },
				parameters: 'contact[name]=' + encodeURIComponent(name),
				method: 'put'
			});
		}
		Element.hide('name-field-' + target);
		Element.show('name-display-' + target);
		return false;
	},


	/*
		Enables "Add to another Contact" panel
		Params:
		(object) oObject - triggering object
	 */

	AddAnotherContact: function (group_id) {
		//var panel = document.getElementsByClassName("add-to-contact",oObject.parentNode.parentNode.parentNode.parentNode)[0];
		Effect.BlindDown('add-another-contact-panel-' + group_id, {duration: 0.15});
		Effect.Fade(oObject);
		return false;
	},

	/*
		Cancels "Add to another group" panel
		Params:
		(string) sID - ID of the contact
	 */

	CancelAddAnotherContact: function (sID) {
		Effect.BlindUp('add-another-contact-panel-' + sID, {duration: 0.15});
		Effect.Appear('add-another-contact-' + sID);
		return false;
	},

	/*
		Adds a contact to another group
		Params:
		(string) sID - ID of the contact
	 */

	OKAddAnotherContact: function (sID) {
		Effect.BlindUp('add-another-contact-panel-' + sID, {duration: 0.15});
		Effect.Appear('add-another-contact-' + sID);
		return true;
	}


};



History = {
	toggle: function(element_id) {
		side_item = $(element_id);
		item_history = $(element_id + '_history')
		
		if (Element.visible(item_history)) {
			Effect.BlindUp(item_history,{
				duration:0.15,
				afterFinish: function(effect) {
					Element.removeClassName(side_item,"selected");
				}
			});
			
		} else {
			Element.addClassName(side_item,"selected");
			Effect.BlindDown(item_history,{duration:0.15});	
		}
		
	}
};

FAQList = {

	container: null,
	answers: null,
	faqs: null,
	 
	Init: function() {
		FAQList.container = document.getElementsByClassName('faq')[0];
		FAQList.answers = FAQList.container.getElementsByTagName('dd');
		for (var i=0;i<FAQList.answers.length;i++) {
			FAQList.answers[i].style.display = 'none';
		}
		FAQList.faqs = FAQList.container.getElementsByTagName('dt');
		for (var i=0;i<FAQList.faqs.length;i++) {
			FAQList.faqs[i].getElementsByTagName('a')[0].onclick = FAQList.TriggerBehavior;
		}
	},
		
	TriggerBehavior: function() {
		var answer = this.parentNode.parentNode.getElementsByTagName('dd')[0];
		style = Element.getStyle(answer,'display');
		if (style == 'none') {
			//FAQList.CollapseAll();
			Element.addClassName(this.parentNode.parentNode,'active');
			Effect.SlideDown(answer);
		} else {
			Element.removeClassName(this.parentNode.parentNode,'active');
			Effect.SlideUp(answer);
			
		}
	},
	
	CollapseAll: function() {
		for (var i=0;i<FAQList.answers.length;i++) {
			Element.removeClassName(FAQList.answers[i].parentNode,'active');
			var style = Element.getStyle(FAQList.answers[i],'display');
			if (style != 'none') {
				Effect.BlindUp(FAQList.answers[i],{duration: 0.15});
			}
		}
	}
	
};


Hotkey = Class.create();
Hotkey.list = $A();
Hotkey.prototype = {
	character: null,
	action: function(){},
	initialize: function(character, action) {
		this.character = character;
		this.action = action;
	},
	matches: function(character) {
		return (this.character == character);
	}
}
Hotkey.add = function(character, action) {
	Hotkey.list.unshift(new Hotkey(character, action));
}
Hotkey.remove = function(character) {
	Hotkey.list.each(function(h,idx){
		if(h.character == character)
		  Hotkey.list.splice(idx, 1);
	});
}
Hotkey.process = function(event) {
  event = event || window.event;
  if (event) {
	  // Require modifier (Note: different by platform/browser) 
    if (event.ctrlKey || event.altKey || event.metaKey) {
      var code = event.charCode || event.which || event.keyCode;
      var character = String.fromCharCode(code).toLowerCase();
      if (event.shiftKey) character = character.toUpperCase();
      if(hotkey = Hotkey.list.detect(function(hk){ return hk.matches(character); }))
        hotkey.action();
    }
  }
};

function breakout_of_frame()
{
  // see http://www.thesitewizard.com/archive/framebreak.shtml
  // for an explanation of this script and how to use it on your
  // own website
  if (top.location != location) {
    top.location.href = document.location.href ;
  }
}

function breakout_of_frame_if_ie6() {
	if (Prototype.Browser.IE) {
		var version = parseFloat(navigator.userAgent.split('IE ')[1]);
		if (version < 7.0) {
			breakout_of_frame();
		}
	}
}
