jQuery(function ($) {
	if (!window.console) {
		console = {
			log: function () {}
		};
	}

	(function applySafariOffsetPatch() {
		// small fix for old safari versions compatibility

		// this bug occures 
		// on iPhone OS since 3.2 version (iPad)
		// and on iOS since 4.0 version

		// as of 1.4.2 the mobile safari reports wrong values on offset()
		// http://dev.jquery.com/ticket/6446
		// remove once it's fixed
		if (/webkit.*mobile/i.test(navigator.userAgent) && /; CPU.*OS (?:3_2|4_0)/i.test(navigator.userAgent) && "getBoundingClientRect" in document.documentElement) {
			(function ($) {
				$.fn.offsetOld = $.fn.offset;
				$.fn.offset = function () {
					var result = this.offsetOld();
					result.top -= window.scrollY;
					result.left -= window.scrollX;

					return result;
				};
			})(jQuery);
		}

		$.browser.mobileSafari = /webkit.*mobile/i.test(navigator.userAgent)
		$.fn.cssKluge = function (css) {
			if ($.browser.mobileSafari) {
				css.top -= window.scrollY;
				css.left -= window.scrollX;
			}
			return this.css(css);
		};
	})();


	var phoneBook = $('#phoneBook');
	var defaultValue = phoneBook.val();

	phoneBook
		.bind('keypress keydown keyup', function (ev) {
			var isEmpty = $(this).is('.field-with-message, .type-email');
			var currentValue = isEmpty ? '' : $(this).val();
			//console.log('checking for key', ev.which, currentValue, isEmpty);
			if (isEmpty || (ev.which && ev.which !== 13 && ev.which !== 9 && $('#comunica').data('current-value') !== currentValue)) {
				//console.log('removing classes', ev.which);
				$('#comunica')
					.removeClass('type-cell type-fax type-tel type-email')
					.data('current-value', currentValue);
			}

			ev.stopPropagation();
		})
		.fieldWithMessage()
		.autocomplete('/api/addressbook/search/', {
			width: phoneBook.outerWidth(),
			scrollHeight: 400,
			minChars: 2,
			matchContains: true,
			matchSubset: true,
			max: 50,
			delay: 10,
			cacheLength: 10,
			resultsClass: 'ac_results comunica-ac-results',
			selectFirst: true,
			parse: function(contacts) {
				var result		= [];

				$(contacts).each(function (index, contact) {
					var vcardContents = [
						contact.contactName,
						$(contact.data || []).map(function (index, item) {
							return item.value;
						}).get().join('\n')
					].join('\n');

					$(contact.data || []).each(function (index, item) {
						if (index === 0) {
							item.contactName = contact.contactName;
						}

						result.push({
							data: item,
							value: vcardContents,
							result: item.value
						});
					});
				});
				
				return result;
			},
			formatItem: function(item) {
				var result = [];

				if (item.contactName) {
					result.push('<div class="contact_name">');
					result.push(item.contactName);
					result.push('</div>');
				}

				result.push('<div class="contact_number">');
				result.push('<span class="type ' + item.type + '"></span>');
				result.push(item.value);
				result.push('</div>');

				return result.join('');
			}
		})
		.result(function(ev, item) {
			$('#comunica')
				.removeClass('type-cell type-fax type-tel type-email')
				.data('current-value', $(this).val());

			$('#comunica')
				.addClass('type-' + item.type);
			//console.log('adding class for type', item.type);
		});

	var callmeLink = (function () {
		var dialogEl = $('#comunica .callerid-dialog');

		function sendCallmeLink(callerId) {
			$.getJSON(
				'/api/webphone/',
				{
					keep_session: 1,
					method: 'link',
					operation: 'get_create',
					type: 'flash',
					number: callerId.number,
					uri: callerId.alias,
					lang: $('html').attr('lang'),
					ts: new Date().getTime()
				},
				function (link) {
					//console.log(link, link.url);
					var mailTo = dialogEl.data('mailTemplate')
						.replace(/@LINK@/, encodeURIComponent(link.url))
						.replace(/@EXPIRATION@/, encodeURIComponent(link.locale.expiration.long));
					//console.log(mailTo);
					location.href = mailTo;
				}
			);
		}

		function showCallerIdChooser() {
			var callerIdList = dialogEl.data('callerIdList');
			if (callerIdList.length > 1) {
				dialogEl.dialog('open');
			} else {
				sendCallmeLink(callerIdList[0]);
			}
		}

		function initializeCallerIdChooser(mailTemplate, value, callerIdList) {
			var list = [ '<ul>' ];
			$.each(callerIdList, function (i, callerId) {
				list.push('<li id=callerid-list-item::' + i + '>' + callerId.number + '</li>');
			});
			list.push('</ul>');
			dialogEl.html(list.join(''));

			dialogEl
				.dialog({
					autoOpen: false,
					modal: true,
					resizable: false,
					closeOnEscape: true,
					draggable: false,
					width: 400
					//height: 450
				})
				.find('li')
					.click(function () {
						dialogEl.dialog('close');
						var offs = parseInt($(this).attr('id').split('::')[1]);
						sendCallmeLink(dialogEl.data('callerIdList')[offs]);
					})
				.end()
				.data('initialized', true)
				.data('mailTemplate',
					mailTemplate.replace(/^mailto:/, 'mailto:' + encodeURIComponent(value))
				)
				.data('callerIdList', callerIdList);
		}

		return {
			send: function (mailTemplate, value) {
				if (dialogEl.data('initialized')) {
					showCallerIdChooser();
				} else {
					$.getJSON(
						'/api/webphone/callerid/list/',
						function (callerIdList) {
							if (callerIdList.length) {
								initializeCallerIdChooser(mailTemplate, value, callerIdList);
								showCallerIdChooser();
							}
						}
					);
				}
			}
		};
	})();

	$('#comunica li > a, #comunica span > a').click(function () {
		var value = phoneBook.is('.field-with-message') ?
			'' : phoneBook.val();

		var target = $(this);
		target.blur();

		$.getJSON('/api/comunica/', {
			q: value,
			action: target[0].className,
			type: $('#comunica').hasClass('communicate content-box') ? 'utente' : 'box'
		}, function () {
			if (target.is('.panelPhone') && window.PhoneWrapper) {
				PhoneWrapper.call(value);
			} else if (value && target.is('.panelCML') && !$('#comunica').is('.anonymous-usage')) {
				callmeLink.send(target.find('span.collapsed').text(), value);
			} else {
				location.href = target[0].href.replace(/numero=[^&]*/, 'numero=' + encodeURIComponent(value));
			}
		});

		return false;
	});
});

