// Global object
var ig = window.ig = {};

//qTip calendar style
$.fn.qtip.styles.calendar = { 
   width: 270,
   padding: 5,   
   color: 'black',
   textAlign: 'left',
   border: {
      width: 7,
      radius: 5,
   },
   tip: 'bottomLeft',
   name: 'light' 
};

// Tree acos
ig.TreeAco = {};

ig.TreeAco.update = function() {
	var tree_acos=$.tree.reference('#tree-acos'),tree_aros=$.tree.reference('#tree-contacts'),acos=[],aro='';
	$.metadata.setType("attr", "data");
	aro = $(tree_aros.selected).metadata().aro;
	acos = jQuery.map($.tree.plugins.checkbox.get_checked(tree_acos),function(node,i){
		if (tree_acos.parent(node) == -1 || $(tree_acos.parent(node)).children('a').hasClass('undetermined')) {
			return node.id;
		} else {
			return null;
		}	
	});
	$('#node-detail').html('<p class="dayviewer-loading"></p>');
	$.post(
		'/privacy/update',
		$.param({'data[acos][]':acos,'data[aro][model]':aro.model,'data[aro][foreign_key]':aro.foreign_key}),
		function(json){
			ig.TreeAco.create('#tree-acos');
		},
		'json'
	);
	return false;
}; 

ig.TreeAco.create = function(el) {
	var tree_aros=$.tree.reference('#tree-contacts'),aro,html='';
	if ($('#introduction-text .privacy-group').is(':hidden')) {
 		$('#introduction-text').children('div').hide();	
		$('#introduction-text .privacy-group').fadeIn(300);		
	}	
	html += '<div id="tree-acos"></div>'+
	'<div style="clear:both;padding-top:15px;">'+
		'<div style="text-align:right;padding-bottom:5px;">'+	
			'<select id="QuickSetMenu">'+
				'<option value="">Quick Set</option>'+
				'<option value="check">Check All</option>'+
				'<option value="uncheck">Uncheck All</option>'+
				'<option value="personal">No Personal Contact Info</option>'+
			'</select>'+
		'</div>'+	
		'<div style="text-align:right;">'+
			'<input type="button" value="Save" class="button" onclick="return ig.TreeAco.update();">'+
		'</div>'+		
	'</div>';
	$('#node-detail').html(html);	
	$('#QuickSetMenu').change(function(){
		switch($(this).val()) {
			case 'check':
				jQuery.tree.plugins.checkbox.check($(el).find('li:first'));
				break;
			case 'uncheck':
				jQuery.tree.plugins.checkbox.uncheck($(el).find('li:first'));
				break;
			case 'personal':
				jQuery.tree.plugins.checkbox.uncheck($(el).find('li:first'));
				$.each(['interests','personal_statement','country','company','education','about_me','business_contact_details'], function(i,id){
					jQuery.tree.plugins.checkbox.check($(el).find('li[id='+id+']'));
				});
				break;
		}
	});
	$.metadata.setType("attr", "data");
	aro = $(tree_aros.selected).metadata().aro;
	$(el).tree({
  		data : {
				type : "json",
				opts : {
					url : '/privacy/get?'+$.param({'aro[model]':aro.model,'aro[foreign_key]':aro.foreign_key})
				}
			},		  	
		types : {
			"default" : {
				clickable	: true,
				renameable	: false,
				deletable	: false,
				creatable	: false,
				draggable	: false
			}
		},			
		ui : {
			theme_name : "checkbox",
			//Fixed issue 271
			selected_parent_close : false 
		},
		plugins : {
			checkbox : {}
		},
		callback : {
			onload : function(tree_obj) {
				$.metadata.setType("attr", "data");
				$.each($(el).find('li'),function(i,node){
					if ($(node).metadata().check) {
						 jQuery.tree.plugins.checkbox.check(node);
					}	
				});
			}
		}
	});
};

// Tree contacts
ig.TreeContact = {};

ig.TreeContact.del = function(msg){
	if (confirm(msg)) $.tree.reference('#tree-contacts').remove();
	return false;
}

ig.TreeContact.addPhantom = function(node_id){
	
	if ($('#introduction-text .manually-add-button').is(':hidden')) {
 		$('#introduction-text').children('div').hide();	
		$('#introduction-text .manually-add-button').fadeIn(300);		
	}
	var handle = function(f){
		
		f.submit(function(){
						 
			$(this).ajaxSubmit({					   
				beforeSubmit:function(){document.forms['submit_images'].submit();$(f).parent().html('<p class="dayviewer-loading"></p>'); },	
				success: function(){					
					
					$.tree.reference('#tree-contacts').refresh( $.tree.reference('#tree-contacts').selected );
				}
			});
			return false;	
		});						
	}; 	
	$('#node-detail').html('<p class="dayviewer-loading"></p>').load('/add-contact',{node_id:node_id},function(){
		$('#PhantomContactPid').val($($.tree.reference('#tree-contacts').selected).attr('id'));
		handle($(this).find('form'));
	});
}

ig.TreeContact.editPhantom = function(){
	$.metadata.setType("attr", "data");
	var data = $($($.tree.reference('#tree-contacts').selected).get(0)).metadata();
	var handle = function(f){
		f.submit(function(){
			$(this).ajaxSubmit({
				beforeSubmit:function(){document.forms['submit_images'].submit(); $(f).parent().html('<p class="dayviewer-loading"></p>'); },		
				success: function(){
					$.tree.reference('#tree-contacts').refresh( $.tree.reference('#tree-contacts').parent($($.tree.reference('#tree-contacts').selected)) );
				}
			});
			return false;	
		});						
	}; 	
	$('#node-detail').html('<p class="dayviewer-loading"></p>').load('/edit-contact/'+data.id,function(){
		handle($(this).find('form'));
	});	
}

ig.TreeContact.sendUnsorted = function(){
	$.tree.reference('#tree-contacts').moved($.tree.reference('#tree-contacts').selected, $('#tree-contacts li[rel=unsorted]').children("a:eq(0)"), "inside", false, false);
};

ig.TreeContact.removeDuplicated = function(){
	$.getJSON('/contacts/duplicated',function(json){
		if (json.status) {
			$.tree.reference('#tree-contacts').refresh();
		} else {
			//@todo error
		}
	});
};

ig.TreeContact.MessageGroup = function(){
	var contacts = [];
	$.each($.tree.reference('#tree-contacts').children($.tree.reference('#tree-contacts').selected),function(i,el){
		if ($(el).attr('rel') == 'contact') {
			$.metadata.setType("attr", "data");
			var data = $(el).metadata();			
			contacts.push(data.id);
		}
	});
	if (contacts.length) {
		ig.redirect('/messages/compose?'+$.param({to:contacts}));
	}
};

ig.TreeContact.InviteGroupEvent = function(){
	var contacts = [];
	$.each($.tree.reference('#tree-contacts').children($.tree.reference('#tree-contacts').selected),function(i,el){
		if ($(el).attr('rel') == 'contact') {
			$.metadata.setType("attr", "data");
			var data = $(el).metadata();			
			contacts.push(data.id);
		} else if ($(el).attr('rel') == 'phantom') {
			$.metadata.setType("attr", "data");
			var data = $(el).metadata();			
			contacts.push(data.email);			
		}
	});
	if (contacts.length) {
		ig.Calendar.addEntry(2,contacts);
		ig.Calendar.setDate(new Date, false);
	}
};

ig.TreeContact.InviteGroupChat = function(){
	var contacts = [];
	$.each($.tree.reference('#tree-contacts').children($.tree.reference('#tree-contacts').selected),function(i,el){
		if ($(el).attr('rel') == 'contact') {
			$.metadata.setType("attr", "data");
			var data = $(el).metadata();			
			contacts.push(data.id);
		}
	});
	if (contacts.length) {
		ig.Calendar.addEntry(4,contacts);
		ig.Calendar.setDate(new Date, false);
	}
};

//api form loader
ig.loadAjaxForm = function( fdom ){

	if (!fdom){alert('elements DOM cannot be empty');return false;}
	var fid = $(fdom).attr('id');
	if(!fid){alert('form id attr is empty');return false;}

	if (fid == 'addUserGroupForm') {
		var opt={
			target:$(fdom).parent(),
			beforeSubmit:ig.TreeContact.block,
			success:function(){
				var $node = $.tree.reference('#tree-contacts').get_node('li[gid='+$('#GroupId').val()+']');
				$node.addClass('hasFriends');
				$node.removeClass('hasChildren');
				ig.TreeContact.unblock();
			}
		};
	} else if($(fdom).parent().children().size() == 1){
		var opt={target:$(fdom).parent(),beforeSubmit:ig.block,success:ig.unblock};
	}else{
		var div = $('<div></div>');
		$(fdom).wrap(div);
		var opt ={target:$(fdom).parent(),beforeSubmit:ig.block,success:ig.unblock};
	}
	$(fdom).ajaxSubmit(opt);
	return false;	
};

//API calendar
ig.Calendar = {};

ig.Calendar.dayDate = null;
ig.Calendar.allDay = null;
ig.Calendar.indicator = '<p class="dayviewer-loading"></p>';

ig.Calendar.Summary = {};
ig.Calendar.Summary.indicator = '<p class="indicator"></p>';

ig.Calendar.Summary.print = function(view){
	var printDiv = $('<div></div>');
	printDiv.html($('.slide-out-'+view).html());
	printDiv.find('div.header div.input').remove();
	printDiv.children('div:first').remove();
	printDiv.find('*').css({color:'black'});
	printDiv.jqprint();
	return false;
};

ig.Calendar.Summary.onSlideOut = function(obj,el) {
	var view = $('#calendar').fullCalendar('getView');
    var content = $(obj).find('.slide-out-'+view.name);
    var params = {
		start: view.start.getTime() / 1000, 
		end: view.end.getTime() / 1000,
		filter: $(el).val()?$(el).val():''
	};           		
	content.show().html(ig.Calendar.Summary.indicator).load('/calendar/summary/'+view.name+'?'+$.param(params));
};

ig.Calendar.Summary.onSlideIn = function(obj) {
	$(obj).find('.slide-out-content > div').hide();           
};

ig.Calendar.Summary.tabSlideOut = function(el) {
   $(el).tabSlideOut({
   	   tabHandle: '.handle',
       pathToTabImage: 'img/calendar-summary-button.png',
       imageHeight: '154px',
       imageWidth: '61px',    
       tabLocation: 'right',
       speed: 300,
       action: 'click',
       topPos: '25px',
       fixedPosition: true,
       onSlideOut : ig.Calendar.Summary.onSlideOut,
       onSlideIn : ig.Calendar.Summary.onSlideIn
   });		
};

ig.Calendar.Form = {};

ig.Calendar.initNote = function(f) {
	
	$(f).find('input.date').datepicker({
		dateFormat: 'dd M yy',
		changeMonth: true,
		changeYear: true,
		showOn: 'both',
		buttonImage: '/img/icons/icon_day.gif',
		buttonImageOnly: true
	}).attr('readonly','readonly');
	
	$(f).find('.ui-icon-help').qtip({
        content: { 
			text: $('.bullet-info'), 
			title: {text: 'Help', button: 'x'} 
    	},
        style: {
    		width: 400,	
			height:38,
    		title: {background: '#ddecf4'},		        		
    		border: {color: '#9BC4E2'},		        		
    		name: 'calendar',
    		tip: true
    	},
    	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}},
		hide: {when: {event: 'mouseout'}, effect: {length: 10}},
		show: {solo: true, effect: {length: 50}}
    });
    
	//$(f).find('input.datetime').datetime({ format: 'yy-mm-dd hh:ii O' }).attr('readonly',true);
	
	$(f).find('#color').colorPicker();
	$(f).find('#textColor').colorPicker();
	
	if ($(f).find('input.allDay').is(':checked')) ig.Calendar.TimeHide(f); else ig.Calendar.TimeShow(f);

	$(f).find('div.accordion .ui-accordion-header').click(function(){$(this).next().toggle();return false;}).next().hide();
	$(f).find('div.accordion').children('div:has(div.error-message)').show();

	ig.Calendar.initReminder(f);
	
	ig.Calendar.initRecur(f);	
};

ig.Calendar.initTask = function(f) {
	$(f).find('input.date').datepicker({
		dateFormat: 'dd M yy',
		changeMonth: true,
		changeYear: true,
		showOn: 'both',			
		buttonImage: '/img/icons/icon_day.gif',
		buttonImageOnly: true
	});
	
	$(f).find('.ui-icon-help').qtip({
        content: { 
			text: $('.bullet-info'), 
			title: {text: 'Help', button: 'x'} 
    	},
        style: {
    		width: 400,	
			height:38,
    		title: {background: '#ddecf4'},		        		
    		border: {color: '#9BC4E2'},		        		
    		name: 'calendar',
    		tip: true
    	},
    	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}},
		hide: {when: {event: 'mouseout'}, effect: {length: 10}},
		show: {solo: true, effect: {length: 50}}
    });
	
	//$(f).find('input.datetime').datetime({ format: 'yy-mm-dd hh:ii O' }).attr('readonly',true);
	
	$(f).find('#color').colorPicker();
	$(f).find('#textColor').colorPicker();		
	
	$(f).find("#percent").slider({
		step: 5,
		value: $(f).find("#TaskPercent").val(),
		slide: function(event, ui) {
			$(f).find("#TaskPercent").val(ui.value);
			$(f).find('div.percent > span.value').text(ui.value + '%');
		}			
	});
	$(f).find('div.percent > span.value').text($(f).find("#percent").slider("value") + '%');
	
	if ($(f).find('input.allDay').is(':checked')) ig.Calendar.TimeHide(f); else ig.Calendar.TimeShow(f);

	$(f).find('div.accordion .ui-accordion-header').click(function(){$(this).next().toggle();return false;}).next().hide();
	$(f).find('div.accordion').children('div:has(div.error-message)').show();
	
	ig.Calendar.initReminder(f);		

	ig.Calendar.initRecur(f);	
};

ig.Calendar.initPayment = function(f) {
	$(f).find('input.date').datepicker({
		dateFormat: 'dd M yy',
		changeMonth: true,
		changeYear: true,
		showOn: 'both',
		buttonImage: '/img/icons/icon_day.gif',
		buttonImageOnly: true
	});
	
	$(f).find('.ui-icon-help').qtip({
        content: { 
			text: $('.bullet-info'), 
			title: {text: 'Help', button: 'x'} 
    	},
        style: {
    		width: 400,	
			height:38,
    		title: {background: '#ddecf4'},		        		
    		border: {color: '#9BC4E2'},		        		
    		name: 'calendar',
    		tip: true
    	},
    	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}},
		hide: {when: {event: 'mouseout'}, effect: {length: 10}},
		show: {solo: true, effect: {length: 50}}
    });
	
	//$(f).find('input.datetime').datetime({ format: 'yy-mm-dd hh:ii O' }).attr('readonly',true);
    
	$(f).find('#color').colorPicker();
	$(f).find('#textColor').colorPicker();				

	if ($(f).find('input.allDay').is(':checked')) ig.Calendar.TimeHide(f); else ig.Calendar.TimeShow(f);

	$(f).find('div.accordion .ui-accordion-header').click(function(){$(this).next().toggle();return false;}).next().hide();
	$(f).find('div.accordion').children('div:has(div.error-message)').show();

	ig.Calendar.initReminder(f);	

	ig.Calendar.initRecur(f);	
};

ig.Calendar.initEvent = function(f) {
	$(f).find('input.date').datepicker({
		dateFormat: 'dd M yy',
		changeMonth: true,
		changeYear: true,
		showOn: 'both',			
		buttonImage: '/img/icons/icon_day.gif',
		buttonImageOnly: true
	});
	
	$(f).find('.ui-icon-help').qtip({
        content: { 
			text: $('.bullet-info'), 
			title: {text: 'Help', button: 'x'} 
    	},
        style: {
    		width: 400,	
			height:38,
    		title: {background: '#ddecf4'},		        		
    		border: {color: '#9BC4E2'},		        		
    		name: 'calendar',
    		tip: true
    	},
    	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}},
		hide: {when: {event: 'mouseout'}, effect: {length: 10}},
		show: {solo: true, effect: {length: 50}}
    });
	
	//$(f).find('input.datetime').datetime({ format: 'yy-mm-dd hh:ii O' }).attr('readonly',true);
    
	$(f).find('#color').colorPicker();
	$(f).find('#textColor').colorPicker();

	$(f).find('select.contacts').fcbkcomplete({
        json_url: null,
        cache: true,
        filter_hide: true,
		firstselected: true,
        filter_selected: true,
        height: 5	
    });

	if ($(f).find('input.allDay').is(':checked')) ig.Calendar.TimeHide(f); else ig.Calendar.TimeShow(f);

	$(f).find('.accordion .ui-accordion-header').click(function(){$(this).next().toggle();return false;}).next().hide();
	$(f).find('div.accordion').children('div:has(div.error-message)').show();

	ig.Calendar.initReminder(f);	

	ig.Calendar.initRecur(f);		
};

ig.Calendar.initConference = function(f) {
	$(f).find('input.date').datepicker({
		dateFormat: 'dd M yy',
		changeMonth: true,
		changeYear: true,
		showOn: 'both',			
		buttonImage: '/img/icons/icon_day.gif',
		buttonImageOnly: true
	});
	
	$(f).find('.ui-icon-help').qtip({
        content: { 
			text: $('.bullet-info'), 
			title: {text: 'Help', button: 'x'} 
    	},
        style: {
    		width: 400,	
			height:38,
    		title: {background: '#ddecf4'},		        		
    		border: {color: '#9BC4E2'},		        		
    		name: 'calendar',
    		tip: true
    	},
    	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}},
		hide: {when: {event: 'mouseout'}, effect: {length: 10}},
		show: {solo: true, effect: {length: 50}}
    });
	
	//$(f).find('input.datetime').datetime({ format: 'yy-mm-dd hh:ii O' }).attr('readonly',true);
    
	$(f).find('#color').colorPicker();
	$(f).find('#textColor').colorPicker();

	$(f).find('select.contacts').fcbkcomplete({
        json_url: null,
        cache: true,
        filter_hide: true,
		firstselected: true,
        filter_selected: true,
        height: 5	
    });

	if ($(f).find('input.allDay').is(':checked')) ig.Calendar.TimeHide(f); else ig.Calendar.TimeShow(f);

	$(f).find('.accordion .ui-accordion-header').click(function(){$(this).next().toggle();return false;}).next().hide();
	$(f).find('div.accordion').children('div:has(div.error-message)').show();

	ig.Calendar.initReminder(f);

	ig.Calendar.initRecur(f);		
};

ig.Calendar.initReminder = function(f) {
	$(f).find('div.accordion div.reminder input.number').bind('focus keyup',function(){
		var n = $(f).find('div.accordion div.reminder input.number').val(),u = $(f).find('div.accordion div.reminder select.unit').val();
		if (u == 'minutes' && parseInt(n)*60 > 28*24*3600) {
			n = 40320;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'hours' && parseInt(n)*3600 > 28*24*3600) {
			n = 672;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'days' && parseInt(n)*24*3600 > 28*24*3600) {
			n = 28;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'weeks' && parseInt(n)*7*24*3600 > 28*24*3600) {
			n = 4;
			$(f).find('div.accordion div.reminder input.number').val(n);
		}		
		if (n && u) {
			$(f).find('div.accordion span.summary-reminder').text(n + ' ' + u);
		} else {
			$(f).find('div.accordion span.summary-reminder').text('none');
		}	
	}).keyup();
	$(f).find('div.accordion div.reminder select.unit').change(function(){
		var n = $(f).find('div.accordion div.reminder input.number').val(),u = $(f).find('div.accordion div.reminder select.unit').val();
		if (u == 'minutes' && parseInt(n)*60 > 28*24*3600) {
			n = 40320;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'hours' && parseInt(n)*3600 > 28*24*3600) {
			n = 672;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'days' && parseInt(n)*24*3600 > 28*24*3600) {
			n = 28;
			$(f).find('div.accordion div.reminder input.number').val(n);
		} else if (u == 'weeks' && parseInt(n)*7*24*3600 > 28*24*3600) {
			n = 4;
			$(f).find('div.accordion div.reminder input.number').val(n);
		}			
		if (n && u) {
			$(f).find('div.accordion span.summary-reminder').text(n + ' ' + u);
		} else {
			$(f).find('div.accordion span.summary-reminder').text('none');
		}	
	});	
};

ig.Calendar.initRecur = function(f) {
	$(f).find('select.frequency').change(function(){
		$(f).find('div.recur > div:not(:first)').hide();
		switch($(this).val()){
			case 'daily':
				$(f).find('div.recur span.interval_caption').text('days');
				$(f).find('div.recur div.interval').show();
				$(f).find('div.recur div.rstart').show();
				$(f).find('div.recur div.endson').show();
				break;
			case 'weekly':
				$(f).find('div.recur span.interval_caption').text('weeks');
				$(f).find('div.recur div.interval').show();
				$(f).find('div.recur div.repeaton').show();
				$(f).find('div.recur div.rstart').show();
				$(f).find('div.recur div.endson').show();					
				break; 
			case 'monthly':
				$(f).find('div.recur span.interval_caption').text('months');
				$(f).find('div.recur div.interval').show();
				$(f).find('div.recur div.repeatby').show();
				$(f).find('div.recur div.rstart').show();
				$(f).find('div.recur div.endson').show();					
				break; 
			case 'yearly':
				$(f).find('div.recur span.interval_caption').text('years');
				$(f).find('div.recur div.interval').show();
				$(f).find('div.recur div.rstart').show();
				$(f).find('div.recur div.endson').show();					
				break; 
			case '':
				$(f).find('div.recur span.interval_caption').text('');
				break; 
		}				
	}).change();
	$(f).find('div.recur div.endson input:radio').change(function(){
		switch ($(f).find('div.recur div.endson input:radio::checked').val()) {
			case 'never':
				$(f).find('div.recur div.endson .endson_count, div.recur div.endson .endson_until').val('').attr('disabled','disabled');
				break;
			case 'count':
				$(f).find('div.recur div.endson .endson_count').removeAttr('disabled');
				if (!$(f).find('div.recur div.endson .endson_count').val())
					$(f).find('div.recur div.endson .endson_count').val(5);	
				$(f).find('div.recur div.endson .endson_until').val('').attr('disabled','disabled');
				break;
			case 'until':
				var start = $.fullCalendar.parseDate($(f).find('div.recur div.rstart :input:first').val()),dayDate = new Date();
				dayDate.setTime(start.getTime()+1000*60*60*24*30);
				$(f).find('div.recur div.endson .endson_until').removeAttr('disabled');
				if (!$(f).find('div.recur div.endson .endson_until').val())
					$(f).find('div.recur div.endson .endson_until').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));	
				$(f).find('div.recur div.endson .endson_count').val('').attr('disabled','disabled');
				break;		
		}		
	}).change();
};

ig.Calendar.setDate = function(dayDate, allDay) {
	
	var f = $('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form');

	if (dayDate === undefined) {
		dayDate = ig.Calendar.dayDate;
		if (allDay === undefined) { 
			allDay = ig.Calendar.allDay;
		}	
	} else if (dayDate) { 
		ig.Calendar.dayDate = dayDate;
		ig.Calendar.allDay = allDay;
	}	
	
	if (!dayDate) return; 
	
	f.find('div.start :input:first').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));
	f.find('div.end :input:first').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));
	//f.find('input.datetime').datetime('value',dayDate);
	f.find('div.recur div.rstart :input:first').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));
	f.find('div.recur div.repeaton input:checkbox').val([ig.Utilities.date('l',dayDate.getTime()/1000).toLowerCase()]);
	
	if (!allDay) {
		var d = new Date(+dayDate);
		d.setHours(dayDate.getHours()+1);
		f.find('div.start :input:last').val($.fullCalendar.formatDate(dayDate, 'hh:mm TT'));
		f.find('div.end :input:last').val($.fullCalendar.formatDate(d, 'hh:mm TT'));		
	} else {
		//f.find(':checkbox.allDay').attr('checked','checked');
		var d = new Date;
		d.setHours(d.getHours()+1);
		f.find('div.start :input:last').val($.fullCalendar.formatDate(new Date, 'hh:mm TT'));
		f.find('div.end :input:last').val($.fullCalendar.formatDate(d, 'hh:mm TT'));		
	}
};

ig.Calendar.TimeHide = function(el) {
	$(el).find('div.start input.time').val('').attr('disabled','disabled');
	$(el).find('div.end input.time').val('').attr('disabled','disabled');
};
	
ig.Calendar.TimeShow = function(el) {
	$(el).find('div.start input.time').removeAttr('disabled');
	$(el).find('div.end input.time').removeAttr('disabled');
};

ig.Calendar.block = function(id){
	if (!id) id = '#calendar';
	$(id).block({message:null,overlayCSS: { backgroundColor: '#fff' , opacity: '0.7'},css: {border: '0'}});
};

ig.Calendar.unblock = function(id){
	if (!id) id = '#calendar';
	$(id).unblock();
};

ig.Calendar.timeData = function() {
	var data = [];
	for(var i=0;i<=23;i++) {
		if (i<10) {
			data.push('0'+i+':00');
			data.push('0'+i+':30');
		} else {
			data.push(i+':00');
			data.push(i+':30');
		}
	}
	return data; 	
};

ig.Calendar.Form.url = null;

ig.Calendar.editEntry = function(url,event) {

	ig.Calendar.Form.url = url;
	
	$('div.fc-event').qtip('hide');
	
	$('#entry-edit').remove();
	
	$('<div id="entry-edit"></div>').appendTo('body');
	
	$('#entry-edit').dialog({
		width: 600,
		autoOpen: false,
		modal: true,
		position: ['center',150],
		title: 'Edit Entry Calendar',
		open: function(event, ui) {
			//add handler submit
			var handle = function(f){
				f.submit(function(){
					$(this).ajaxSubmit({
						beforeSubmit:function(){$('#entry-edit').html(ig.Calendar.indicator);},
						success:function(html){
							if ($('#entry-edit').html(html).find('form').find('.error-message').size()) {
								handle($('#entry-edit').html(html).find('form'));
							} else {
								$('#entry-edit').dialog('close');			
								$('#calendar').fullCalendar('refetchEvents');
							}
						}
					});
					return false;	
				});						
			};
			$('#entry-edit').html(ig.Calendar.indicator).load(ig.Calendar.Form.url,function(){
				handle($(this).find('form'));
			});	
		},
		close: function(event,ui) {			
			$('#entry-edit').remove();
		}
	}).dialog('open');
	
	if (event) {
		$('#entry-edit').dialog('option', 'buttons', {
			'Confirm': function() {
				$('#EventStatus').val('active');
				$(this).find('form').submit();			
			},
			'Save' : function(){
				$(this).find('form').submit();
			},
			Cancel: function() {
				$(this).dialog('close'); 
			}
		});	
	} else {		
		$('#entry-edit').dialog('option', 'buttons', {		
			'Save' : function() {
				$(this).find('form').submit();
			},
			Cancel: function() {
				$(this).dialog('close');
			}			
		});
	}	
};

ig.Calendar.addEntry = function(index,cid){
	var eurl='',curl='',index=(index)?index:0;
	eurl = (cid)?'/events/add?'+jQuery.param({cid:cid}):'/events/add';
	curl = (cid)?'/conferences/add?'+jQuery.param({cid:cid}):'/conferences/add';	
	$('#entry-add').remove();
	$('<div id="entry-add" class="hide">'+
		'<div id="entry-tabs"><ul>'+
			'<li><a href="/notes/add" ><span>Note</span></a></li>'+
			'<li><a href="/tasks/add" ><span>Task</span></a></li>'+
			'<li><a href="'+eurl+'" ><span>Event</span></a></li>'+
			'<li><a href="/payments/add" ><span>Payment</span></a></li>'+
			'<li><a href="'+curl+'" ><span>Online Chat</span></a></li>'+
		'</ul></div>'+
	'</div>').appendTo('body');
	
	$('#entry-add').dialog({
		width: 630,
		autoOpen: false,
		modal: true,
		title: 'Create Note, Task, Payment, Event or Online chat',
		position: ['center',150],
		open: function(event,ui) {
		   $(this).parent().css('overflow','visible');
		   $('#entry-tabs').tabs({
			   	selected: index,
				show : function(event, ui) {
					if (ui.index == 2 ) {
						$('#entry-add').dialog('option','buttons',{
							'Send Invites No RSVP Needed': function(){
								$('#EventAddForm #EventRsvp').val(0);	
								$('#EventAddForm #EventInvited').val(1);
								$('#EventAddForm #EventStatus').val('active');
								$('#EventAddForm').submit();
							},
							'Send Invites With RSVP': function() {
								$('#EventAddForm #EventRsvp').val(1);
								$('#EventAddForm #EventInvited').val(1);
								$('#EventAddForm #EventStatus').val('pending');
								$('#EventAddForm').submit();
							},
							'Save' : function(){
								$('#EventAddForm #EventRsvp').val(0);	
								$('#EventAddForm #EventInvited').val(0);
								$('#EventAddForm #EventStatus').val('active');
								$('#EventAddForm').submit();
							},
							Cancel: function() {
								$(this).dialog('close'); 
							}
						});
					} else if (ui.index == 4) {
						$('#entry-add').dialog('option','buttons',{
							'Send Invites No RSVP Needed': function(){
								$('#ConferenceAddForm #ConferenceRsvp').val(0);	
								$('#ConferenceAddForm').submit();	
							},
							'Send Invites With RSVP': function() {
								$('#ConferenceAddForm #ConferenceRsvp').val(1);	
								$('#ConferenceAddForm').submit();	
							},
							Cancel: function() {
								$(this).dialog('close'); 
							}
						});
					} else {
						$('#entry-add').dialog('option','buttons',{
							'Save' : function(){
								$('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form').submit();
							},
							Cancel: function() { 
								$(this).dialog('close'); 
							}							
						});
					}
		   		},	
				load : function(event, ui) {
					//set Date 
					ig.Calendar.setDate();			
					//add handler submit
					var handle = function(f){
						f.submit(function(){
								$(this).ajaxSubmit({
								beforeSubmit: function(){
									var h = $('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').height(),indicator = $('<p></p>').append(ig.Calendar.indicator);
									indicator.height(h-10);
									$('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').html(ig.Calendar.indicator);
								},	
								success:function(html){
									if ($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').html(html).find('form').find('.error-message').size()) {
										handle($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form'));
									} else {
										$('#entry-add').dialog('close');			
										$('#calendar').fullCalendar('refetchEvents');
									}
								}
							});
							return false;	
						});						
					};
					handle($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form'));
				}
			});
		},
		close: function(event,ui) {			
			$('#entry-add').remove();
		}
	}).dialog('open');	
};

ig.Calendar.deleteEntry = function(url,id) {
	if (confirm('Are you sure you wish to remove this entry?')) {
		$('div.fc-event').qtip('hide');
		ig.Calendar.block();
		$.getJSON(url,function(json){
			if (json.status)
				$('#calendar').fullCalendar('removeEvents',id);
			ig.Calendar.unblock();
		});
	} else {
		return false;
	}	
};

//date = m/d/Y
ig.Calendar.dailyView = function(el) {
	$(el).fullCalendar({
		theme: true,
		firstDay: 1,
		editable: false,
		lazyFetching: false,
		header: {
			left: 'prev,next today',
			center: 'title',
			right: ''
		},			    
		weekMode: 'liquid',			    
		defaultEventMinutes: 30,
		defaultView: 'agendaDay',
		eventSources: ig.Calendar.eventSources,		
		eventRender: function(event, element) {
			var id = event.id.split('|')[1],model = event.id.split('|')[0],tooltip='',title=event.title + ' ';
				
			if (model == 'note') {
				if (!event.allDay)
					title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');

		        element.qtip({
		            content: { 
						text: $('<div class="tooltip-loading"><span></span></div>'), 
						url: '/notes/tooltip/'+id, 
						title: {text: title, button: 'x'} 
		        	},
		            style: {
	        		    title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
		        
			} else if (model == 'task') {
				if (!event.allDay)
					title += $.fullCalendar.formatDates( event.start, event.end, 'h(:mm)t - {h(:mm)t}');
				
		        element.qtip({
		            content: { 
    					text: $('<div class="tooltip-loading"><span></span></div>'), 
    					url: '/tasks/tooltip/'+id, 
    					title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'payment') {
				if (!event.allDay)
					title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');

		        element.qtip({
		            content: { 
        				text: $('<div class="tooltip-loading"><span></span></div>'), 
        				url: '/payments/tooltip/'+id, 
        				title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'event') {
				var name = (event.className[0] == 'event')?'blue':'light';
				if (!event.allDay)
					title += $.fullCalendar.formatDates( event.start, event.end, 'h(:mm)t - {h(:mm)t}');
		        element.qtip({
		            content: { 
	        			text: $('<div class="tooltip-loading"><span></span></div>'), 
	        			url: '/events/tooltip/'+id, 
	        			title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },		        		
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'conference') {
				title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');
		        element.qtip({
		            content: { 
		        		text: $('<div class="tooltip-loading"><span></span></div>'), 
		        		url: '/conferences/tooltip/'+id, 
		        		title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },		        		
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		       });
			} else { }	
	    },				
		loading: function(bool) {
			if (bool) ig.Calendar.block('#daily-view-calendar'); else ig.Calendar.unblock('#daily-view-calendar'); 			
		}
	});
};

ig.Calendar.fullCalendar = function(el,date,calid) {
	date = (date)?$.fullCalendar.parseDate(date):new Date;	
	var month = date.getMonth(),year = (date.getYear() < 2000)?date.getYear()+1900:date.getYear(),eventSources = ig.Calendar.eventSources;
	$(el).fullCalendar({
		
		theme: true,
		
		firstDay: 1,
		
		editable: true,
		
		lazyFetching: false,
		   
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		    
		weekMode: 'liquid',
		    
		defaultEventMinutes: 30,
		
		year: year,
		
		month: month,
		
		ignoreTimezone: true,
		 			
		eventDrop: function(calEvent, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
			var model = calEvent.id.split('|')[0];
			var id = calEvent.id.split('|')[1];
			
			ig.Calendar.block();

			//post state
			$.post('/calendar/drop/'+model+'/'+id,{
				'id': id,
				'dayDelta': dayDelta,
				'minuteDelta': minuteDelta,
				'allDay':(allDay)?1:0
			},function(){
				$(el).fullCalendar('refetchEvents');					
			});
		},
		
		eventResizeStart: function(calEvent, jsEvent, ui, view) {
			if (calEvent.className[0] == 'note' || calEvent.className[0] == 'conference' || calEvent.className[0] == 'payment') {
				return false;
			} else {
				return true;
			}			
		},
		
		eventResize: function(calEvent, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
			var model = calEvent.id.split('|')[0];
			var id = calEvent.id.split('|')[1];
			
			ig.Calendar.block();
			
			//post state
			$.post('/calendar/resize/'+model+'/'+id,{'id': id,'dayDelta': dayDelta,'minuteDelta': minuteDelta,'allDay': 0},function(){$(el).fullCalendar('refetchEvents');});
		},			
		
		dayClick: function(dayDate, allDay, jsEvent, view) {
			if (calid) {
				ig.SharedCalendar.addEntry(calid);
				ig.SharedCalendar.setDate(dayDate, allDay);
			} else {
				ig.Calendar.addEntry();
				ig.Calendar.setDate(dayDate, allDay);
			}
		},	
		
		eventRender: function(event, element) {
			var id = event.id.split('|')[1],model = event.id.split('|')[0],tooltip='',title=event.title + ' ';
				
			if (model == 'note') {
				if (!event.allDay)
					title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');

		        element.qtip({
		            content: { 
						text: $('<div class="tooltip-loading"><span></span></div>'), 
						url: '/notes/tooltip/'+id, 
						title: {text: title, button: 'x'} 
		        	},
		            style: {
	        		    title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	//position: { corner: {target: 'topLeft',tooltip: 'bottomLeft'}}
		            position: { viewport: $(".fc-border-separate") }
		        });
		        
			} else if (model == 'task') {
				if (!event.allDay)
					title += $.fullCalendar.formatDates( event.start, event.end, 'h(:mm)t - {h(:mm)t}');
				
		        element.qtip({
		            content: { 
    					text: $('<div class="tooltip-loading"><span></span></div>'), 
    					url: '/tasks/tooltip/'+id, 
    					title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'payment') {
				if (!event.allDay)
					title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');

		        element.qtip({
		            content: { 
        				text: $('<div class="tooltip-loading"><span></span></div>'), 
        				url: '/payments/tooltip/'+id, 
        				title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'event') {
				if (!event.allDay)
					title += $.fullCalendar.formatDates( event.start, event.end, 'h(:mm)t - {h(:mm)t}');
		        element.qtip({
		            content: { 
	        			text: $('<div class="tooltip-loading"><span></span></div>'), 
	        			url: '/events/tooltip/'+id, 
	        			title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },		        		
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		        });
			} else if (model == 'conference') {
				title += $.fullCalendar.formatDate( event.start, 'h(:mm)t');
		        element.qtip({
		            content: { 
		        		text: $('<div class="tooltip-loading"><span></span></div>'), 
		        		url: '/conferences/tooltip/'+id, 
		        		title: {text: title, button: 'x'} 
		        	},
		            style: {
		        		title: { background: '#f9f9f9' },		        		
		        		border: {
	               			color: event.color
		        		},		        		
		        		name: 'calendar',
		        		tip: true
		        	},
		            show: 'click',
		            hide: 'unfocus',	        	
		        	position: { corner: {target: 'topRight',tooltip: 'bottomLeft'}}
		       });
			} else { }	
	    },
		
	    eventSources: eventSources,
		
		loading: function(bool) {
			if (bool) ig.Calendar.block(); else ig.Calendar.unblock(); 			
		}
	});
};

//api blockUI message
ig.block = function(s){
	
     	$.blockUI({ 
    		message: 'processing request...',
    		centerX: false,
    		centerY: true,
    		css:{
     			background: '#E7ECDC url(/img/winbox_throbber.gif) no-repeat scroll 0px 0px',
// 				top:  ($(window).height() - 116) /2 + 'px', 
//              left: ($(window).width() - 116) /2 + 'px',
//				top: '10px', 
				left: '35%', 
                width: '116px',
                padding: '18px',
                paddingLeft: '60px',
                border: '2px solid #B4BBA5',
            	'-webkit-border-radius': '10px', 
            	'-moz-border-radius': '10px', 
            	opacity: '.7'                
     		},
     		overlayCSS: { backgroundColor: '#FFF' , opacity: '0.1'}
     	});	 
};

ig.TreeContact.block = function(){
	$('#reorganize').block({message:null,overlayCSS: { backgroundColor: '#C1C1C1' , opacity: '0.5'}});
};

ig.unblock = function(s){
	$.unblockUI();
};

ig.TreeContact.unblock = function(){
	$('#reorganize').unblock();
};

//redirect
ig.redirect = function(s) {
	location.href = s; 
};

//API team
ig.Team = {};
ig.Team.handle = function(f){
	f.submit(function(){
		$(this).ajaxSubmit({
			target: $('#dialog'),
			beforeSubmit:function(){$('#dialog').html(ig.Calendar.indicator);},		
			success: function(){
				if ($('#dialog').find('form').size()) {
					if ($('#step').val() == 'two') {
						$('#dialog').dialog('option','buttons',{
							'Done': function(){
								$('#dialog').find('form').submit();	
							},
							Cancel: function() {
								$(this).dialog('close'); 
							}
						});						
					} 	
					ig.Team.handle($('#dialog').find('form'));
				} else {
					$('#dialog').dialog('close');
					location.reload();
				}
			}
		});
		return false;	
	});						
};/*
ig.Team.setup = function() {
	$('#dialog').remove();
	$('<div id="dialog" class="hide"></div>').appendTo('body');	
	$('#dialog').dialog({
		width: 550,
		autoOpen: false,
		modal: true,
		title: 'Team Setup',
		position: ['center',150],
		open: function(event, ui) {
			$('#dialog').html(ig.Calendar.indicator).load('/teams/setup',function(){ig.Team.handle($(this).find('form'));});				
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Save': function() {
				$(this).find('form').submit();	
			},
			Cancel: function() {
				$(this).dialog('close'); 
			}
		}
	}).dialog('open');	
};
ig.Team.add = function(o) {
	if (!$(o).prev().val()) return;
	$.post('/teams/add',{'data[Team][name]':$(o).prev().val()},function(json){
		if (json.status) {
			$('#dialog').html(ig.Calendar.indicator).load('/teams/setup/'+json.id,function(){
				ig.Team.handle($(this).find('form'));
			});				
		}
	},'json');
};*/
ig.Team.create = function() {
	$('#dialog').remove();
	$('<div id="dialog" class="hide"></div>').appendTo('body');	
	$('#dialog').dialog({
		width: 550,
		autoOpen: false,
		modal: true,
		title: 'Create a Share Team',
		position: ['center',150],
		open: function(event, ui) {
			$('#dialog').html(ig.Calendar.indicator).load('/teams/create',function(){ig.Team.handle($(this).find('form'));});				
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Next (Set Priviledges)': function() {
				$(this).find('form').submit();	
			}
		}
	}).dialog('open');	
};
ig.Team.view = function(id) {
	$('#team-view').html(ig.Calendar.indicator).load('/teams/view/'+id);
}
ig.Team.edit = function(id) {
	$('#dialog').remove();
	$('<div id="dialog" class="hide"></div>').appendTo('body');	
	$('#dialog').dialog({
		width: 550,
		autoOpen: false,
		modal: true,
		title: 'Edit a Share Team',
		position: ['center',150],
		open: function(event, ui) {
			var handle = function(f){
				f.submit(function(){
					$(this).ajaxSubmit({
						target: $('#dialog'),
						beforeSubmit:function(){$('#dialog').html(ig.Calendar.indicator);},		
						success: function(){handle($('#dialog').find('form'));}
					});
					return false;	
				});						
			};
			$('#dialog').html(ig.Calendar.indicator).load('/teams/edit/'+id,function(){
				handle($(this).find('form'));
			});				
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Done': function() {
				$(this).find('form').submit();	
			},
			Cancel: function() {
				$(this).dialog('close'); 
			}			
		}
	}).dialog('open');	
}

//API share calendar
ig.SharedCalendar = {};
ig.SharedCalendar.handle = function(f){
	f.submit(function(){
		$(this).ajaxSubmit({
			beforeSubmit:function(){$('#dialog').html(ig.Calendar.indicator);},		
			success: function(html){ig.SharedCalendar.handle($('#dialog').html(html).find('form'));}
		});
		return false;	
	});						
};
ig.SharedCalendar.setup = function(tid) {
	$('#dialog').remove();
	$('<div id="dialog" class="hide"></div>').appendTo('body');	
	$('#dialog').dialog({
		width: 550,
		autoOpen: false,
		modal: true,
		title: 'Setup Shared Calendar',
		position: ['center',150],
		open: function(event, ui) {
			$('#dialog').html(ig.Calendar.indicator).load('/shared_calendars/setup/'+tid,function(){ig.SharedCalendar.handle($(this).find('form'));});				
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Save': function() {
				$(this).find('form').submit();	
			},
			Cancel: function() {
				$(this).dialog('close'); 
			}
		}
	}).dialog('open');		
};

ig.SharedCalendar.adminOptions = function(cid) {
	$('#dialog').remove();
	$('<div id="dialog" class="hide"></div>').appendTo('body');	
	$('#dialog').dialog({
		width: 550,
		autoOpen: false,
		modal: true,
		title: 'Setup Shared Calendar',
		position: ['center',150],
		open: function(event, ui) {
			$('#dialog').html(ig.Calendar.indicator).load('/shared_calendars/adminOptions/'+cid,function(){
				var handle = function(f){
					f.submit(function(){
						$(this).ajaxSubmit({
							beforeSubmit:function(){$('#dialog').html(ig.Calendar.indicator);},		
							success: function(html){handle($('#dialog').html(html).find('form'));}
						});
						return false;	
					});						
				};	
				handle($(this).find('form'));
			});				
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Save': function() {
				$(this).find('form').submit();	
			},
			Cancel: function() {
				$(this).dialog('close'); 
			}
		}
	}).dialog('open');		
};

ig.SharedCalendar.addEntry = function(calid,index){
	var index=(index)?index:0;
	$('#dialog').remove();
	$('<div id="dialog" class="hide">'+
		'<div id="entry-tabs"><ul>'+
			'<li><a href="/notes/add/'+calid+'" ><span>Note</span></a></li>'+
			'<li><a href="/tasks/add/'+calid+'" ><span>Task</span></a></li>'+
			'<li><a href="/events/add/'+calid+'" ><span>Event</span></a></li>'+
			'<li><a href="/payments/add/'+calid+'" ><span>Payment</span></a></li>'+
			'<li><a href="/conferences/add/'+calid+'" ><span>Online Chat</span></a></li>'+
		'</ul></div>'+
	'</div>').appendTo('body');
	
	$('#dialog').dialog({
		width: 600,
		autoOpen: false,
		modal: true,
		title: 'Create Note, Task, Payment, Event or Online chat',
		position: ['center',150],
		open: function(event,ui) {
		   $(this).parent().css('overflow','visible');
		   $('#entry-tabs').tabs({
			   	selected: index,
				load : function(event, ui) {
					//set Date 
					ig.SharedCalendar.setDate();			
					//add handler submit
					var handle = function(f){
						f.submit(function(){
								$(this).ajaxSubmit({
								beforeSubmit: function(){
									var h = $('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').height(),indicator = $('<p></p>').append(ig.Calendar.indicator);
									indicator.height(h-10);
									$('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').html(ig.Calendar.indicator);
								},	
								success:function(html){
									if ($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').html(html).find('form').find('.error-message').size()) {
										handle($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form'));
									} else {
										$('#dialog').dialog('close');			
										$('#calendar').fullCalendar('refetchEvents');
									}
								}
							});
							return false;	
						});						
					};
					handle($('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form'));
				}
			});
		},
		close: function(event,ui) {			
			$('#dialog').remove();
		},
		buttons: {
			'Save' : function(){
				$('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form').submit();
			},
			Cancel: function() { 
				$(this).dialog('close'); 
			}							
		}
	}).dialog('open');	
};

ig.SharedCalendar.setDate = function(dayDate, allDay) {
	
	var f = $('#entry-tabs div.ui-tabs-panel').not('.ui-tabs-hide').find('form');

	if (dayDate === undefined) {
		dayDate = ig.Calendar.dayDate;
		if (allDay === undefined) { 
			allDay = ig.Calendar.allDay;
		}	
	} else if (dayDate) { 
		ig.Calendar.dayDate = dayDate;
		ig.Calendar.allDay = allDay;
	}	
	
	if (!dayDate) return; 
	
	f.find('div.start :input:first').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));
	f.find('div.end :input:first').val($.fullCalendar.formatDate(dayDate, 'dd MMM yyyy'));
	
	if (!allDay) {
		var d = new Date(+dayDate);
		d.setHours(dayDate.getHours()+1);
		f.find('div.start :input:last').val($.fullCalendar.formatDate(dayDate, 'hh:mm TT'));
		f.find('div.end :input:last').val($.fullCalendar.formatDate(d, 'hh:mm TT'));		
	} else {
		//f.find(':checkbox.allDay').attr('checked','checked');
		var d = new Date;
		d.setHours(d.getHours()+1);
		f.find('div.start :input:last').val($.fullCalendar.formatDate(new Date, 'hh:mm TT'));
		f.find('div.end :input:last').val($.fullCalendar.formatDate(d, 'hh:mm TT'));		
	}
};

//API Conference
ig.Conference = {};
	ig.Conference.Add = function(){
		$('#conference-add').remove();
		$('<div id="conference-add" class="hide"></div>').appendTo('body');	
		$('#conference-add').dialog({
			width: 600,
			autoOpen: false,
			modal: true,
			title: 'Add Conference',
			position: ['center',150],
			open: function(event, ui) {
				var handle = function(f){
					f.submit(function(){
						$(this).ajaxSubmit({
							beforeSubmit:function(){$('#conference-add').html(ig.Calendar.indicator);},		
							success: function(html){
								if ($('#conference-add').html(html).find('form .error-message').size()) {
									handle($('#conference-add').find('form'));
								} else {
									$(this).dialog('close');
									location.reload();									
								}								
							}
						});
						return false;	
					});						
				}; 	
				$('#conference-add').html(ig.Calendar.indicator).load('/conferences/add',function(){
					handle($(this).find('form'));
				});				
			},
			close: function(event,ui) {			
				$('#conference-add').remove();
			},
			buttons: {
				'Send Invites No RSVP Needed': function(){
					$(this).find('form #ConferenceRsvp').val(0);	
					$(this).find('form').submit();	
				},
				'Send Invites With RSVP': function() {
					$(this).find('form #ConferenceRsvp').val(1);	
					$(this).find('form').submit();	
				},
				Cancel: function() {
					$(this).dialog('close'); 
				}
			}
		}).dialog('open');			
	};
	ig.Conference.Edit = function(id){
		$('div.fc-event').qtip('hide');
		$('#conference-edit').remove();
		$('<div id="conference-edit" class="hide"></div>').appendTo('body');	
		$('#conference-edit').dialog({
			width: 600,
			autoOpen: false,
			modal: true,
			title: 'Edit Online Chat',
			position: ['center',150],
			open: function(event, ui) {
				var handle = function(f){
					f.submit(function(){
						$(this).ajaxSubmit({
							beforeSubmit:function(){$('#conference-edit').html(ig.Calendar.indicator);},		
							success: function(html){
								if ($('#conference-edit').html(html).find('form .error-message').size()) {
									handle($('#conference-edit').find('form'));
								} else {
									$('#conference-edit').dialog('close');
									$('#calendar').fullCalendar('refetchEvents');
								}								
							}
						});
						return false;	
					});						
				}; 	
				$('#conference-edit').html(ig.Calendar.indicator).load('/conferences/edit/'+id,function(){
					handle($(this).find('form'));
				});				
			},
			close: function(event,ui) {			
				$('#conference-edit').remove();
			},
			buttons: {
				'Save & Notify': function() {
					$('#conference-edit').find('form').submit();	
				},
				Cancel: function() {
					$('#conference-edit').dialog('close'); 
				}
			}
		}).dialog('open');			
	};

	//API Conference
	ig.Event = {};
		ig.Event.Edit = function(id){
			$('div.fc-event').qtip('hide');
			$('#event-edit').remove();
			$('<div id="event-edit" class="hide"></div>').appendTo('body');	
			$('#event-edit').dialog({
				width: 550,
				autoOpen: false,
				modal: true,
				title: 'Edit Event',
				position: ['center',150],
				open: function(event, ui) {
					var handle = function(f){
						f.submit(function(){
							$(this).ajaxSubmit({
								beforeSubmit:function(){$('#event-edit').html(ig.Calendar.indicator);},		
								success: function(html){
									if ($('#event-edit').html(html).find('form .error-message').size()) {
										handle($('#event-edit').find('form'));
									} else {
										$('#event-edit').dialog('close');
										$('#calendar').fullCalendar('refetchEvents');
									}								
								}
							});
							return false;	
						});						
					}; 	
					$('#event-edit').html(ig.Calendar.indicator).load('/events/edit/'+id,function(){
						handle($(this).find('form'));
					});				
				},
				close: function(event,ui) {			
					$('#event-edit').remove();
				},
				buttons: {
					'Send Invites No RSVP Needed': function(){
						$('#event-edit #EventRsvp').val(0);	
						$('#event-edit #EventInvited').val(1);
						$('#event-edit #EventStatus').val('active');
						$('#event-edit').find('form').submit();
					},
					'Send Invites With RSVP': function() {
						$('#event-edit #EventRsvp').val(1);
						$('#event-edit #EventInvited').val(1);
						$('#event-edit m#EventStatus').val('pending');
						$('#event-edit').find('form').submit();
					},
					'Save' : function(){
						$('#event-edit #EventRsvp').val(0);	
						$('#event-edit #EventInvited').val(0);
						$('#event-edit #EventStatus').val('active');
						$('#event-edit').find('form').submit();
					},
					Cancel: function() {
						$('#event-edit').dialog('close'); 
					}
				}
			}).dialog('open');			
		};	
		
//API purchase history
	ig.Balance = {};	
	ig.Balance.History = function(){
		$('#dialog').remove();
		$('<div id="dialog" class="hide"></div>').appendTo('body');	
		$('#dialog').dialog({
				width: 300,
				autoOpen: false,
				modal: true,
				title: 'Your Balance History',
				position: ['center',150],
				open: function(event, ui) {
					$('#dialog').html(ig.Calendar.indicator).load('/users/balanceHistory');				
				},
				close: function(event,ui) {			
					$('#dialog').remove();
				},
				buttons: {
					'Close': function() {
						$('#dialog').dialog('close'); 
					}
				}
			}).dialog('open');			
		};	
		ig.Balance.Invoice = function(id){
			$('#dialog').html(ig.Calendar.indicator).load('/users/invoice/'+id);
		};		
		ig.Balance.ShowHistory = function() {
			$('#dialog').html(ig.Calendar.indicator).load('/users/balanceHistory');
		};
		
//API profile
ig.Profile = {};

	ig.Profile.block = function(){
		$('#tabs').block({message:null,overlayCSS: { backgroundColor: '#C1C1C1' , opacity: '0.5'}});
	};
	
	ig.Profile.unblock = function(){
		$('#tabs').unblock();
	};

	//privacy handler form
	ig.Profile.handlerPrivacyForm = function(form) {
		var opts = {
			dataType: 'json',
			beforeSubmit: function(){ig.Profile.block();},
			success: function (json) {
				if (json.status) {
					$(form).find('span.value').html($(form).find(':text').val());
					ig.Profile.unblock();
				}
			}
		};
		$(form).ajaxSubmit(opts);
		return false;
	};
	
	//state change
	ig.Profile.state = false;
	
	//done button event
	ig.Profile.saveForm = function (f, opts) {
		if ($(f).is('form')) {
			$(f).ajaxSubmit(opts);
		} else {
			ig.redirect('/my-profile');
		}		
	};
	
	ig.Profile.done  = function(o, message) {
		if (ig.Profile.state) {
			//set message
			$('#dialog_save_info .message').html(message);
			//ui dialog init
			$('#dialog_save_info').dialog({
				bgiframe: true,
				autoOpen: false,
				modal: false,
				overlay: {
					backgroundColor: '#FFF',
					opacity: 0.9
				},
				buttons: {
					Cancel: function() {
						$(this).dialog('close');
					},
					'Don\'t Save': function(){
						$(this).dialog('close');
						ig.redirect('/my-profile');
					},
					'Save' : function(){
						$(this).dialog('close');
						var i = 0;
						var $forms = $('.wrap-content form.allow-change');
						
						var options = {
							target: $forms.eq(i).parent(), 
							success: function (data) {
								options = $.extend(options,{target: $forms.eq(++i).parent()});
								ig.Profile.saveForm($forms.eq(i), options);
							}
						};
						ig.Profile.saveForm($forms.eq(0), options);
					}
				}			
			});
			//open dialog
			$('#dialog_save_info').dialog('open');			
		} else {
			ig.redirect('/my-profile');
		}
	};

	//delete trigger
	ig.Profile.remove = function(o,u){
		if ($(o).parents('form:first').find('div.row').size() > 1) {
			if (u) {
				$.get(u,function(){
					$(o).parents('div.row').remove();
				});				
			} else {
				$(o).parents('div.row').remove();
			}	
			ig.Profile.state = true;
		}
	};

	//educations
	ig.Profile.Education = {};
	
	ig.Profile.Education.add = function(s){
		var html = ig.Profile.htmlEducation.split('%s%').join(ig.Profile.Education.max);
		$('#EducationEditForm .row:last').after(html);
		$('#EducationEditForm .autocompleter').each(function(){ 
			ig.Autocompleter.education(this);
		});		
		ig.Profile.Education.max++;
		ig.Profile.state = true;
	};	
	
	//companies
	ig.Profile.Company = {};
	
	ig.Profile.Company.add = function(s){
		var html = ig.Profile.htmlCompany.split('%s%').join(ig.Profile.Company.max); 
		$('#CompanyEditForm .row:last').after(html);
		$('#CompanyEditForm .row:last .autocompleter').each(function(){ 
			ig.Autocompleter.company(this);
		});		
		ig.Profile.Company.max++;
		ig.Profile.state = true;
	};
	
//API Widgets
	ig.Widget = {};
	
	//Summary
	ig.Widget.Summary = {};
	ig.Widget.Summary.Done = function(o,id){
		$.get('/tasks/done/'+id,function(){
			$(o).attr('checked','checked');
			$(o).attr('disabled','disabled');
			$(o).parents('tr:first').remove();
		});
		$.post('/widget/ajax_tasks',function(data){			
			$('#summary-tasks').empty().html(data);
		});
		/*$.get('/tasks/done/'+id,function(){
			$(o).attr('checked','checked');
			$(o).attr('disabled','disabled');
			$(o).parents('tr:first').removeClass('overdue').addClass('completed');
		});*/
	};
	
	//Comming Up widget
	ig.Widget.CommingUp = {};
	ig.Widget.CommingUp.Update = function(o,l) {
		var cntr = $(o).parents('.clr:first'); 
		cntr.html('<p class="dayviewer-loading"></p>');
		cntr.load('/widget/CommingUp/'+l);
	};
	
	//Easy Entry
	ig.Widget.EasyEntry = {};
	ig.Widget.EasyEntry.Change = function(o) {
		var val = $(o).val();
		$('#infoboxpane-EASY_ENTRY form.easy-entry div.duration').hide();
		$('#infoboxpane-EASY_ENTRY form.easy-entry div.where').hide();
		$('#infoboxpane-EASY_ENTRY form.easy-entry div.amount').hide();
		if (val == 'Task') {
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.duration').show();
		} else if (val == 'Event') {
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.duration').show();
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.where').show();
		} else if (val == 'Payment') {
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.amount').show();			
		}
	};
	ig.Widget.EasyEntry.allDay = function(o) {
		if ($(o).is(':checked')) {
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.duration select').attr('disabled','disabled');
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.time :text').attr('disabled','disabled');
		} else {
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.duration select').removeAttr('disabled');
			$('#infoboxpane-EASY_ENTRY form.easy-entry div.time :text').removeAttr('disabled');
		}
	};
	ig.Widget.EasyEntry.handleForm = function(f) {
		var div = $(f).parent();
		f.submit(function(){
			$(this).ajaxSubmit({
				beforeSubmit:function(){div.html(ig.Calendar.indicator);},		
				success: function(html){div.html(html);ig.Widget.EasyEntry.handleForm(div.find('form'));}
			});
			return false;	
		});			
	}
	
	//Credits
	ig.Widget.Credits = {};
	ig.Widget.Credits.Buy = function(qty) {
		if (qty) {
			var l = parseInt(($(window).width() - 800)/2),t = parseInt(($(window).height() - 600)/2);
			window.open('/users/credits?qty='+qty,"credits","width=800,height=600,left="+l+",top="+t+",scrollbars=1,location=1,toolbar=0");	
		}
	}
	ig.Widget.Credits.BuyForm = function() {
		var l = parseInt(($(window).width() - 800)/2),t = parseInt(($(window).height() - 600)/2);
		window.open('/users/credits',"credits","width=800,height=600,left="+l+",top="+t+",scrollbars=1,location=1,toolbar=0");	
	}	
	
//API Autocompleter
ig.Autocompleter = {};

	ig.Autocompleter.time = function(id) {
		$(id).autocomplete(ig.Calendar.timeData(), {
			minChars: 0,
			max: ig.Calendar.timeData().length,
			autoFill: false,
			mustMatch: true,
			matchContains: true,
			scrollHeight: 220,
			highlight: false,
			cacheLength: false	
		});	
	};
	
	ig.Autocompleter.skillsData = ["C#/.Net","CodeWarrior/C++","VB/Delphi","J2EE","JFC","PalmOS","Perl","PHP","PocketPC","Visual Basic","MS-SQL","ActiveX","VB/Delphi/ASP/IIS","SatelliteForms","XML","Assembler","VB/.NET","LaTeX","Delphi","Delphi/VB","Database Modeling","Application Design","QA","Games/Windows","PHP/IIS/MS SQL","PostgreSQL","ASP","UML","LAMP administration","WML/WMLScript","Python","J2ME","Lotus Domino","ColdFusion","Zope/Python","CSS","Symbian SDK","Crystal Reports","Tech Writer","Remoting","Kylix","Graphics","Testing","PowerBuilder","Oracle Forms","Oracle Reports","Oracle DBA","Oracle PL/SQL","SQL","Systems Programming","Sybase","Struts","Sharepoint","Cobol","Hibernate","Tomcat","IntelliJ IDEA","Web Sphere","Resin","WebLogic","JBoss","Smarty","Video Streaming","VoiceXML","XML-RPC","phpNuke","postNuke","OsCommerce","Project Management","FoxPro","Borland C++ Builder","VBA","Windows Administration","Unix Shell","VoIP","3D Design","Informix","Driver development","QNX","Macromedia Director","Access","XUL","Oracle Application Server","GTK programming","SOAP","Online Payments","Wireless","SQLite","Lotus Notes","Filemaker Pro","UI Design","JSP","Asterisk","Search","Ruby","Lingo","MySQL","Mac OS X","Qt","EDI","MS Navision","InterBase","Mambo","Data Entry","DotNetNuke","Blackberry/RIM","Recruiting","Photoshop","OCX","SyncML","AJAX","Hyperion","Mason","EO","WordPress","Adobe Flex","JavaScript","Joomla","Java","Drupal","FreeBSD","SAP","Rails","Linux","Writer","Excel","Flash","XHTML","Alfresco","Plone","Facebook","SEM",".NET","Blogger","Salesforce","C++","Adobe AIR","Django","vBulletin","iPhone","Zimbra","Netsuite","Android","Agile","Zend","Twitter","Magento","Amazon","hi5","Google App Engine","PBwiki","TypePad","Zillow","Tokbox","Network Solutions","Online Assistant"];
	
	ig.Autocompleter.skills = function(id) {
		$(id).autocomplete(ig.Autocompleter.skillsData, {
			 max: 3,
			 multiple: true,
			 multipleSeparator: ", "
		});	
	};

	ig.Autocompleter.company = function(o) {
		$(o).autocomplete('/ajax/autocomplete/company', {
			parse: function(resp) {
				eval('var data = ' + resp);
				if(data.status) {
					return $.map(data.data, function(row) {
						return {
							data: row,
							value: row.company_name,
							result: row.company_name
						}
					});
				}
				return false;
			},
			width: 260,
			minChars: 1,
			selectFirst: false,
			formatItem: function(row) {
				return row.company_name;
			}
		});	
	};
	
	ig.Autocompleter.education = function(o) {
		$(o).autocomplete('/ajax/autocomplete/education', {
			parse: function(resp) {
				eval('var data = ' + resp);
				if(data.status) {
					return $.map(data.data, function(row) {
						return {
							data: row,
							value: row.name,
							result: row.name
						}
					});
				}
				return false;
			},
			width: 260,
			minChars: 1,
			selectFirst: false,
			formatItem: function(row) {
				return row.name;
			}
		});	
	};
	
	ig.AddPoll = function() {

		$('#dialog').remove();
		
		$('<div id="dialog"></div>').appendTo('body');
		
		$('#dialog').dialog({
			width: 450,
			autoOpen: false,
			modal: true,
			position: ['center',150],
			title: 'Feedback Us',
			open: function(event, ui) {
				//add handler submit
				var handle = function(f){
					f.submit(function(){
						$(this).ajaxSubmit({
							beforeSubmit:function(){$('#dialog').html(ig.Calendar.indicator);},
							success:function(html){
								$('#dialog').html(html);
								$('#dialog').dialog('option', 'buttons', {
									'Logout': function() {
										$(this).dialog('close');
										ig.redirect('/users/logout');
									},
									'Continue' : function(){
										$(this).dialog('close');
										location.reload();
									}
								});	
							}
						});
						return false;	
					});						
				};
				$('#dialog').html(ig.Calendar.indicator).load('/polls/add',function(){
					handle($(this).find('form'));
				});	
			},
			buttons : {
				'Save': function () {
					$(this).find('form').submit();
				}
			},
			close: function(event,ui) {			
				$('#dialog').remove();
			}
		}).dialog('open');
	};
	
//Utilities
ig.Utilities = {
		
		date: function ( format, timestamp ) {	// Format a local time/date

			var a, jsdate = new Date(timestamp ? timestamp * 1000 : null);
			var pad = function(n, c){
				if( (n = n + "").length < c ) {
					return new Array(++c - n.length).join("0") + n;
				} else {
					return n;
				}
			};
			var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
			var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
			var txt_months =  ["", "January", "February", "March", "April","May", "June", "July", "August", "September", "October", "November","December"];
			var f = {
				// Day
					d: function(){
						return pad(f.j(), 2);
					},
					D: function(){
						t = f.l(); return t.substr(0,3);
					},
					j: function(){
						return jsdate.getDate();
					},
					l: function(){
						return txt_weekdays[f.w()];
					},
					N: function(){
						return f.w() + 1;
					},
					S: function(){
						return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
					},
					w: function(){
						return jsdate.getDay();
					},
					z: function(){
						return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
					},

				// Week
					W: function(){
						var a = f.z(), b = 364 + f.L() - a;
						var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;

						if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
							return 1;
						} else{

							if(a <= 2 && nd >= 4 && a >= (6 - nd)){
								nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
								return date("W", Math.round(nd2.getTime()/1000));
							} else{
								return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
							}
						}
					},

				// Month
					F: function(){
						return txt_months[f.n()];
					},
					m: function(){
						return pad(f.n(), 2);
					},
					M: function(){
						t = f.F(); return t.substr(0,3);
					},
					n: function(){
						return jsdate.getMonth() + 1;
					},
					t: function(){
						var n;
						if( (n = jsdate.getMonth() + 1) == 2 ){
							return 28 + f.L();
						} else{
							if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
								return 31;
							} else{
								return 30;
							}
						}
					},

				// Year
					L: function(){
						var y = f.Y();
						return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
					},
					//o not supported yet
					Y: function(){
						return jsdate.getFullYear();
					},
					y: function(){
						return (jsdate.getFullYear() + "").slice(2);
					},

				// Time
					a: function(){
						return jsdate.getHours() > 11 ? "pm" : "am";
					},
					A: function(){
						return f.a().toUpperCase();
					},
					B: function(){
						// peter paul koch:
						var off = (jsdate.getTimezoneOffset() + 60)*60;
						var theSeconds = (jsdate.getHours() * 3600) +
										 (jsdate.getMinutes() * 60) +
										  jsdate.getSeconds() + off;
						var beat = Math.floor(theSeconds/86.4);
						if (beat > 1000) beat -= 1000;
						if (beat < 0) beat += 1000;
						if ((String(beat)).length == 1) beat = "00"+beat;
						if ((String(beat)).length == 2) beat = "0"+beat;
						return beat;
					},
					g: function(){
						return jsdate.getHours() % 12 || 12;
					},
					G: function(){
						return jsdate.getHours();
					},
					h: function(){
						return pad(f.g(), 2);
					},
					H: function(){
						return pad(jsdate.getHours(), 2);
					},
					i: function(){
						return pad(jsdate.getMinutes(), 2);
					},
					s: function(){
						return pad(jsdate.getSeconds(), 2);
					},
					//u not supported yet

				// Timezone
					//e not supported yet
					//I not supported yet
					O: function(){
					   var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
					   if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
					   return t;
					},
					P: function(){
						var O = f.O();
						return (O.substr(0, 3) + ":" + O.substr(3, 2));
					},
					//T not supported yet
					//Z not supported yet

				// Full Date/Time
					c: function(){
						return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
					},
					//r not supported yet
					U: function(){
						return Math.round(jsdate.getTime()/1000);
					}
			};

			return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
				if( t!=s ){
					// escaped
					ret = s;
				} else if( f[s] ){
					// a date function exists
					ret = f[s]();
				} else{
					// nothing special
					ret = s;
				}

				return ret;
			});
		}
};	
	
$(function(){

		//Manage all, none, unread, read links.
		$("#button_all").live(
			'click',
			function () {
				$('.selection').find(':checkbox:enabled').each(
					function () {
						$(this).attr('checked','checked');
					}
				);
				return false;
			}
		);
		
		$("#button_none").live(
			'click',
			function () {
				$('.selection').find(':checkbox:enabled').each(
					function () {
						$(this).removeAttr('checked');
					}
				);
				return false;
			}
		);
		
		$("#button_read").click(
			function () {
				$('.selection').find(':checkbox:enabled').each(
					function () {
						$(this).removeAttr('checked');
					}
				);
				$('.selection').find(':checkbox[title=read]').each(
					function () {
						$(this).attr('checked', 'checked');
					}
				);
				return false;
			}
		);
		
		$("#button_unread").click(
			function () {
				$('.selection').find(':checkbox:enabled').each(
					function () {
						$(this).removeAttr('checked');
					}
				);
				$('.selection').find(':checkbox[title=unread]').each(
					function () {
						$(this).attr('checked', 'checked');
					}
				);
				return false;
			}
		);
});	
