


$(document).ready(function(){


    


	//homepage slider


	if( $('#slider').length > 0 ){


		$('#slider').mbSlider({


			 autoplay: true,


			 pauseOnHover: true,


			 playPauseButtonSeperate: true,


			 playDirection: 'right',


			 pagination: false,


			 continuous: true,


			 mousewheelsupport: false,


			 showControls : {


				 play: false,


				 pause: false,


				 first: false,


				 last: false


			 }


		});


	}


	


	


	//testimonial slider


	if( $('#testimonial').length > 0 ){


		$('#testimonial').mbSlider({


			 autoplay: true,


			 pauseOnHover: true,


			 playPauseButtonSeperate: true,


			 playDirection: 'right',


			 continuous: true,


			 mousewheelsupport: false,


			 showControls: false,


			 pagination: false,


			 orientation: 'vertical'       


		});


	}


	//newsletter signup


	$("#newsletter").submit(function(){


		$("#newsletter-response").html("<span class='response-waiting'>Please Wait...</span>").hide().fadeIn(200);


		$.ajax({


			url: 'ajax.php',


			type: 'Post',


			data: 'action=signup&' + $("form#newsletter").serialize(),


			success:function(data){


				var responseData = jQuery.parseJSON(data);


				var klass;


				if(responseData.status == 'error'){


					klass = 'error';	


				}


				else {


					klass = 'success';	


				}


				$("#newsletter-response .response-waiting").fadeOut(200,function(){


					$("#newsletter-response").html("<span class='"+klass+"'>"+responseData.message+"</span>").hide().fadeIn(200,function(){


						setTimeout(function(){ 


							$("#newsletter-response span").fadeOut(200,function(){ 


								$("#newsletter-response").html('');


							}) 


						},3000); 


					});


				})


			}


		})


		return false;


	})


	


	


	


	//Quotation Form


	//date add function


	Date.prototype.addDays = function(days) {


		this.setDate(this.getDate()+days);


	} 


	


	//pregnant traveller fields


	$("input[name='pregnant']").change(function(){


		if($(this).val() == 'yes'){


			$(".pregnant-fields").slideDown(400);


		}


		else {


			$(".pregnant-fields").slideUp(400);


			$('#pregnant_complications_yes').attr('checked','');


			$('#pregnant_complications_no').attr('checked','checked');


			unquoteableMsg('hide');


		}


	})


	


	//number of travellers ages


	$("#numoftravellers").change(function(){


		var num = parseInt($(this).val()),


			html = '';


		


		$(".dynamic-traveller-input").remove();


		


		if(num > 1){


			for(var i=2; i<=num; i++){


				html += '<li class="dynamic-traveller-input">' +


					    '<label for="traveller_'+i+'">Traveller '+i+' Age:</label>' +


					    '<input type="text" name="traveller_'+i+'" id="traveller_'+i+'" class="small" />' +


					    '</li>';


			}


		}


		$("#maintravellersage").closest('li').after(html);


	})


	


	//destination tooltips


	$("#destination").change(function(){


		var desination = $(this).val(),


			tooltip = $(this).parent().find('.tooltip-text');


			


		switch( $(this).val() ){


			case 'uk':


				tooltip.text('Mainland UK, Northern Ireland, and Island of the coast of the mainland Exluding the Channel Islands.');


			break;


			case 'eu':


				tooltip.text('Countries within the EU, the Channel Islands and countries bordering the Mediterranean Sea.');


			break;


			case 'worldwide1':


				tooltip.text('World Wide Excluding USA, Canada and the Caribbean.');


			break;


			case 'worldwide2':


				tooltip.text('World Wide Inc USA, Canada and the Caribbean.');


			break;


			case 'australia':


				tooltip.text('Australia and New Zealand.');


			break;


		}


	})


	


	//cover for set default numoftravellers


	$("#coverfor").change(function(){


		var travellers = $("#numoftravellers"),


			tooltip = $(this).parent().find('.tooltip-text');


			


		switch( $(this).val() ){


			case 'individual':


				travellers.html("<option value='1'>1</option>");


				tooltip.text('One child or adult');


			break;


			case 'couple':


				travellers.html("<option value='2'>2</option>");


				tooltip.text('Two adults together, regardless of relationship status.');


			break;


			case 'family':


				travellers.html("<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6' selected='selected'>6</option>");


				tooltip.text('2 adults and up to 4 children under 18 at the time of departure living at the same address. Children under the age of 2 are free with an insured adult.');


			break;


			case 'singleparent':


				travellers.html("<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5' selected='selected'>5</option>");


				tooltip.text('1 adult and up to 4 children under 18 at the time of departure living at the same address. Children under the age of 2 are free with an insured adult.');


			break;	


		}


		$("#numoftravellers").trigger('change');


	})


	


	//datepickers


	if( $("#startdate").length > 0){


		$("#startdate").datepicker({


			dateFormat : 'dd/mm/yy',


			onClose: function(dateText, inst){


				if(dateText !== ''){


					var mindate = dateText.split('/');


						mindate = new Date(mindate[2]+'/'+mindate[1]+'/'+mindate[0]);


					$("#enddate").datepicker('enable');	


					$("#enddate").datepicker('option','minDate',mindate);


					$("#enddate").datepicker('option','maxDate',new Date(mindate.getTime() + ($("#numofdays").val())*24*60*60*1000));


					$("#enddate").val('');


				}


				//getEndDate(dateText);


			},


			constrainInput : true,


			minDate: new Date()


		});


	}


	


	if( $("#enddate").length > 0){


		$("#enddate").datepicker({


			dateFormat : 'dd/mm/yy',


			onClose: function(dateText, inst){


				//getEndDate(dateText);


			},


			constrainInput : true,


			minDate: new Date()


		});


		$("#enddate").datepicker('disable');


	}


	


	if( $("#maintravellersdob").length > 0){


		$("#maintravellersdob").datepicker({


			dateFormat : 'dd/mm/yy',


			onClose: function(dateText, inst){


				getAgeFromDate(dateText);


			},


			constrainInput : true,


			changeMonth: true,


			changeYear: true,


			yearRange: '1900:c'


		});


	}


	


	$("#numofdays").change(function(){


		//getEndDate( $("#startdate").val() )


		var mindate = $("#startdate").val().split('/'),


			mindate = new Date(mindate[2]+'/'+mindate[1]+'/'+mindate[0]);


		$("#enddate").datepicker('option','maxDate',new Date(mindate.getTime() + ($(this).val())*24*60*60*1000));


		$("#enddate").val('');


	})


	


	function getAgeFromDate(dateText){


		if(dateText !== ''){


			var d = dateText.split('/'),


				today = new Date(),


				by = Number(d[2]),


				bm = Number(d[1])-1,


				bd = Number(d[0]),


				bday = new Date(by,bm,bd),


				age = 0,


				dif = bday;


				


			while(dif < today){


				var dif = new Date(by+age,bm,bd);


				age++;


			}


			age +=-2 ;


			$("#maintravellersage").val(age);


		}


	}


	


	


	/*


	function getEndDate(dateText){


		if(dateText !== ''){


			var dateSplit = dateText.split('/'),


				d = new Date(dateSplit[2],(dateSplit[1]-1),dateSplit[0]),


				numofdays = parseInt($('#numofdays').val()),


				dateStr = '';


				


			d.addDays(numofdays);


			dateStr += (( d.getDate() < 9 ) ? '0' + d.getDate() : d.getDate()) + '/';	


			dateStr += (( d.getMonth() < 9 ) ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1)) + '/';	


			dateStr +=  d.getFullYear();


			


			$("#enddate").val(dateStr);


			$("#enddate_disabled").val(dateStr);


		}


	}


	*/


	


	//unquoteable message


	$("input[name='cancer'], input[name='surgery'], input[name='terminal_condition'], input[name='other_conditions'], input[name='trip_cancelled'], input[name='risks'], input[name='medical_conditions'], input[name='pregnancy_complications'], input[name='pregnancy_type'], select[name='pregnantweeks']").change(function(){


		


		var name = $(this).filter(':checked').attr('name'),


		    val = $(this).filter(':checked').val(),


			inputs = ['cancer','surgery','terminal_condition','other_conditions','trip_cancelled','risks','medical_conditions','pregnancy_complications'];


		


		for(x in inputs){


			var checkvalue = $("input[name='"+inputs[x]+"']:checked").val();


			if(inputs[x] == name) checkvalue = val


			


			if(checkvalue == 'yes'){


				unquoteableMsg('show');


				return false;


			}


		}


		


		if(!checkPregnancyType()){


			unquoteableMsg('show');


			return false;	


		}


		


		unquoteableMsg('hide');


	});


	


	function checkPregnancyType(){


		var ptype = $("input[name='pregnancy_type']").filter(':checked').val(),


			pweeks = $("select[name='pregnantweeks']").val();


			


			


		if(ptype == 'multiple' && pweeks !== 'under32'){


			return false;


		}


		


		if(pweeks == 'over36'){


			return false;


		}


		


		return true;


	}


	


	function unquoteableMsg(action){


		var marginVal = (action == 'show') ? 0 : '-125';


		$("#unquoteable-msg").animate({


			marginTop: marginVal


		},{


			duration:200 


		})


		


		if(action == 'show'){


			$("#submit").hide();	


		}


		else {


			$("#submit").show();	


		}


	}


	


	


	//validation


	$('#quote').submit(function(e){


		var numoftravellers = $("#numoftravellers").val(),


			mainTravellersAge = parseInt($("#maintravellersage").val()),


			cover = $("#coverfor").val(),


			errors = '',


			formerror = false,


			blankage = false,


			invalidMainAge = false,


			incorrectNumPeople = false,


			incorrectOldestTraveller = false,


			tooOld = false,


			medicalQuestions = [


				$("input[name='medical_conditions']").is(':checked'),


				$("input[name='risks']").is(':checked'),


				$("input[name='cancer']").is(':checked'),


				$("input[name='surgery']").is(':checked'),


				$("input[name='terminal_condition']").is(':checked'),


				$("input[name='other_conditions']").is(':checked'),


				$("input[name='trip_cancelled']").is(':checked')


			],


			medicalQuestionsAnswered = false


		


		


		//check there is a start date


		if( $("#startdate").val() == '' ){


			errors += '<li class="error"> - You have not specified a start date for your trip</li>';


			formerror = true;	


		}


		


		//check there is a end date


		/*


		if( $("#enddate").val() == '' ){


			errors += '<li class="error"> - You have not specified an end date for your trip</li>';


			formerror = true;	


		}


		*/


		


		//check all age fields are filled in


		if( $("#maintravellersage").val() == '' ){


			errors += '<li class="error"> - You have not specified a date of birth for the main traveller</li>';


			blankage = true;


			formerror = true;	


		}


		


		if(cover !== 'individual' && numoftravellers > 1){


			for(var i=2; i<=numoftravellers; i++){


				if($("#traveller_"+i).val() == ''){


					errors += '<li class="error"> - You have not specified an age for traveller '+i+'</li>';


					blankage = true;


					formerror = true;


				}


			}


		}


		


		for(x in medicalQuestions){


			if(medicalQuestions[x] == false){


				errors += '<li class="error"> - You have not answered all of the medical questions</li>';


				formerror = true;


				break;


			}


		}


		


		//check correct ages


		if(!blankage){


			var adults = 0,


				children = 0


				


			$("#maintravellersage, input[name*='traveller_']").each(function(){


				var age = parseInt($(this).val())


				if(age > 17){


					adults++;	


				}


				else if(age < 0){


					errors += '<li class="error"> - You have entered an incorrect date of birth for the main traveller.</li>';


					invalidMainAge = true;


					formerror = true;


				}


				else {


					children++;


				}


			})


			


			switch(cover){


				case 'single':	


					if(adults < 1){


						errors += '<li class="error"> - This policy covers one adult. The ages of your travellers do not reflect this.</li>';


						incorrectNumPeople = true;


						formerror = true;	


					}


				break;


				case 'couple':	


					if(adults < 2){


						errors += '<li class="error"> - This policy covers two adults. The ages of your travellers do not reflect this.</li>';


						incorrectNumPeople = true;


						formerror = true;


					}


				break;


				case 'family':


					if(adults !== 2 || children > 4){


						errors += '<li class="error"> - This policy covers two adults and upto 4 children. The ages of your travellers do not reflect this.</li>';


						incorrectNumPeople = true;


						formerror = true;	


					}


				break;


				case 'singleparent':


					if(adults !== 1 || children > 4){


						errors += '<li class="error"> - This policy covers one adults and upto 4 children. The ages of your travellers do not reflect this.</li>';


						incorrectNumPeople = true;


						formerror = true;


					}


				break;


			}


		}


		


		//check nobody over 80


		if(!incorrectNumPeople && !invalidMainAge){


			for(var i=2; i<=numoftravellers; i++){


				if(parseInt($("#traveller_"+i).val()) > 80){


					errors += '<li class="error"> - Traveller '+i+' is over the age of 80 and cannot be insured on this policy.</li>';


					tooOld = true;


					formerror = true;


				}


			}


			


			if(mainTravellersAge > 80){


				errors += '<li class="error"> - The main traveller is over the age of 80 and cannot be insured on this policy.</li>';


				tooOld = true;


				formerror = true;


			}


		}


		


		


		/*


		if(!tooOld){


			switch(cover){


				case 'couple':


					if(mainTravellersAge < $("#traveller_2").val()){


						errors += '<li class="error"> - The second traveller is older than the main traveller. The quote is based on the age of the oldest traveller.</li>';


						incorrectOldestTraveller = true;


						formerror = true;	


					}


				break;


				case 'family':


					if(numoftravellers > 2){


						if(mainTravellersAge < $("#traveller_2").val()){


							errors += '<li class="error"> - The second traveller is older than the main traveller. The quote is based on the age of the oldest traveller.</li>';


							incorrectOldestTraveller = true;


							formerror = true;	


						}


					}


				break;


			}


		}


		*/


		


		if(formerror){


			$("#form-error").find('li.error').remove();


			$("#form-error").find('li').eq(0).after(errors);


			$("#form-error").slideDown(200);


			e.preventDefault();


		}


		else {


			/* GET QUOTE DATA */


			var form = $(this),


				wrapper = $("#wrapper"),


				heightExcFooter = ($(window).height() - $("#outer-footer").height()),


				viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();


			


			$("#form-error").slideUp(200);


			


			$("html").animate({


				scrollTop:0


			},{


				duration:1000,


				easing: 'easeOutQuart',


				complete:function(){


					wrapper.animate({


						height: heightExcFooter


					},{


						easing: 'jswing',


						duration: 300,


						complete: function(){


							$(this).css('overflow','hidden'); //wrapper


							form.fadeOut(400,function(){


								$("body").append('<div id="quote-loader"><span>Getting Quotes...</span></div>');


								var loading	= $("#quote-loader").hide().fadeIn(400);				   


								$.ajax({


									url: 'get-quote.php',


									type: 'POST',


									data: form.serialize(),


									success: function(data){


										setTimeout(function(){


											form.after('<div id="quote-data">'+data+'</div>').hide();


											var quotedata = $('#quote-data').hide();


											wrapper.animate({


												height: '+=' + quotedata.height()


											},{


												duration: 400,


												complete: function(){


													loading.fadeOut(400,function(){ 


														$(this).remove() ;


														quotedata.fadeIn(200);


														wrapper.css('overflow','visible');


														//wrapper.css('height','auto');


													});	


												}


											}); // end wrapper animate (2nd)


										},1000); //end setTimeout


									} // end $.ajax success


								}) // end $.ajax


							}); // end form fadeOut


						} // end wrapper animate (1st)


					}); // end html scroll animate;


				} 


			});


			/* END GET QUOTE DATA */


			e.preventDefault();


		}


	});


	


	//change to multi trip


	$('#triptype').bind('change',function(){


		var label = $('label[for="numofdays"]'),


			html = '';


		if( $(this).val() == 'multi' ){


			html =  


					'<option value="31">Upto 31</option>'+


					'<option value="45">Upto 45</option>'+


					'<option value="60">Upto 60</option>';


					


			label.text('Maximum Trip Length:');


			$('#enddate-datepicker').slideUp(200);


		}


		else {


			html =  '<option value="5">Upto 5</option>'+


					'<option value="10">Upto 10</option>'+


					'<option value="17">Upto 17</option>'+


					'<option value="23">Upto 23</option>'+


					'<option value="31">Upto 31</option>'+


					'<option value="38">Upto 38</option>'+


					'<option value="45">Upto 45</option>'+


					'<option value="52">Upto 52</option>'+


					'<option value="60">Upto 60</option>';


			label.text( label.data('original_text') );


			$('#enddate-datepicker').slideDown(200);


		}


		$('#numofdays').html(html);


	})


	


	


	//onload


	$('#quote').bind('keypress', function(e){


		if(e.keyCode == 13) e.preventDefault();


	});


	


	$('#quote-data-back').live('click',function(){


		$('#quote-data').fadeOut(400,function(){


			$(this).remove();	


		});


		$('#quote').css('height','auto').hide().fadeIn(400);


		$('#wrapper').css('height','auto');


		$('html').animate({


			scrollTop:200


		},800);


	});


	


	$('label[for="numofdays"]').data('original_text', $('label[for="numofdays"]').text() );


	


	$("#coverfor, #destination").trigger('change')


	


	//tooltips


	$('.info-icon').hover(function(){


		var text = $(this).parent().find('.tooltip-text')


		$(this).append(text)


		$(this).find('.tooltip-text').hide().fadeIn(200);


	},function(){


		$(this).find('.tooltip-text').fadeOut(200);	


	})


	


	//End Quotation Form


	


	


	


	//***************************************************************************************


	// SECURE AREA


	//***************************************************************************************


	


	//validate admin login form


	$("#admin-login").validate ({


		rules: {


			username: {


				required: true


			},


			pass: {


				required: true,


				password: true


			}


		}


	});


	


	//validate forgot password form


	$("#forgot-password").validate ({


		rules: {


			forgot_email: {


				required: true,


				email: true


			}


		}


	});


	


	//forget password logic


	var forgotPasswordElem = $("#forgot");


	forgotPasswordElem.data('original-text',forgotPasswordElem.text());


	forgotPasswordElem.click(function(){


		$("#forgot-password,#admin-login").toggle();


		if( forgotPasswordElem.text() == 'Login' ){


			forgotPasswordElem.text( forgotPasswordElem.data('original-text') );	


		}


		else {


			forgotPasswordElem.text('Login');


		}


	});


	


	//inject toolbars


	var toolbar = $('.toolbar[data-is-master-copy=true]').clone(); //only get the master copy of the toolar


	$(toolbar).removeAttr('data-is-master-copy');


	$("[data-has-children='true']").prepend(toolbar);


	


	//show / hide toolbars on hover


	$("[data-has-children='true']")


		.live('mouseenter',function(){


			var activeElems = $("[data-state='active']").length;


			if( activeElems < 1 ){


				$(this).find('.toolbar').fadeIn(200);


			}


		})


		.live('mouseleave',function(){


			var self = $(this);


			if( !self.hasClass('active') ){


				self.find('.toolbar').fadeOut(200);


			}


		});


	


	//edit functionality


	$('.toolbar .edit').live('click',function(){


		


		//set block meta data


		var block = $(this).closest("[data-has-children='true']");


		block.removeClass('idle')


			 .addClass('active')


			 .attr('data-state','active');


		


		//create editable child elements


		block.find('*').each(function(){





			var self = $(this);


			if( self.attr('data-editable') == 'true' ){


				var id = self.attr('data-field') + '_editor',


					placeholder = self.attr('data-placeholder');


				switch( self.attr('data-editor') ){


					case 'input':


						var val = self.text(),


							editorHTML = "<input type='text' value='"+val+"' name='"+id+"' id='"+id+"' placeholder='"+placeholder+"' />";


					break;


					case 'textarea':


						var val = self.html(),


							editorHTML = "<textarea rows='6' name='"+id+"' id='"+id+"'>"+val+"</textarea>";


					break;


					case 'rte':


						var val = self.html(), 


							editorHTML = "<textarea class='MceEditor' rows='6' name='"+id+"' id='"+id+"'>"+val+"</textarea>";		


					break;


					case 'bubble':


						var str = '';


						self.children().each(function(){


							str += $(this).text() + ',';


						});


						str = str.substring(0,str.length-1);


						var editorHTML = "<textarea rows='6' name='"+id+"' id='"+id+"'>"+str+"</textarea>";


					break;


					case 'image':


						var docid = self.attr('data-id'),


							editorHTML = ' <a class="lightbox" href="upload_form.php?lightbox[width]=500&lightbox[height]=340&lightbox[modal]=true&uploader=document_image&docid='+docid+'" id="'+id+'"><div class="thumbnail-large-edit"></div></a>';


					break;


				}


				self.hide()


					.after(editorHTML);


					tinymceinit();


				placeholderPolyfill(); //polyfill for newly generated DOM elements


			}


		});


	});


	


	//revert editable elements back to there original element


	function revertEditableElems(block,updateValue)


	{


		var datastring = '';


		var i = 0;


		block.find("textarea[id*='_editor'],input[id*='_editor'],a[id='thumbnail_editor']").each(function(){


			var self = $(this),


				idParts = self.attr('id').split('_'),


				nameFromParts = (idParts.length > 2) ? idParts[0] + '_' + idParts[1] : idParts[0],


				e = block.find("[data-field='"+nameFromParts+"']"),


				id = $("#document_id").val(),


				name = idParts[0],


				val = self.val(),


				url = '';


			


			if( val == this.getAttribute('placeholder') ){


				val = '';	


			}


					


			//if tinymce, run trigger save before assigning the value to val variable	


			if(e.attr('data-editor') == 'rte'){


				tinyMCE.triggerSave();


				val = self.val();


			}


			


			if(updateValue){	


				i++;


				if(block.attr('data-area') == 'address'){


					var addid = block.attr('data-id');


					name = self.attr('name');


					name = name.substring(0,name.length-7);


					datastring += '&' + name + '=' + val;


					url = 'action=updatedocumentaddress&increment='+i+'&type=edit'+datastring+'&id='+addid;


				}


				else {


					url = 'action=updatedocument&item='+idParts[0]+'&value='+encodeURIComponent(val)+'&document_id='+id;


				}


				


				$.ajax({


					url: 'secureajax.php',


					data: url,


					type: 'POST',


					dataType: 'json',


					success: function(result){


						


					}


				});


				


				


				switch( e.attr('data-editor') ){


					case 'input':


						e.text(val);


					break;


					case 'textarea':


						e.text(val);


					break;


					case 'rte':


						e.html($('#'+idParts[0]+'_editor').val());


					break;


					case 'bubble':


						var valparts = val.split(','),


							html = '';


						for(val in valparts){


							html += "<li>"+valparts[val]+"</li>";


						}


						e.html(html);


					break;


					case 'image':


					


					break;


				}


			}


	


			if(e.attr('data-editor') == 'rte'){


				tinyMCE.execCommand('mceRemoveControl', false, self.attr('id'));


			}


			e.show();


			self.remove();	


				


		});


	}


	


	//accept and update changes


	$('.toolbar .accept').live('click',function(){


		var block = $(this).closest("[data-has-children='true']");


		revertEditableElems(block,true);


	});





	//cancel and revert changes


	$('.toolbar .cancel').live('click',function(){


		var block = $(this).closest("[data-has-children='true']");


		revertEditableElems(block,false);


	});


	


	//accept + cancel hide toolbar


	$('.toolbar .accept, .toolbar .cancel').live('click',function(){


		var block = $(this).closest("[data-has-children='true']");


		block.removeClass('active')


			 .addClass('idle')


			 .attr('data-state','idle');


	});


	


	//add new company button


	var newCompany = $('#add-new-company');


	$('#add-new-company-button').bind('click',function(){


		newCompany.show();


		$('#add-new-company-button').hide();


	});


	


	//accept add new company


	$('#add-new-company .toolbar .accept').bind('click',function(){


		$("#add-company").submit();


		if ( $("#add-company").valid() ) {


			


			var self = $(this),


				parent = self.closest('ul'),


				html = '<li data-has-children="true" data-state="idle" class="block idle deleteable address" data-deleteable="true"><ol>',


				docid = $("#document_id").val(),


				datastring = '',


				emptyform = true;


			


			self.parent().parent().find('input').each(function(){


				var self = $(this),


					name = self.attr('name'),


					val = self.val(),


					placeholder = this.getAttribute('placeholder');


				


				//if the value is the same as the placeholder, set it to nothing


				if(val == this.getAttribute('placeholder') ){


					val = '';	


				}


				


				if(val !== ""){


					emptyform = false;	


				}


				


				datastring += '&' + name + '=' + val;


				html += '<li><span data-editable="true" data-editor="input" data-field="'+name+'" data-placeholder="'+placeholder+'">'+val+'</span></li>';


			});


			html += '</ol></li>';


			


			//if form was not empty


			if(!emptyform){


				html = $(html).prepend( $('.toolbar:last').clone() );


				//do ajax


				$.ajax({


					url: 'secureajax.php' ,


					data: 'action=updatedocumentaddress'+datastring+'&type=add&docid='+docid,


					type: 'POST',


					dataType: 'json',


					success: function(result){


						


					}


				});


				


				$('#add-new-company').before(html);


			}


			


			$('#add-new-company').hide();


				


				


			$('#add-new-company-button').show();


			hasAddresses();


		}


		


	});


	


	$("#add-company").bind('submit',function(event){


		event.preventDefault();								  


	});


								   


	//cancel add new company


	$('#add-new-company .toolbar .cancel').bind('click',function(){


		$('#add-new-company').hide();


		$('#add-new-company-button').show();


	});


	


	//delete company


	$('.toolbar .delete').live('click',function(){


		var doDelete = confirm('Are you sure you want to delete this address? This cannot be undone!');


		if(doDelete){


			var block = $(this).closest("[data-has-children='true']");


			var id = block.attr('data-id');


			block.remove();


			//do ajax


			$.ajax({


					url: 'secureajax.php' ,


					type: 'POST',


					data: 'action=updatedocumentaddress&type=delete&id='+id,


					dataType: 'json',


					success: function(result){


						


					}


				});	


			hasAddresses();


		}


	});


	


	//delete document button


	$('#delete-doc').bind('click',function(){


		var self = $(this),


			attachements = $('#attachments'),


			actionComplete = false;


	


		if( self.data('mode') == 'deleting' ){


			var okToDelete = confirm('Are you sure you want to delete the selected attachements? This cannot be undone!');


			


			if( okToDelete ){


				var toDelete = '';	


				var idtodelete = '';


				attachements.find('.selected').each(function(){


					var self = $(this);


					toDelete += self.attr('data-file') + ',';


					idtodelete += self.attr('data-fileid') + ',';


					self.remove();


				});


				toDelete = toDelete.substring(0,toDelete.length-1);


				idtodelete = idtodelete.substring(0,idtodelete.length-1);


				//do ajax pass to delete


				$.ajax({


					url: 'secureajax.php?action=deleteattachment&idtodelete='+idtodelete ,


					type: 'GET',


					dataType: 'json',


					success: function(result){


						hasAttachments();


					}


				});


				actionComplete = true;


			}


			


			if(actionComplete){


				self.data('mode','idle');


				attachements.data('mode','idle');


				$('#delete-ins, #cancel-delete-doc').hide();


				self.text('Delete Attachement');


				$('#new-doc').show();


				hasAttachments();


			}


			


		}


		else {


			self.data('mode','deleting');


			self.text('Delete Selected Attachements');


			$('#attachments').data('mode','deleting');


			$('#delete-ins, #cancel-delete-doc').show();


			$('#new-doc').hide();


		}


		hasAttachments();


	});


	


	//attachements click event


	$('#attachments li a').live('click',function(event){	


		var self = $(this);


		if( self.parent().parent().data('mode') == 'deleting' ){


			event.preventDefault();


			if( self.hasClass('selected') ){


				self.removeClass('selected');


			}


			else {


				self.addClass('selected');	


			}


		}


	});


	


	//cancel deleting event


	$('#cancel-delete-doc').bind('click',function(){


		$('#attachments .selected').removeClass('selected');


		


		$('#delete-doc').data('mode','idle');


		$('#attachments').data('mode','idle');


		


		$('#delete-ins, #cancel-delete-doc').hide();


		$('#delete-doc').text('Delete Attachement');


		


		$('#new-doc').show();


		hasAttachments();


	});





  	//tinymce 


	function tinymceinit(){


		tinyMCE.init({


			mode : "textareas",


			theme : "advanced",


			skin:"o2k7",


			skin_variant : "silver",


			plugins : "safari,fullscreen,paste",		


			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,indent,outdent,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,fontsizeselect,seperator,fontselect,seperator,formatselect", 


			theme_advanced_buttons2 : "link,unlink,seperator,undo,redo,copy,paste,seperator,pastetext,pasteword,selectall,seperator,removeformat,cleanup,code,seperator,fullscreen",


			theme_advanced_buttons3 : "",


			theme_advanced_fonts: "Arial=arial",


			theme_advanced_font_sizes : "11px,12px,14px,16px,18px,20px,24px,28px",


			theme_advanced_toolbar_location : "top",


			theme_advanced_toolbar_align : "center",


			theme_advanced_statusbar_location : "bottom",


			theme_advanced_resizing : true,


			width : "647px",


			height : "500px",


			editor_selector : "MceEditor",


			document_base_url : "/", //NEEDS THIS!!!


			content_css :  "",


			invalid_elements : "div",


			cleanup_on_startup : false,


			cleanup :true,


			trim_span_elements : false,


			verify_html : true


		});


	}


	


	//placeholders polyfill


	function placeholderPolyfill()


	{


		$('input').each(function(){


			if(!Modernizr.input.placeholder){


				var placeholderText = this.getAttribute('placeholder'),


					initVal = ( $(this).val() !== '' ) ? $(this).val() : placeholderText;


				if(placeholderText){


					$(this)


						.addClass('placeholder-text')


						.val(initVal)


						.bind('focus',function(){


							if(this.value == placeholderText){


								$(this)


									.val('')


									.removeClass('placeholder-text');


							}


						})


						.bind('blur',function(){


							if(this.value == ''){


								$(this)


									.val(placeholderText)


									.addClass('placeholder-text');


							}


						});		


				}


			}


		});


	}


	


	//enable lightbox


	if( $('.lightbox').length > 0 ){


		$('.lightbox').lightbox();


	}


	


	//on init


	hasAddresses();


	hasAttachments();


	placeholderPolyfill();


	$('#delete-ins, #cancel-delete-doc').hide();





});





//hide delete attachments + bounding box if there are no documents to delete or show


function hasAttachments()


{


	if( $('#attachments li').length > 0 ){


		$('#attachments, #delete-doc').show();


	}


	else {


		$('#attachments, #delete-doc').hide();


	}


}





//show no addresses message


function hasAddresses()


{


	if( $('.address').length < 1 ){


		$('#no-addresses').show();	


	}


	else {


		$('#no-addresses').hide();	


	}


}


								  


	
