
// namespace
var PROFILEWRITER = PROFILEWRITER || {};

// stop image flicker on backgrounds in ie6
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

// alert
say = function(str){
    try{
			if(typeof(console) !== 'undefined' && console != null)
      {
        window.loadFirebugConsole();
        console.log(str);
    	}
    }catch(e){
        alert(str);
    }
}

// tell me what an object is all about
describeObject = function(obj){
	for(var name in obj){
		say(name + " = " + obj[name]);
	}
}

changeLanguage = function(lang){
	var queryArr = window.location.href.split("&"), 
			newLocationArr = [],
			newLocation,
			k = 0;
	for (var i in queryArr)
	{
		if (queryArr[i].indexOf("language=") == -1)
		{
			newLocationArr[k] = queryArr[i];
			k++;
		}
	}
	
	newLocation = newLocationArr.join("&") + "&language=" + lang;
	window.location.href = newLocation;
}

downloadProfile = function(fileType)
{
	$("#dldValue").val(PROFILEWRITER.getHTMLProfile());
	if (fileType == 'doc')
	{
		sendUserActionEvent('CLICK', 'DOC DOWNLOAD');
		$("#dldForm").attr("action", "/include/html2doc.php");
	}
	else
	{
		sendUserActionEvent('CLICK', 'PDF DOWNLOAD');
		$("#dldForm").attr("action", "/include/html2pdf.php");
	}
	setTimeout(function() { $("#dldForm").submit(); }, 500);
}

sendEmail = function()
{
	$.post("/include/ajax.send_email.php",{email: $("#email-address").val(), html: PROFILEWRITER.getHTMLProfile()},
	function(json)
	{
		if (json.success == 'true')
		{
			sendUserActionEvent('CLICK', 'EMAIL_MY_PROFILE');
			$(".validation").find("p").css("color", "green");
		}
		else
		{
			$(".validation").find("p").css("color", "#FF0000");
		}
		
		$(".validation").removeClass("hide");
		$(".validation").find("p").html(json.msg);
	}, "json");
}

saveProfile = function()
{
	var getUsername = 0;
	if (typeof($("#register-trigger-links a").attr("href")) != "undefined" && $("#register-trigger-links a").attr("href") == "#")
	{
		getUsername = 1;
	}
	
	$.post("/include/ajax.save_profile.php",{profile: escape(JSON.stringify(currentFeedback)), response_id: response_id, language: language, getUsername: getUsername},
	function(json)
	{
		if (json.userHasProfile == true)
		{
			$("#register-trigger-links a").attr("href", "/" + json.username);
			$("#register-trigger-links ul li:first").removeClass("inactive");
		}
	}, "json");
}

// string trim function
trim = function(str){
	return str.replace(/^\s+|\s+$/g,"");
}
ltrim = function(str){
	return str.replace(/^\s+/,"");
}
rtrim = function(str){
	return str.replace(/\s+$/,"");
}

// to run on page load
$(window).load(function(){
	// initiaise the editing functionality
	if($('body.edit').length > 0){
		PROFILEWRITER.init();
	}else if($('body.sample').length > 0){
		PROFILEWRITER.init(true);
	}

	if ($("#email-address").length > 0)
	{
		$("#email-address").keypress(function(e) {
			if(e.keyCode == 13) {
				sendEmail();
			}
		});
	}
	
	if (showFullResults == true && userIsOwner == true && typeof(examples) == 'undefined')
	{
		//saving initial displayed profile
		saveProfile();
	}
});

submitPaypalFormTypeB = function()
{
	VDNA_SetUpInfoCookie("VDNAcheckedPaypal", "true");
	document._xclick.submit();
}

// to run on DOM ready
$(function(){

});

// our profile writer stuff
PROFILEWRITER = {

	getPartialFeedback : function(sample){
	
		var data = feedback; // get feedback from wherever
		
    	if(!data.section.length){
    		// no sections
    	}
    	else
    	{
				var checkPayment = 0;
    		$.each(data.section, function(i, item){
    		checkPayment++;
    		if (checkPayment == 3 && hasPaid == false)
    		{
    			return false;
    		}
    		// create section div
				var section = document.createElement('DIV');
				$(section).attr('class', 'section');
				
				// add title
				var h4 = document.createElement('H4');
				$(h4).html('<span>' + item["@attributes"].ident.replace("_", " ") + '</span>');
				$(section).append($(h4));
				
				// create paragraph div
				var paragraph = document.createElement('DIV');
				$(paragraph).attr('class', 'paragraph');
				if(i===0){
					$(paragraph).addClass('header');
				}
				$(section).append($(paragraph));
				
				var everyChunk = []; // an array containing arrays of chunks
				$.each(item.text, function(k, item){ // all paragraphs
					var chunks = []; // temp array containing initial chunks
					$.each(item.chunkGroup, function(j, _item){
						if(_item.chunk[0]){
							var allChunks = []; // all chunks
							var showChunk = 0;
							for(var k = 0 ; k < _item.chunk.length ; k++){
								allChunks.push(_item.chunk[k]["@value"]);
							}
							var span = document.createElement('SPAN');
							$(span).html(_item.chunk[showChunk]["@value"] + '&nbsp;');
							$(span).data('others', allChunks);
							$(span).data('temp', allChunks);
							$(span).data('current', 0);
							$(span).data('total', _item.chunk.length);
							// put initial chunk into chunks
							chunks.push($(span));
						}
					});
					// put all initial chunks into everyChunk
					everyChunk.push(chunks);
					
					// if this is just a sample page, break out of the loop
					if(sample===true && k === 0){
						return false;
					}
					if (checkPayment == 2)
						return false;
				});
				
				// for each paragraph
				for( var m = 0 ; m < everyChunk.length ; m++ ){
					// create paragraph-text div
					var paragraphtext = document.createElement('DIV');
					$(paragraphtext).attr('class', 'paragraph-text');
					$(paragraphtext).html('<p><span></span></p>');
					$(paragraph).append($(paragraphtext));
					// add the chunks (needs to be done like this as we need to add
					// HTML *objects* not HTML text
					var $span = $(paragraphtext).children('p').children('span');
					for(var l = 0 ; l < everyChunk[m].length ; l++){
						$span.append(everyChunk[m][l]);
					}
				}
				
				// add to page										
				$('#inner-page-inner').append($(section));
				
				// if this is just a sample page, break out of the loop
				if(sample===true && i === 1){
					return false;
				}
    	
    		});
    		
				if (startProfileWriter == true)
				{
					$('#loading').hide();
				}
    		$('#inner-page').show();
    		
    		//set up the editing functionality
    		PROFILEWRITER.editEvents(sample);
    	
    	}
	},


	getFeedback : function(sample){
	
		var data = feedback; // get feedback from wherever
		
    	if(!data.section.length){
    		// no sections
    	}
    	else
    	{
				// clearing sections divs if any, before adding the new ones
				$('#inner-page-inner').find(".section").remove();
				
				$.each(data.section, function(i, item){
				// create section div
				var section = document.createElement('DIV');
				$(section).attr('class', 'section');
				
				// add title
				var h4 = document.createElement('H4');
				$(h4).html('<span>' + item["@attributes"].ident.replace("_", " ") + '</span>');
				$(section).append($(h4));
				var group = item["@attributes"].ident;
				
				// create paragraph div
				var paragraph = document.createElement('DIV');
				$(paragraph).attr('class', 'paragraph');
				if(i===0){
					$(paragraph).addClass('header');
				}
				$(section).append($(paragraph));
				
				var everyChunk = []; // an array containing arrays of chunks
				$.each(item.text, function(k, item){ // all paragraphs
					var chunks = []; // temp array containing initial chunks
					$.each(item.chunkGroup, function(j, _item){
						if(_item.chunk[0]){
							var allChunks = []; // all chunks
							var showValue = []; // where from do we take the text: @value or @updated
							var showChunk = 0; // position of the first time displayed text
							for(var k = 0 ; k < _item.chunk.length ; k++)
							{
								showValue[k] = "@value";
								if (typeof(_item.chunk[k]["@selected"]) != "undefined" && _item.chunk[k]["@selected"] == "true")
								{
									showChunk = k;
									var status = "show";
									if (typeof(_item.chunk[k]["@status"]) != "undefined" && _item.chunk[k]["@status"] == "hide")
									{
										 status = "hide";
									}
								}
								if (typeof(_item.chunk[k]["@updated"]) != "undefined" && _item.chunk[k]["@updated"] != "false")
								{
									showValue[k] = "@updated";
								}
								allChunks.push(_item.chunk[k][showValue[k]]);
							}
							if (showFullResults == true)
							{
								// saving modifs in DB if the user paid for it :)
								PROFILEWRITER.updateCurrentFeedback(group, _item.chunk[showChunk][showValue[showChunk]], 'false', status);
							}
							var span = document.createElement('SPAN');
							$(span).html(_item.chunk[showChunk][showValue[showChunk]] + '&nbsp;');
							if (status == "hide")
							{
								if( item.chunkGroup.length == 1){
									$(span).addClass('no-text').html('<img src="http://resources-ms-ak.visualdna.com/profile-writer.visualdna.com/live/20100219171245/images/profile/bringback.gif" alt="" />');
								}else{
									$(span).addClass('hide');
								
								}
								$(span).data('disabled', 'true');
							}
							$(span).data('others', allChunks);
							$(span).data('temp', allChunks);
							$(span).data('current', showChunk);
							$(span).data('total', _item.chunk.length);
							// put initial chunk into chunks
							chunks.push($(span));
						}
					});
					// put all initial chunks into everyChunk
					everyChunk.push(chunks);
					
					// if this is just a sample page, break out of the loop
					if(sample===true && k === 0){
						return false;
					}
				});
				
				// for each paragraph	
				for( var m = 0 ; m < everyChunk.length ; m++ ){
					// create paragraph-text div
					var paragraphtext = document.createElement('DIV');
					$(paragraphtext).attr('class', 'paragraph-text');
					$(paragraphtext).html('<p><span></span></p>');
					$(paragraph).append($(paragraphtext));
					// add the chunks (needs to be done like this as we need to add
					// HTML *objects* not HTML text
					var $span = $(paragraphtext).children('p').children('span');
					for(var l = 0 ; l < everyChunk[m].length ; l++){
						$span.append(everyChunk[m][l]);
					}
				}
				
				// add to page										
				$('#inner-page-inner').append($(section));
				
				// if this is just a sample page, break out of the loop
				if(sample===true && i === 1){
					return false;
				}
    	
    		});
    		
      	$('#loading').hide();
    		$('#inner-page').show();
    		
    		if (userIsOwner == true)
	    	{
	    		//set up the editing functionality
	    		PROFILEWRITER.editEvents(sample);
				}
    	}
	},

	updateCurrentFeedback : function(group, value, update, status)
	{
		var data = currentFeedback; // get feedback from wherever
		if (update != "false")
		{
			var temp = update;
			update = value;
			value = temp;
		}
		$.each(data.section, function(i, item)
		{
			if (item["@attributes"].ident == group)
			{
				$.each(item.text, function(k, item)
				{
					$.each(item.chunkGroup, function(j, _item)
					{
						if(_item.chunk[0])
						{
							for(var k = 0 ; k < _item.chunk.length ; k++)
							{
								if (value == _item.chunk[k]["@value"] || value == _item.chunk[k]["@updated"])
								{
									for(var j = 0 ; j < _item.chunk.length ; j++)
									{
										if (typeof(_item.chunk[j]["@selected"]) != "undefined")
										{
											_item.chunk[j]["@selected"] = "false";
										}
										if (typeof(_item.chunk[j]["@status"]) != "undefined")
										{
											_item.chunk[j]["@status"] = status;
										}
									}
									_item.chunk[k]["@selected"] = "true";
									_item.chunk[k]["@status"] = status;
									if (update != 'false')
									{
										_item.chunk[k]["@updated"] = update;
									}
								}
							}
						}
					});
				});
			}
		});

	},

	// set up load events for editing functionality
	editEvents : function(sample){
	
		if(sample===true){ return; }
		
		var $p = $('#inner-page-inner').children().find('div.paragraph-text p'), // editable paragraphs
		$text = $('#inner-page-inner').children().find('div.paragraph-text'),
		$edit = $('#inner-page-inner').children().find('div.paragraph-edit'),
		$div = $('#inner-page-inner').children().find('div.paragraph'), // div.paragraph
		$section = $('#inner-page-inner').children('div.section'), // div.section
		$h4 = $('#inner-page-inner').children().find('h4'), // h4s
		pos, // paragraphs position
		$paragraph, // paragraph's div.paragraph
		offset = 320, // offset X, to position click to edit properly
		originalY = 20, // original/starting position of click to edit. should match the css
		y, // mouse Y position
		x, // mouse X position
		$clickToEdit = $('div#clicktoedit'), // click to edit button
		$active, // active paragraph
		that = this, // grab this
		timer, highlightHeader;
		if(window.location.href.indexOf('example')!=-1){
			originalY = -4; // original/starting position of click to edit on examples page. should match the css
			offset = 260;
		}
		
		if($('#profile-intro').length>0){
			offset = 260;
		}
		
		// paragraph mouseover				
		$p.bind('mouseover', function(){
			window.clearTimeout(timer);
			$active = $(this);
			// get section
			$paragraph = $(this).parents('div.paragraph');
			// add yellow background and highlight title
			$(this).addClass('over');
		});
		
		// paragraph mouseout	
		$p.bind('mouseout', function(){
			$active = $(this);
			// get section
			$paragraph = $(this).parents('div.paragraph');
			// remove yellow background and unhighlight title
			$(this).removeClass('over');
		});
		
		// highlights the header		
		highlightHeader = function($obj, on){
			(on)? $obj.children('h4').addClass('selected') :$obj.children('h4').removeClass('selected');
		};
		
		// highlight header event		
		$section.bind('mouseenter', function(){
			highlightHeader($(this), true);
		});

		// highlight header event		
		$section.bind('mouseleave', function(){
			highlightHeader($(this), false);
		});
		
		// section mouseleave		 
		$section.bind('mouseleave', function(){
			// move it back to start
			timer = window.setTimeout(function(){
				$clickToEdit.animate({ top: originalY}, 500);
			}, 500);
		});

		// paragraph mousemove / mouseenter
		$p.bind('mousemove', function(e){
			window.clearTimeout(timer);
			// work out position
			y = e.pageY - offset;
			// move it
			$clickToEdit.css('top', y);
		});
		
		// h4 mousemove / mouseenter
		$h4.bind('mousemove', function(e){
			window.clearTimeout(timer);
			// work out position
			y = e.pageY - offset;
			// move it
			$clickToEdit.css('top', y);
		});
		
		// edit mouseenter
		$edit.bind('mouseenter', function(){
			// move it back to start
			timer = window.setTimeout(function(){
				$clickToEdit.animate({ top: originalY}, 500);
			}, 500);
		});
		
		// click
		$p.bind('click', function(){
			that.showEditMode($(this));
		});
		
		// change to edit mode when h4 is clicked too		
		$h4.bind('click', function(){
			if($(this).data('edit') != 'true'){
				$(this).parent().children().find('div.paragraph-text p').trigger('click');
				$(this).data('edit', 'true');
			}else{
				$(this).parent().children().find('div.done').trigger('click')
				$(this).data('edit', 'false');
			}
		});
		
	},
	
	// adds functionality to copy button
	createCopyButton : function(sample){
		if(sample===true){ return; }
		var that = this;
		var url = window.location.href;
		ZeroClipboard.setMoviePath('http://resources-ms-ak.visualdna.com/profile-writer.visualdna.com/live/20100219171245/swf/ZeroClipboard.swf');
		var clip = new ZeroClipboard.Client();
		clip.addEventListener('mousedown',function(e) {
			clip.setText(that.getProfile());
			e.preventDefault();
		});
		clip.addEventListener('complete',function(client,text) {
			sendUserActionEvent('CLICK', 'COPY_ALL_TEXT');
			alert("You've copied your profile to the clipboard!");
		});
		clip.glue('copy-button');
	},
	
	// gets the current shown profile
	getProfile : function(){
		var $sections = $('#inner-page-inner').children('div.section'),
		str = [], header, paragraphs, capitalize;

		capitalize = function(obj){
			var val = obj,newVal = '';
			val = val.split(' ');
		    for(var c = 0; c < val.length; c++){
		    	newVal += val[c].substring(0,1).toUpperCase() +
					val[c].substring(1,val[c].length) + ' ';
		    }
	  		return newVal;
	  	}

		// remove any edit screens		
		$.each($sections, function(){
			$(this).children().find('div.done').trigger('click');
		});
		$.each($sections, function(){
			header = $(this).children('h4').children('span').text();
			paragraphs = $(this).children('div.paragraph').children().find('p');
			
			str.push(capitalize(header));
			$.each(paragraphs, function(){
				paragraph = $(this).html();

				paragraph = paragraph.replace(/\<span class="no-text hide">.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class="hide no-text">.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class="hide">.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class="no-text">.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class=no-text hide>.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class=hide no-text>.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class=hide>.+?<\/span>/gi, "");
				paragraph = paragraph.replace(/\<span class=no-text>.+?<\/span>/gi, "");
				
				paragraph = paragraph.replace(/\<[\/]?span\>/gi, "");
				paragraph = paragraph.replace(/&nbsp;/g, "");
				str.push(paragraph);
			});
		});
		str = str.join('\n\n');
		return str;
	},
	
	// gets the current shown profile
	getProfileChunks : function(){
		var $sections = $('#inner-page-inner').children('div.section'),
		str = [], header, paragraphs, capitalize;

		// remove any edit screens
		$.each($sections, function(){
			$(this).children().find('div.done').trigger('click');
		});
		$.each($sections, function(){
			header = $(this).children('h4').children('span').text();
			paragraphs = $(this).children('div.paragraph').children().find('p');
			str.push(header);
			$.each(paragraphs, function(){
				paragraph = $(this).html();
				paragraph = paragraph.replace(/&nbsp;/g, "");
				str.push(paragraph);
			});
		});
		str = str.join('\n\n');
		return str;
	},

	// gets the current shown profile
	getHTMLProfile : function(){
		var $sections = $('#inner-page-inner').children('div.section'),
		str = [], header, paragraphs, capitalize, span, spans;
		// remove any edit screens		

		capitalize = function(obj){
			var val = obj,newVal = '';
			val = val.split(' ');
	    for(var c = 0; c < val.length; c++){
	    	newVal += val[c].substring(0,1).toUpperCase() +
				val[c].substring(1,val[c].length) + ' ';
	    }
  		return newVal;
  	}
		$.each($sections, function(){
			$(this).children().find('div.done').trigger('click');
		});
		$.each($sections, function(){
			header = $(this).children('h4').children('span').text();
			paragraphs = $(this).children('div.paragraph').children().find('p');
			str.push("<br /><b>" + capitalize(header) + "</b>");
			$.each(paragraphs, function(paragraph){
				bigSpan = $(this).children('span').find("span");
				spans = "";
				// removing hidden spans from the profile
				$.each(bigSpan, function(){
					if ($(this).attr("class") != 'hide')
					{
						span = $(this).html();
						span = span.replace(/&nbsp;/g, "");
						if (span.indexOf("<img") == -1 && span.indexOf("<IMG") == -1)
						{
							spans += span;
						}
					}
				});
				if (spans != "")
					str.push(spans);
			});
		});
		str = str.join('<br /><br />');
		return str;
	},

	// switches to edit mode
	showEditMode : function($obj){
		var $chunks = $obj.children('span').children('span'), // text chunks
		$textarea,// textarea to create
		div, // contains textarea
		$paragraph = $obj.parents('div.paragraph'),
		that = this, // the text section
		done, // done button
		cancel, // cancel button
		clear; // clear float
		
		$obj.parents('div.section').children('h4').data('edit', 'true');
		
		// create containing div
		div = document.createElement('DIV');
		$(div).attr('class', 'paragraph-edit');
		
		// create text areas
		$.each($chunks, function(i){
			$textarea = that.createTextArea($(this));
			$(div).append($textarea);
		});
		
		// create done button
		done = document.createElement('DIV');
		$(done).attr('class', 'done');
		$(done).html('<a href="#" onclick="return false;" title="Update"><span>Update</span></a>');
		$(done).bind('click', function(){
			that.saveChunks($(this), true);
		});
		
		// create clear
		clear = document.createElement('DIV');
		$(clear).attr('class', 'clear');
		
		// IE needs us to hide the click to edit btn
		$obj.mouseout();
		// hide display mode
		$obj.parent().hide();
		// append done button
		$(div).append($(done));
		// append clear
		$(div).append($(clear));
		// append textareas
		$(div).insertAfter($obj.parent());
		
		// scroll
		/*		
		var top = $obj.parents('.section').position().top + $obj.parents().position().top;
		window.setTimeout(function(){
			$(window).scrollTo(top, 500);
		},100);
		*/

	},
	
	// creates textareas and textarea control
	createTextArea : function($obj){
	
		var textarea, textareabox, suggestright, suggestleft, textareacheckdiv, textareacheck, textareacheckbg // html elements
		that = this, // grab this
		chunkTotal = $obj.data('total'), // number of chunks
		others =  $obj.data('others'), // all chunks
		current = $obj.data('current'), // current visible chunk
		disabled = $obj.data('disabled'); // disabled?
	
		// create outer area
		textareabox = document.createElement('DIV');
		$(textareabox).attr('class', 'textarea-box');
		$(textareabox).data('total', chunkTotal);
		$(textareabox).data('current', current);
		$(textareabox).data('originals', others); // associate the chunks
		
		// create next suggestion box
		suggestright= document.createElement('DIV');
		if((current+1)==chunkTotal){
			$(suggestright).attr('class', 'suggest-right hide');
		}else{
			$(suggestright).attr('class', 'suggest-right');
		}
		$(suggestright).html('<p title="Try again">Try again</p>');
		$(suggestright).bind('click', function(){
			that.getNextSuggestion($(this));
		});
		
		// create previous suggestion box
		suggestleft = document.createElement('DIV');
		if(current!=0){
			$(suggestleft).attr('class', 'suggest-left');
		}else{
			$(suggestleft).attr('class', 'suggest-left hide');
		}
		$(suggestleft).html('<p title="Previous suggestion">&nbsp;</p>');
		$(suggestleft).bind('click', function(){
			that.getPreviousSuggestion($(this));
		});
		
		// create disable/enable text chunk checkbox container
		textareacheckdiv = document.createElement('DIV');
		$(textareacheckdiv).attr('class', 'textarea-check');
		
		// create disable/enable text chunk checkbox container
		if(disabled !== 'true'){
			textareacheck = $('<input type="checkbox" checked="checked" />');
		}else{
			textareacheck = $('<input type="checkbox" />');
		}
		$(textareacheck).attr('class', 'checkbox');
		$(textareacheck).bind('click', function(){
			that.changeTextChunkStatus($(this));
		});
		
		textareacheckbg = document.createElement('DIV'); 
		$(textareacheckbg).attr('class', 'textarea-check-bg');
		
		// create textarea
		textarea = document.createElement('TEXTAREA');
		$(textarea).attr('class', 'textarea');
		$(textarea).attr('id', '');
		$(textarea).text(others[current]);
		$(textarea).data('temp', $obj.data('temp')); // set up temp area for none saved edits
		if(disabled === 'true'){
			$(textarea).attr('disabled', 'disabled');
			$(textarea).addClass('disabled');
		}
		
		if(chunkTotal){
			$(textareabox).append(suggestright);
			$(textareabox).append(suggestleft);
		}
		$(textareacheckdiv).append(textareacheck);
		$(textareacheckdiv).append(textareacheckbg);
		$(textareabox).append(textareacheckdiv);
		$(textareabox).append(textarea);
		
		return $(textareabox);
	},
	
	// get next suggestion
	getNextSuggestion : function($obj){
		var $textarea = $obj.siblings('textarea'), // textarea
		originals = $obj.parent().data('originals'), // original chunks array
		temp = $textarea.data('temp'), // temp chunks array
		total = $obj.parent().data('total'), // total chunks
		current = $obj.parent().data('current'), // current visible chunk
		$previous = $obj.siblings('div.suggest-left'); // previous button

		$previous.removeClass('hide'); // show previous button
		
		// grab the current text as it may have been edited, and overwrite the temp array
		temp[current] = $textarea.val();
		$textarea.data('temp', temp);
		
		if(temp[current+1]){
			$textarea.val(temp[current+1]); // show next chunk
			$obj.parent().data('current', current+1);
		}
		
		// hide next button if we're at the end
		if(current+1==total-1){
			$obj.addClass('hide');
		}
	},

	// get previous suggestion
	getPreviousSuggestion : function($obj){
		var $textarea = $obj.siblings('textarea'), // textarea
		originals = $textarea.data('originals'), // original chunks array
		temp = $textarea.data('temp'), // temp chunks array
		total = $obj.parent().data('total'), // total chunks
		current = $obj.parent().data('current'), // current visible chunk
		$next = $obj.siblings('div.suggest-right'); // next button
		
		$next.removeClass('hide'); // show next button
		
		// grab the current text as it may have been edited, and overwrite the temp array
		temp[current] = $textarea.val();
		$textarea.data('temp', temp);
		
		if(temp[current-1]){
			$textarea.val(temp[current-1]); // show previous chunk
			$obj.parent().data('current', current-1); // update current chunk variable
		}
		
		// hide previous button if we're at the beginning
		if(current-1==0){
			$obj.addClass('hide');
		}
	},
	
	// disables/enables text chunk
	changeTextChunkStatus : function($obj){
		if($obj.is(':checked')){
			$obj.parents('div.textarea-box').children('textarea').removeAttr('disabled');
			$obj.parents('div.textarea-box').children('textarea').removeClass('disabled');
		}else{
			$obj.parents('div.textarea-box').children('textarea').attr('disabled', 'disabled');
			$obj.parents('div.textarea-box').children('textarea').addClass('disabled');
		}
	},
	
	// saves any edited chunks
	saveChunks : function($obj){
		var $paragraph = $obj.parents('div.paragraph'), // section
		$paragraphedit = $paragraph.children('div.paragraph-edit'), // section edit
		$textareas = $paragraphedit.children().find('textarea'); // textareas
		
		var group = $obj.parent().parent().parent().find("h4").find("span").html().replace(" ", "_");
		$.each($textareas, function(){
			var temp = $(this).data('temp');
			var current = $(this).parent().data('current');
			var previousValue = "false";
			if ($(this).val() != temp[current])
				previousValue = temp[current];
			temp[current] = $(this).val();
			if (showFullResults == true)
			{
				var status = "show";
				if($(this).attr('disabled')){
					status = "hide";
				}
				// saving modifs in DB if the user paid for it :)
				PROFILEWRITER.updateCurrentFeedback(group, $(this).val(), previousValue, status);
			}
			$(this).data('temp', temp);
			$(this).parent().data('originals', $(this).data('temp'));
		});
		
		if (showFullResults == true && typeof(examples) == 'undefined')
		{
			// saving modifications to the DB
			saveProfile();
		}

		$(this).data('temp', $(this).parent().data('originals'));
		this.showDisplayMode($obj);
	},
	
	// switches to display mode
	showDisplayMode : function($obj){
		
		var $paragraph = $obj.parents('div.paragraph'), // section
		str = '', // new string
		$paragraphtext = $obj.parent().prev('div.paragraph-text'), // section text
		$paragraphedit = $obj.parent(), // section edit
		$textareas = $paragraphedit.children().find('textarea'), // textareas
		$paragraphp = $paragraphtext.children('p'), // section paragraph
		hidden = false;
		
		$obj.parents('div.section').children('h4').data('edit', 'false');
		
		// create new paragraph
		var chunks = [] // chunk to show
		$.each($textareas, function(){
			var total = $(this).parent().data('total');
			var current = $(this).parent().data('current');
			var others = $(this).parent().data('originals');
			var span = document.createElement('SPAN');
			$(span).data('others', others);
			$(span).data('temp', others);
			$(span).data('total', total);
			$(span).data('current', current);
			if($(this).attr('disabled')){
				$(span).data('disabled', 'true');
				$(span).html('&nbsp;');
				hidden = true;
				//if( $textareas.length == 1 ){
					$(span).html('<img src="http://resources-ms-ak.visualdna.com/profile-writer.visualdna.com/live/20100219171245/images/profile/bringback.gif" alt="" />');
					$(span).addClass('no-text');
					$(span).addClass('hide');
				//}
			}else{
				$(span).html($(this).val() + '&nbsp;');
			}
			chunks.push($(span));
		});
		
		// remove old text
		$paragraphp.children('span').children().remove();
		
		// add the chunks (needs to be done like this as we need to add
		// HTML *objects* not HTML text
		for(var l = 0 ; l < chunks.length ; l++){
			$paragraphp.children('span').append(chunks[l]);
		}
		
		if($paragraphp.children('span').children('span').not('.no-text').length == 0){		
			if($paragraphp.children('span').children('span.no-text').length == 1){
				$paragraphp.children('span').children('span.no-text').removeClass('hide');
			}else{
				$paragraphp.children('span').children('span.no-text:first').removeClass('hide');
			}
		}

		// hide edit
		$paragraphtext.show();
		// show display
		$paragraphedit.remove();
		
	},
	
	// initialise
	init : function(sample){
		
		if (showFullResults == false)
		{
			// grab partial feedback
			this.getPartialFeedback(sample);
		}
		else
		{
			// grab the feedback	
			this.getFeedback(sample);
		}

		
		if (userIsOwner == true && showFullResults == true)
		{
			// create the copy button 
			this.createCopyButton(sample);
		}
	}

}

/* jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Dual licensed under MIT and GPL.
 */
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

/* /*----------------------------------------------------------------------------
 * jQuery Clipboard Copy
 * ---------------------------------------------------------------------------
 * Author:  Stephen Blum
 */
jQuery.copy=function(data){return jQuery.fn.copy.call({},data);};jQuery.fn.copy=function(delimiter){var self=this,flashcopier=(function(fid){return document.getElementById(fid)||(function(){var divnode=document.createElement('div');divnode.id=fid;document.body.appendChild(divnode);return divnode;})();})('_flash_copier'),data=jQuery.map(self,function(bit){return typeof bit==='object'? bit.value||bit.innerHTML.replace(/<.+>/g,''):'';}).join(delimiter||'').replace(/^\s+|\s+$/g,'')||delimiter,divinfo='<embed src="jquery.copy.swf"FlashVars="clipboard='+encodeURIComponent(data)+'"width="0"height="0"'+'type="application/x-shockwave-flash"></embed>';flashcopier.innerHTML=divinfo;return self;};