var FILE_COUNTER = 1;
var LAST_SNIP = 'left';
var SCROLL_BOTTOM = 0;

var tl;
var bandInfos;
var eventSource;

$(document).ready(function(){


		// make sure the logo is just above the bottom of the browser
		SCROLL_BOTTOM = $(window).height() - 325;

		// make sure logo doesn't scroll below the footer
		
		pos = $('#footer').position();
		if (pos.top-325 < SCROLL_BOTTOM) { 
			SCROLL_BOTTOM = pos.top-325;
		}

		setupZoom();

		$('.repairField').blur(function() { 
			
			o = $(this);
			if (o.val()=='') { 
				//console.log('resetting default');
				o.css('color','#CCC');
				o.val(o.attr('default'));
			}
		});

		$('.repairField').focus(function() { 
			
			o = $(this);
			
			//console.log("focus "+o.attr('id'));
			 if (o.val()==o.attr('default')) {
				//console.log('ready for input');
				o.css('color','#000');
				o.val('');
			}
			

		});

		$('.repairField').blur();


		if (!isTouch() && typeof jQuery.fn.tinymce == 'function') { 

		$('textarea.tinymce').tinymce({
			script_url : podRoot+'/themes/hdl/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
			theme: "advanced",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",	
			valid_elements: "p,blockquote,h1,h2,h3,h4,h5,h6,ol,ul,li,br,em,strong,i,u,b,strike,a[href|target|title],img[src|width|height|alt|border|title],object[width|height],param[name|value],embed[src|type|allowfullscreen|allowscriptaccess|width|height]",
			plugins:"paste",
			width:"100%",
			paste_auto_cleanup_on_paste: true,
			paste_strip_class_attributes: "all",
			paste_remove_spans: true,
			paste_remove_styles: true,
			relative_urls:false,
			remove_script_host: false,

			theme_advanced_buttons1: "formatselect,pastetext,removeformat,separator,bold,italic,separator,bullist,numlist,separator,link,unlink,image,separator,undo,removeformat,separator,charmap",
			theme_advanced_buttons2: "",
			theme_advanced_blockformats : "p,blockquote,h1,h2,h3,h4,h5,h6",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			content_css : podRoot+"/themes/hdl/tinymce.css"
		});
		
		$('textarea.tinyquestion').tinymce({
			script_url : podRoot+'/themes/hdl/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
			theme: "advanced",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",	
			valid_elements: "p,blockquote,h1,h2,h3,h4,h5,h6,ol,ul,li,br,em,strong,i,u,b,strike,a[href|target|title],img[src|width|height|alt|border|title]",
			plugins:"paste",
			width:"100%",
			paste_auto_cleanup_on_paste: true,
			paste_strip_class_attributes: "all",
			paste_remove_spans: true,
			paste_remove_styles: true,
			relative_urls:false,
			remove_script_host: false,

			theme_advanced_path : false,
			theme_advanced_buttons1: "bold,link,unlink",
			theme_advanced_buttons2: "",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			content_css : podRoot+"/themes/hdl/tinymce.css"
		});
		
		
		$('textarea.tinycomments').tinymce({
			script_url : podRoot+'/themes/hdl/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
			theme: "advanced",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",	
			theme_advanced_buttons1: "bold,italic,separator,link,unlink",
			theme_advanced_buttons2: "",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_path : false,
			relative_urls:false,
			remove_script_host: false,
			content_css : podRoot+"/themes/hdl/tinymce.css"
		});		
		
		} 
		
		if (isTouch()) {
			$('#touchWarning').show();
		}
		
		
		if ($('#case_study_title').html()) { 
			going = true;
			min = 24;
			max = 40;
			tries = 1;
			size = $('#case_study_title').css("fontSize");
			height = $('#case_study_title').height();
			size = size.split("px")[0];
			
			html = $('#case_study_title').html();
			
			breaks = 0;
			offset = 0;
			do {
				offset=html.indexOf("<br>",offset);
				if (offset >= 0) { 
					breaks++;			
					offset = offset+4;
				} 
			} while (offset>=0);
			
			lines = breaks+1;
			if (lines == 1) {
				extra = 30;
			} else {
				extra = 10;
			}
 			//console.log("Current size: " + size);
			bufferheight = height+(parseInt(size)*lines)+extra;
			//console.log("Max height: " +bufferheight);
		//	going=false;
			while (going) {
				tries++;
				if (height < bufferheight && size < max) {
					//console.log(height + " < " + bufferheight + " - Enlarging!");
					size++;
					$('#case_study_title').css("fontSize",size+"px");
					//console.log("Font size: " + size);

				}

				height = $('#case_study_title').height();

				
				// have we gone onto a second line?
				// or maybe busted out of the alloted room?
				if (height > bufferheight && size > min) { 
					//console.log(height + " > " + size + " and " + size + " > " + min + " so I am shrinking");
					size--;
					$('#case_study_title').css("fontSize",size+"px");
					going = false;
				} 
				if (height > bufferheight && size==min) {
					//console.log("Stoping");
					going = false;
				}
				if (tries > 100) {
					//console.log("Timed out");
					going = false;
				}
			
			}
			
		}




		var logo = $('#floating_logo'); 
		if (logo.html()) { 
			logo.css('position','absolute');
			logo.css('top',SCROLL_BOTTOM+"px");
		}


		$(window).scroll(function() { 
			logo = $('#floating_logo'); 
			if (logo.html()) { 
				top_of_screen = $(window).scrollTop();
				pos = logo.position();

				if (top_of_screen >= SCROLL_BOTTOM) { 
					logo.css('position','fixed');
					logo.css('top','1px');
				} else {
					logo.css('position','absolute');
					logo.css('top',SCROLL_BOTTOM+'px');
				}
			}
		});


		$('a.glossary').bt( 
			{
			  hoverIntentOpts: {
			    timeout: 1000
		  		},
				spikeLength:0,
				spikeGirth:0,
				fill: 'white',
				cornerRadius:0,
				strokeStyle: '#0000A1',
				strokeWidth:1,
				shadow: true,
				shadowOffsetX: 3,
				shadowOffsetY: 3,
				shadowBlur: 8,
				shadowColor: 'rgba(0,0,0,.9)',
			    padding:10,
				cssStyles: {fontSize: '1.2em',color: '#333'}
			}
		);
		$('a.footnote').bt( 
			{
			
			  hoverIntentOpts: {
			    timeout: 1000
		  		},
				spikeLength:0,
				spikeGirth:0,
				fill: 'white',
				cornerRadius:0,
				strokeStyle: '#0000A1',
				strokeWidth:1,
				shadow: true,
				shadowOffsetX: 3,
				shadowOffsetY: 3,
				shadowBlur: 8,
				shadowColor: 'rgba(0,0,0,.9)',
			    padding:10,
				cssStyles: {fontSize: '1.2em',color: '#333'}
			}
		);
		
		$('fieldset p.input input.text').bt( 
			{
				trigger: ['focus', 'blur'],
				positions: ['right'],
				spikeLength:0,
				spikeGirth:0,
				overlap:-20,
				fill: 'white',
				strokeWidth:0,
			    padding:10,
				cssStyles: {fontSize: '12px',color: '#333'}
			}
		);

		$('fieldset p.fifty input.text').bt( 
			{
				trigger: ['focus', 'blur'],
				positions: ['right'],
				spikeLength:0,
				spikeGirth:0,
				overlap:-280,
				fill: 'white',
				strokeWidth:0,
			    padding:10,
				cssStyles: {fontSize: '12px',color: '#333'}
			}
		);

		$('fieldset p.last input.text').bt( 
			{
				trigger: ['focus', 'blur'],
				positions: ['right'],
				spikeLength:0,
				spikeGirth:0,
				overlap:-20,
				fill: 'white',
				strokeWidth:0,
			    padding:10,
				cssStyles: {fontSize: '12px',color: '#333'}
			}
		);
		$('fieldset p.input textarea').bt( {
			 trigger: ['focus', 'blur'],
			positions: ['right'],
				spikeLength:0,
				spikeGirth:0,
				overlap:-20,
				fill: 'white',
				strokeWidth:0,
			    padding:10,
				cssStyles: {fontSize: '12px',color: '#333'}

			}
		);

		
		if (typeof jQuery.fn.validate == 'function') { 
			$('form.valid').validate({
			   ignoreTitle: true		   
			});
		}
});


function swapLoginPw() { 
	$('#ajax_login_fake_password').hide();
	$('#ajax_login_password').show();
	$('#ajax_login_password').focus();
	return false;
}
function swapJoinPw() { 
	$('#ajax_join_fake_password').hide();
	$('#ajax_join_password').show();
	$('#ajax_join_password').focus();
	return false;
}

function blog_submit() { 

	tinyMCE.triggerSave();
	$('#blog_form .repairField').each(function(){ if ($(this).val()==$(this).attr('default')){$(this).val('');}});
}

function autosaveCase() { 

	tinyMCE.triggerSave();
	
	var fields = new Array('headline','tagline','design_team','client','sector','stakeholders_integral','stakeholders_implied','stakeholders_interested','project_cost','start_date','project_status');
	
	// get list of questions
	$('textarea.question').each(function() {
			fields.push($(this).attr('id'));
		});
	
	data = '';
	for (i in fields) { 
		field = $('#'+fields[i]);
	
		name=field.attr('name');
		val = field.val();
		var d = field.attr('default');
		if (val!=d) { 
			data = data + '&' + name + '=' + encodeURIComponent(val);
		}
	}
	
	data = data+'&id=' + $('#contentId').val();

	data = 'method=autosave'+data;
	$.post(API,data,function(json,textStatus) { 
		if (json.error) { 
			alert(json.error);
		} else {
			$('#save_status').html(json.message);
		}
	},"json");
	
	
}

function showFirstBubble() { 


		events = eventSource.getAllEventIterator();
		event =  events._events.getFirst();
		bandInfos[0].eventPainter.showBubble(event);

}

function goto(id) {

	if (id=='timeline') { 
		$.scrollTo('#'+id,{easing:'swing',duration:150,offset:-75}); 
		showFirstBubble();		
	} else {	
		$('.case_sidebar').css('background','transparent');
		$('#'+id).css('background','#FFFFFF');
		$.scrollTo('#'+id,{easing:'swing',duration:150}); 
	}
	if (id != 'body') { 
		 $('#body').effect("highlight",{color:"#eeedf8"},1000);
	}
	return false;
}


function setActiveNav(id) { 

	$(id).addClass('active');
}


function autosaveBlog() {

	tinyMCE.triggerSave();
	if ($('#headline').val()!=$('#headline').attr('default')) { 
	data = $('#blog_form').serialize();
	data = 'method=autosave&'+data;
	$.post(API,data,function(json,textStatus) { 
		if (json.error) { 
			alert(json.error);
		} else {
			$('#save_status').html(json.message);
			$('#id').val(json.id);	
		}
	},"json");
	}	
}


function valid_onsubmit(form) { 
	tinyMCE.triggerSave();
	return true;
}


function htmlspecialchars (string, quote_style, charset, double_encode) {
    // Convert special characters to HTML entities  
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
 
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }
 
    return string;
}

function snip(id,type) { 

	var name = $('#thumbnail_'+id).attr('title');	
	LAST_SNIP = type;
	var str = '[img name="'+ name + '" type="' + type + '"]';
	$('#snip_'+id).html(str);
	return false;

}


	function toggleBot(html_id,on,off,api_parameters,handler) { 

		var command = API + '?' + api_parameters + '&html_id='+encodeURIComponent(html_id)+'&on='+encodeURIComponent(on)+'&off='+off;

		if(!handler) { handler = toggleBotSuccess; }

		$.getJSON(command,handler);

		return false;
	}
	
	function toggleBotSuccess(json) {
	
		if (json.error) {
			alert(json.error);
		}
		if (json.isOn) {
			$('#'+json.html_id).addClass('active');
			$('#'+json.html_id).html(json.on);
		} else {
			$('#'+json.html_id).removeClass('active');
			$('#'+json.html_id).html(json.off);				
		}
	
	}
	

function removeComment(id) { 

	if (confirm('Remove this comment?')) { 

		command = API+"?method=removeComment&comment="+id;
		$('#comment'+id).hide();
		$.getJSON(command,removeCommentSuccess);
	}
	
	return false;
}


function removeCommentSuccess(json) {

	if (json.error) {
		alert(json.error);
	}
}



function approveComment(id) { 

		command = API+"?method=approveComment&comment="+id;
		$.getJSON(command,approveCommentSuccess);
	
	return false;
}

function approveCommentSuccess(json) {

	if (json.error) { 
		alert(json.error);
	} else {
		$('#approve_'+json.id).html('&#x2714;');
	}

}

function galleryNext(id) { 
	var next = false;
	$('.gallery_photo').each(function() { 
		
		if (next) { 
			next = false;
			if (id != $(this).attr('fileid')) { 
				gallery($(this).attr('fileid'));
			}
			return false;
		}
		if ($(this).attr('fileid')==id) { 
			next = true;
		}
	
	});
	
	if (next) { 
		var all = $('.gallery_photo');
		var first = $(all[0]).attr('fileid');
		if (first != id) {
			gallery(first);
		}
	}

	return false;


}

function gallery(id) { 
	$('a.gallery_nav').removeClass('gallery_active');
	$('a#gallery_nav_'+id).addClass('gallery_active');
	$('.gallery_photo').fadeOut();
	$('#photo_'+id).fadeIn();
	var caption = $('#photo_'+id + ' img').attr('alt');
	$('#gallery_caption').html(caption);
	return false;
}

	function resortQuestions() { 
	
		var order = '';
		$('#question_admin .question_short').each(function(i,elm) { order +=  $(elm).attr('docId') + ","; })
		command = API + "?method=resortChildren&order=" + order + "&type=question&template=question.short";
		$.getJSON(command);
		
	}




function moveNumberUp(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=up&type=bignumber&template=format.bignumbers";
	$.getJSON(command,refreshBigNumbers);
	return false;
}
function moveNumberDown(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=down&type=bignumber&template=format.bignumbers";
	$.getJSON(command,refreshBigNumbers);
	return false;
}
function movePersonUp(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=up&type=caseperson&template=format.attached_people";
	$.getJSON(command,refreshPeople);
	return false;
}
function movePersonDown(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=down&type=caseperson&template=format.attached_people";
	$.getJSON(command,refreshPeople);
	return false;
}
function moveFileUp(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=up&type=file&template=format.attached_file";
	$.getJSON(command,refreshFiles);
	return false;
}
function moveFileDown(contentId,childId) { 

	command = API + "?method=resortChildren&contentId="+contentId+"&childId="+childId+"&direction=down&type=file&template=format.attached_file";
	$.getJSON(command,refreshFiles);
	return false;
}

function moveQuestionUp(contentId) { 

	command = API + "?method=resortContent&contentId="+contentId+"&direction=up&type=question&template=question.short";
	$.getJSON(command,refreshQuestions);
	return false;
}
function moveQuestionDown(contentId) { 

	command = API + "?method=resortContent&contentId="+contentId+"&direction=down&type=question&template=question.short";
	$.getJSON(command,refreshQuestions);
	return false;
}

function refreshQuestions(json) {

	if (json.error) {	
		alert(json.error);
	} else {		
		$('#question_admin .stack_rows').html(json.html);
	}


}

function addFile() { 
	p = document.createElement('p');
	p.setAttribute('class','input fileinput');
	
	
	img = document.createElement('img');
	img.setAttribute('src','/peoplepods/themes/hdl/img/arrow_up_alt1_32x32.png');
	
	label = document.createElement('label');
	label.innerHTML = 'Upload File:';
	
	file = document.createElement('input');
	file.setAttribute('type','file');
	file.setAttribute('name','file'+FILE_COUNTER);
	file.setAttribute('class','file');
	file.setAttribute('id','file'+FILE_COUNTER);
	
	p.appendChild(img);
	p.appendChild(label);
	p.appendChild(file);
	document.getElementById('file_list').appendChild(p);
	FILE_COUNTER++;
	return false;
}

function removeBlogFile(contentId,fileId) { 


	command = API + "?method=removeFile&mode=blog&contentId="+contentId+"&fileId="+fileId;
	$.getJSON(command,refreshFiles);
			
	return false;

}





function showAjaxLogin() {
	$('#ajax_join').hide();
	$('#ajax_login').show();
	return false;
}
function showAjaxJoin() {
	$('#ajax_join').show();
	$('#ajax_login').hide();
	return false;
}
function ajaxJoin() { 
	$('#ajax_login_join_error').hide();
	var name = $('#ajax_join_name').val();
	var email = $('#ajax_join_email').val();
	var pw = $('#ajax_join_password').val();
	command = API + "?method=join&name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email)+"&password="+encodeURIComponent(pw);
	$.getJSON(command,ajaxAuthReturn);
	return false;	return false;
}
function ajaxLogin() { 

	$('#ajax_login_join_error').hide();
	var email = $('#ajax_login_email').val();
	var pw = $('#ajax_login_password').val();
	command = API + "?method=login&email="+encodeURIComponent(email)+"&password="+encodeURIComponent(pw);
	$.getJSON(command,ajaxAuthReturn);
	return false;
}
function ajaxAuthReturn(json) { 


	if (json.error) { 
		$('#ajax_login_join_error').html(json.error);
		$('#ajax_login_join_error').show();
		if ($('#next_action').val()) { 
			$('#next_action').hide();
		}
	} else {
	
		$('#login_description').html( "Thanks for logging in, <strong>" + json.nick+"</strong>!  Now we can continue with the submission process.");
		$('#ajax_login_join').slideUp();
		if ($('#next_action').val()) { 
			$('#next_action').show();
		}

	}

	return false;
}


function checkForEnter (event) {
    if (event.keyCode == 13) {
        event.preventDefault();
        return false;
    }
} 


function repairField(obj,val) {
	obj = $(obj);
	
	if (obj.val()==val) { 
		if (obj.attr('name')=='password') { 
//			obj.attr('type','password');
		}
		obj.val('');
		obj.css("color","#000000");
	}  else if (obj.val()=='') {
		if (obj.attr('name')=='password') { 
//			obj.attr('type','text');
		}
		obj.val(val);
		obj.css("color","#CCCCCC");
	}

}


function validatePerson(name,organization,role) { 
	return ($('#case_form').validate({ignoreTitle: true}).element(name) && $('#case_form').validate({ignoreTitle: true}).element(organization) && $('#case_form').validate({ignoreTitle: true}).element(role));
}

function addPerson(contentId,name,organization,role,personId) { 


	personId_val = $(personId).val();

	$("#edit_person_" +personId_val + " .repairField").each(function() {
		if($(this).val() == $(this).attr('default')) {
			$(this).val("");
		}
	});

	// validate values
	valid = validatePerson(name,organization,role);

	contentId = $(contentId).val();
	name_val = $(name).val();
	org_val = $(organization).val();
	role_val = $(role).val();

	
	if (valid) { 
	
		command = API + "?method=addPerson&contentId="+contentId+"&name="+encodeURIComponent(name_val)+"&organization="+encodeURIComponent(org_val)+"&role="+encodeURIComponent(role_val)+"&personId="+encodeURIComponent(personId_val);
		$.getJSON(command,refreshPeople);
		
		if (personId_val=='') { 
			$(name).val('');
		//	$(organization).val('');
			$(role).val('');
			$(personId).val('');
		}			
	}
	
	$("#edit_person_" +personId_val + " .repairField").each(function() {
		$(this).blur();
	});
	
	return false;
}
function removePerson(contentIdObj,personId) { 
	if (confirm('Remove this person?')) { 
	contentId = $(contentIdObj).val();
	command = API + "?method=removePerson&contentId="+contentId+"&personId="+personId;
	$.getJSON(command,refreshPeople);
	}			
	return false;
}


function removeFile(contentIdObj,fileId) { 
	if (confirm('Remove this file?')) { 
	contentId = $(contentIdObj).val();
	command = API + "?method=removeFile&contentId="+contentId+"&fileId="+fileId;
	$.getJSON(command,refreshFiles);
	}			
	return false;

}


function refreshFiles(json) {

	if (json.error) {	
		alert(json.error);
	} else {
		$('#file_list').html(json.html);
	}



}

function updateFile(id) { 

	caption = $('#caption_'+id).val();	
	$.getJSON(API+"?method=updateFile&fileId="+id+"&description="+encodeURIComponent(caption),refreshFiles);

}


function editFile(id) { 

	$('.file_caption').show();
	$('.file_caption_edit').hide();

	$('#file_caption_'+id).hide();
	$('#file_caption_edit_'+id).show();
	return false;
}


function editPerson(id) { 

	$('#people_list .submit_attached_people').show();
	$('#people_list .attached_people_form').hide();

	$('#person_'+id).hide();
	$('#edit_person_'+id).show();

	$('#edit_person_'+id + ' .repairField').blur(function() { 
		
		o = $(this);
		if (o.val()=='') { 
		//	//console.log('resetting default');
			o.css('color','#CCC');
			o.val(o.attr('default'));
		}
	});

	$('#edit_person_'+id + ' .repairField').focus(function() { 
		
		o = $(this);
		
		//console.log("focus "+o.attr('id'));
		 if (o.val()==o.attr('default')) {
			//console.log('ready for input');
			o.css('color','#000');
			o.val('');
		}
		

	});

	$('#edit_person_'+id+ ' .repairField').blur();

}

function refreshPeople(json) {

	$('#edit_person_ input').blur();

	if (json.error) {	
		alert(json.error);
	} else {
		$('#people_list').html(json.html);
	}



}

function validateEvent(date,description) { 
	return ($('#case_form').validate({ignoreTitle: true}).element(date) && $('#case_form').validate({ignoreTitle: true}).element(description) && $(date).val()!='' );
}


function addEvent(contentId,phase,date,description,eventId) { 

	// validate values
	valid = validateEvent(date,description);
			
	contentId = $(contentId).val();
	phase_val = $(phase).val();
	date_val = $(date).val();
	description_val = $(description).val();
	eventId_val = $(eventId).val();
		
	if (valid) { 

		command = API + "?method=addEvent&contentId="+contentId+"&phase="+encodeURIComponent(phase_val)+"&description="+encodeURIComponent(description_val)+"&date="+encodeURIComponent(date_val)+"&eventId="+encodeURIComponent(eventId_val);
		$.getJSON(command,refreshEvents);
		
		if (eventId_val=='') {
			$(phase).val('');
			$(description).val('');
			$(date).val('');
			$(eventId).val('');
		}		
	}
	
	
	return false;
}

function removeEvent(contentIdObj,eventId) { 
	if (confirm('Remove this event?')) { 
	contentId = $(contentIdObj).val();
	command = API + "?method=removeEvent&contentId="+contentId+"&eventId="+eventId;
	$.getJSON(command,refreshEvents);
	}			
	return false;
}

function editEvent(id) { 

	$('#event_list .submit_timeline').show();
	$('#event_list .timeline_event_form').hide();

	$('#event_'+id).hide();
	$('#edit_event_'+id).show();

}
function editNumber(id) { 

	$('#number_list .submit_bignumber').show();
	$('#number_list .number_form').hide();
	
	$('#number_'+id).hide();
	$('#edit_number_'+id).show();

			$('#edit_number_'+id + ' .repairField').blur(function() { 
				
				o = $(this);
				if (o.val()=='') { 
					//console.log('resetting default');
					o.css('color','#CCC');
					o.val(o.attr('default'));
				}
			});

			$('#edit_number_'+id + ' .repairField').focus(function() { 
				
				o = $(this);
				
				//console.log("focus "+o.attr('id'));
				 if (o.val()==o.attr('default')) {
					//console.log('ready for input');
					o.css('color','#000');
					o.val('');
				}
				

			});

	$('#edit_number_'+id+ ' .repairField').blur();

}

function refreshEvents(json) {

	if (json.error) {	
		alert(json.error);
	} else {			
		$('#event_list').html(json.html);
		$('input.datepickr').datepick({navigationAsDateFormat: true, prevText: '< M', currentText: 'M y', nextText: 'M >',changeMonth: false, changeYear: false,mandatory:true,buttonImage: 'img/calendar.png',buttonImageOnly: true});
		$('input.eudatepickr').datepick({dateFormat:'dd/mm/yy',navigationAsDateFormat: true, prevText: '< M', currentText: 'M y', nextText: 'M >',changeMonth: false, changeYear: false,mandatory:true,buttonImage: 'img/calendar.png',buttonImageOnly: true});

	}


}


function validateBigNumber(number,description,source,source_url) {
	return ($('#case_form').validate({ignoreTitle: true}).element(number) && $('#case_form').validate({ignoreTitle: true}).element(description) && $('#case_form').validate({ignoreTitle: true}).element(source) && $('#case_form').validate({ignoreTitle: true}).element(source_url));
}

function addBigNumber(contentId,number,description,source,source_url,numberId) { 

	numberId_val = $(numberId).val();

	$("#edit_number_" +numberId_val + " .repairField").each(function() {
		if($(this).val() == $(this).attr('default')) {
			$(this).val("");
		}
	});
	

	// validate values
	valid = validateBigNumber(number,description,source,source_url);
		
	contentId = $(contentId).val();
	number_val = $(number).val();
	description_val = $(description).val();
	source_val = $(source).val();
	source_url_val = $(source_url).val();
	
	if (valid) { 

		command = API + "?method=addBigNumber&contentId="+contentId+"&number="+encodeURIComponent(number_val)+"&description="+encodeURIComponent(description_val)+"&source="+encodeURIComponent(source_val)+"&source_url="+encodeURIComponent(source_url_val)+"&numberId="+encodeURIComponent(numberId_val);
		$.getJSON(command,refreshBigNumbers);
		
		if (numberId_val=='') { 
			$(number).val('');
			$(description).val('');
			$(source).val('');
			$(numberId).val('');
			$(source_url).val('');

		};
	}
	
	$("#edit_number_" +numberId_val + " .repairField").each(function() {
		$(this).blur();
	});	
	
	return false;
}


function removeBigNumber(contentIdObj,numberId) { 
	if (confirm('Remove this number?')) { 
	contentId = $(contentIdObj).val();
	command = API + "?method=removeBigNumber&contentId="+contentId+"&numberId="+numberId;
	$.getJSON(command,refreshBigNumbers);
	}			
	return false;
}

function refreshBigNumbers(json) {

	if (json.error) {	
		alert(json.error);
	} else {		
		$('#number_list').html(json.html);
		$('#edit_number_ input').blur();
	}


}



function dossierPost(type,dossier) { 

	$('#editor').load('/dossiers/' + dossier + '/post?editor='+type,function(){
		$('#editor').show();
			
		$('#dossier_post_tabs li').removeClass('active');
		$('#dossier_post_tabs li').addClass('inactive');
		$('#dossier_post_tabs li#dossier_'+type).removeClass('inactive');
		$('#dossier_post_tabs li#dossier_'+type).addClass('active');

		$('form.valid').validate({
		   ignoreTitle: true		   
		});


		if (!isTouch()) {
			$('textarea.tinymce').tinymce({
				script_url : podRoot+'/themes/hdl/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
				theme: "advanced",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",	
				valid_elements: "p,blockquote,h1,h2,h3,h4,h5,h6,ol,ul,li,br,em,strong,i,u,b,strike,a[href|target|title],img[src|width|height|alt|border|title],object[width|height],param[name|value],embed[src|type|allowfullscreen|allowscriptaccess|width|height]",
				plugins:"paste",
				width:"100%",
				paste_auto_cleanup_on_paste: true,
				paste_strip_class_attributes: "all",
				paste_remove_spans: true,
				paste_remove_styles: true,
				relative_urls:false,
				remove_script_host: false,
	
				theme_advanced_buttons1: "formatselect,pastetext,removeformat,separator,bold,italic,separator,bullist,numlist,separator,link,unlink,image,separator,undo,removeformat,separator,charmap",
				theme_advanced_buttons2: "",
				theme_advanced_blockformats : "p,blockquote,h1,h2,h3,h4,h5,h6",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				content_css : podRoot+"/themes/hdl/tinymce.css"
			});
		} else {
			$('#touchWarning').show();
		}
		
		
		
		
	});


	return false;

}



function isTouch() {

		return (((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||  (navigator.userAgent.match(/iPad/i))));

}