// find all the dialog links and attach dialog events for them, this is one time operation performed on the document load event
function CreateDialogs(selector, dialogOptions, ajaxParameters, ajaxCallBack) {
	if(selector === null || !selector) {
		selector='body .dialog';
	} else {
		if(typeof selector === 'string' || jQuery.isArray(selector)) {
			var arr;
			if(typeof selector === 'string') arr=selector.split(',');
			else arr=selector;
			selector='';
			for(var i=0;i<arr.length;i++) {
				selector+=arr[i]+' .dialog';
				if(i!==(arr.length-1)) selector+=','; // prevent colon at the end of string
			}
		} else return false;
	}
	var dialogs = jQuery(selector);
	jQuery.each(dialogs, function() {
		// create div element - attach it to dom, create reference for it in the link, initialize dialog
		if(!this.dialogBox) {
			var box = jQuery('<div>')
			.attr('title', this.title)
			.appendTo(jQuery('body'))
			.addClass('adialog')
			.dialog({
				autoOpen:false,
				closeOnEscape:false
			});
			if(dialogOptions) {
				box.dialog('option',dialogOptions);
			}
			this.dialogBox = box;
			box=null;
		}
		// click event which will open the dialog and download the ajax content
		jQuery(this).click(function(e) {
			// get position of the dialog box - just under the link activating it
			var el = this;
			var x = 0;
			var y = el.offsetHeight; // claculate the height of link activator
			var w = el.offsetWidth; // calculate the width of link activator - for proper position of the Mina favoriter box
			do {
				x+=el.offsetLeft;
				y+=el.offsetTop;
			} while(el = el.offsetParent)
			el=null;
			jQuery(this.dialogBox)
			.data('linkPosition',[x,y])
			.data('linkWidth',w)
			.load(this.href, ajaxParameters, ajaxCallBack)
			.dialog('open');
			return false;
		});
	});
}

// helper function getting the current scrolloffset
function getScrollOffset() {
	// in order to display the elements relatively when the viewport was scrolled, we need to calculate the scroll offset for x & y (sx,sy)
	var sx,sy;
	if(typeof(window.pageXOffset) === "number") { // W3C browsers
		sx=window.pageXOffset;
		sy=window.pageYOffset;
	} else if(document.body.scrollLeft||document.body.scrollTop) { // all IE except IE 6 strict
		sx=document.body.scrollLeft;
		sy=document.body.scrollTop;
	} else if(document.documentElement.scrollLeft||document.documentElement.scrollTop) { // IE 6 strict
		sx=document.documentElement.scrollLeft;
		sy=document.documentElement.scrollTop;
	} else {
		sx=sy=0;
	}
	return [sx,sy];
}

// helper function calculates position of the dialog box with the scroll offset included
function calculatePosition(p) {
	if (jQuery.isArray(p)) {
		var so = getScrollOffset();
		if(jQuery('#people-results').length > 0 && jQuery('#people-results').get(0).scrollTop!==0) so[1]+=jQuery('#people-results').get(0).scrollTop;
		var np = [p[0]-so[0],p[1]-so[1]];
		p = null;
		return np;
	}
	else return false;
}

jQuery(document).ready(function(){
	// dialog box for the addressbook contacts view
	// the scroller frame has to be 30px smaller then the dialog box
	var printabook=false;
	var noentries=function(e) {
		jQuery(e).find('#noentries').css('display','block');
		jQuery(e).find('#frame,#adfooter').css('display','none');
	};
	CreateDialogs('#favorites',
	{width:285,
	minHeight:75,
	open:function() {
		jQuery('#favorites a.dialog').addClass('open');
		var pos=jQuery(this).data('linkPosition');
		pos=calculatePosition(pos);
		pos[0]=pos[0]-jQuery(this).dialog('option','width')+jQuery(this).data('linkWidth')-10;
		jQuery(this).dialog('option','position',pos);},
	close:function() {jQuery('#favorites a.dialog').removeClass('open');}},
	false,
	function(e) {
		var self=this;
		if(jQuery('#frame').children().length===0) {
			noentries(this);
			return false;
		}
		jQuery(this).dialog('option','height',450); //430
		jQuery(this).css('height','430px');
		jQuery('#frame').css('height','400px');
		jQuery('.contacts li')
		.mouseover(function() {jQuery(this).addClass('active');})
		.mouseout(function() {jQuery(this).removeClass('active');});
		jQuery('.adialog a.del').click(function() {
			// firstcheck if the entry was the last one in section, if it was then delete also scroll link and remove display classes
			// from all scroll links...
			var last=false;
			if(jQuery(this).parents('ul.contacts').children().length === 1) last=true;
			// ...if it was last element, then remove the entire section, if not remove just the element (addressbook entry)
			if(last) {
				var sectionId=jQuery(this).parent().parent().parent().attr('id');
				jQuery(this).parents('#'+sectionId).remove();
			}
			else {
				jQuery(this).parent().remove();
			}
			if(jQuery('#frame').children().length===0) {
				noentries(self);
				jQuery(self).dialog('option','height','auto');
				jQuery(self).css('height','auto');
			}
			// ...then send AJAX call to remove the cookie on backend
			jQuery.get(this.href);
			return false;
		});
		// setting up print popup
		jQuery(this).find('#adfooter a').click(function(e) {
			e.preventDefault();
			printabook=window.open(this.href, 'addressbook', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=670,height=600,top=0,left=0', false);
			return false;
		});
	});
	// dialog boxes for adding contacts to addressbook
	CreateDialogs('.tools,#person-options,p.addressbook',
	{width:220,
	minHeight:75,
	open:function() {
		var pos=jQuery(this).data('linkPosition');
		var pos=calculatePosition(pos);
		jQuery(this).dialog('option','position',pos);}},
	false,
	function(e) {
		var self = this;
		jQuery(this).find('form input.cancel').click(function() {
			jQuery(self).dialog('close');
			return false;
		});
		if(typeof(jQuery('#favorites a.dialog').get(0))!=='undefined' && jQuery('#favorites a.dialog').get(0).dialogBox.dialog('isOpen')) jQuery('#favorites a.dialog').eq(0).trigger('click');
	});
});