var may_tween = true;

var cur_opened = {}; //ref to currently opened DOM object (TR)
cur_opened['data_avaible'] = false;

var annimation_process = false; //any active annimation flag





function stop_tween(delay){
	may_tween = false;
	setTimeout(function(){may_tween = true; annimation_process = false;}, delay);
}

function check_new_post(form){
	return check_values(form.elements);
}

function check_values(arr){
	// checks all elemnts and focuses invalid if any
	for (var i = 0; i < arr.length; i++){
		var el = arr[i];
		if (el.name){
			if (!el.value){
				alert('All fields are required');
				el.focus();
				return false;
			}
			field_type = el.getAttribute('field_type');
			if (field_type){
				if (field_type == 'int'){
					if (isNaN(parseInt(el.value)) || (parseInt(el.value).toString() !== el.value)){
						alert('Please enter a number (no decimal places)');
						el.focus();
						return false;
					}
				}
				if (field_type == 'date'){
					if  (isNaN(Date.parse(el.value))){
						alert('Please enter a correct date');
						alert((el.value));
						el.focus();
						return false;
					}
				}
			}
		}
	}
	return true;
}


function get_editable_controls(){

	var arr = Array();
	var expanded = document.getElementById('expanded');
	var expanded_divs = expanded.getElementsByTagName('div');
	for (var i = 0; i < expanded_divs.length; i++ ){
		var el = expanded_divs[i];
		
		var var_name = el.getAttribute('var_name');
		if (!var_name) continue;	

		arr.push(el);

		el = null;
	}
	expanded_divs = null;

	var td = expanded.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;

	
	var header = td.parentNode.previousSibling;
	while (header.nodeType != 1){
		header = header.previousSibling;
	}
	header = header.previousSibling;
	while (header.nodeType != 1){
		header = header.previousSibling;
	}
	//alert('get_editable_controls');
	var count = 1;
	//alert('get_editable_controls');
	var child = header.firstChild;
	while (child && child.nodeType != 1){
		child = child.nextSibling
	}
	while(child && count){
		if (child.nodeType == 1){
			if ((count < 4) || (count > 5)){
				arr.push(child);
			}
			count++;

		}
		child = child.nextSibling;
	}
	return arr;
}

function edit_post(){
	var mod_iface = document.getElementById('moderator_iface');
	var edit_button = document.getElementById('edit_button');
	var save_button = document.getElementById('save_button');
	if (mod_iface) {
		add_class(edit_button, 'hidden');
		add_class(save_button, 'hidden');
	}else{
		add_class(edit_button, 'hidden');
		del_class(save_button, 'hidden');
	}
	//may_tween = false;
	


	var arr = get_editable_controls();
	for (var i = 0 ; i < arr.length ; i++){
		var el = arr[i];
		var type = el.getAttribute('field_type');
		
		if (type){
			var str = el.innerHTML;
			var to_edit = el.getAttribute('to_edit');
			if (to_edit){
				el.innerHTML = '<span>'+ eval(to_edit+'(str)') + '</span>';
			}else{
				el.innerHTML = '<span>'+ str + '</span>';
			}
			var span = el.firstChild;
			var el_h = el_height(span);
			var el_w = el_width(span);
			
			if (type == 'text'){
				if (el_w < 300){
					el_w = 300;
				}

				if (to_edit){
					str = eval(to_edit+'(str)');
				}	
				el_h += 20;
				el.innerHTML = '<textarea class="editing" name=p'+i+' field_type="'+type+'" style="width: '+el_w+'px; height: '+ el_h+'px;"></textarea>';
				el.firstChild.value = str;
			}else if (type == 'date'){
				var args = str.split(' ');
				var month = args[0];
				var year = parseInt(args[1]);
				var curr_year = (new Date()).getUTCFullYear();
				var min_year = curr_year;
				var max_year = curr_year;
				if (year < curr_year){
					min_year = year - 2;
					max_year = curr_year + 2;
				}else{
					min_year = curr_year - 2;
					max_year = year + 2
				}
				
				var html= " \
					<select> \
						<option value=Jan>Jan</option> \
						<option value=Feb>Feb</option> \
						<option value=Mar>Mar</option> \
						<option value=Apr>Apr</option> \
						<option value=May>May</option> \
						<option value=Jun>Jun</option> \
						<option value=Jul>Jul</option> \
						<option value=Aug>Aug</option> \
						<option value=Sep>Sep</option> \
						<option value=Oct>Oct</option> \
						<option value=Nov>Nov</option> \
						<option value=Dec>Dec</option> \
					</select> \
					<select> \
				";
				for (var j = min_year; j <= max_year; j++){
					html +=  '<option value="'+ j +'">'+ j +'</option>\n';
				}
				html += '</select>';

				el.innerHTML = html;
				var month_control = el.firstChild;
				while (month_control && (month_control.nodeType != 1)){
					month_control = month_control.nextSibling;
				}
				var year_control = month_control.nextSibling;
				while(year_control && (year_control.nodeType != 1)){
					year_control = year_control.nextSibling;
				}

				month_control.value = month;
				year_control.value = year;
			}else{
				if (el_w < 10){
					el_w = 10;
				}
			
				el.innerHTML = '<input type=text name=p'+i+' class="editing" field_type="'+ type+'" style=" width: '+ el_w + 'px;">';
				if (to_edit){
					str = eval(to_edit+'(str)');
				}while (month && (month.nodeType != 1)){
					month = month.nextSibling;
				}

				el.firstChild.value = str;			
			}
		}
	}
	return void(0);
}

function get_selected_post_id(){

	if (cur_opened['data_avaible']) return cur_opened.base_tr.id.slice(5);
	else return '';

}

function price_to_string(str){
	return str.replace(/\$/g, '');
}



function save_post(){
	var controls = get_editable_controls();
	var arr = new Array();
	for (var i = 0; i < controls.length; i++){
		var el = controls[i].firstChild;
		arr.push(el);
	}

	if (check_values(arr)){
		var id  = get_selected_post_id();
		var content = 'mode=save_post';
		content += '&post_id='+ id;
		for (var i = 0; i < controls.length; i++){
			var name = controls[i].getAttribute('var_name');
			var type = controls[i].getAttribute('field_type');
			var value = null;
			if  (type == 'date'){
				var month = controls[i].firstChild;
				while (month && (month.nodeType != 1)){
					month = month.nextSibling;
				}
				var year = month.nextSibling;
				while (year && (year.nodeType != 1)){
					year = year.nextSibling;
				}

				value = month.value + ' ' + year.value;
			}else{
				value = controls[i].firstChild.value;
			}
			
			content += '&'+name+'='+escape(value);
			//alert(content);
		}
		//alert(content);
		var responce = sync_text_req('/category.php', 'POST', content);

		update_post();
	}

	return void(0);
}
function view_mode(){
	var edit_button = document.getElementById('edit_button');
	var save_button = document.getElementById('save_button');
	var mod_iface = document.getElementById('moderator_iface');
	if (mod_iface){
		add_class(edit_button, 'hidden');
		add_class(save_button, 'hidden');
	}else{
		del_class(edit_button, 'hidden');
		add_class(save_button, 'hidden');
	}

	//may_tween = true;
}

function update_post(){
	var post_id = get_selected_post_id();
	var responce = sync_text_req('/category.php?mode=update_post&post_id='+ post_id, 'GET', '');
	var data = new Object;
	eval(responce);
	
	var controls = get_editable_controls();
	for (var i = 0; i < controls.length; i++){
		var el = controls[i];
		el.innerHTML = '';
		var var_name = el.getAttribute('var_name');
		if (var_name && data[var_name]){
			el.innerHTML = data[var_name];
		}
	}

	
	view_mode();
	return void(0);
}

function el_width(span){
	//get width of text element
	  w = span.offsetWidth;
	return w;
}

function el_height(span){
	//get height of text element
	
	h = span.offsetHeight;
	return h;
}

function sort_by(column, table_id, type){
	if (!may_tween) return;
	var sel_id = get_selected_post_id();
	
	if (sel_id){
		hide_details(document.getElementById('post_'+sel_id));
		function on_sort_selected_collapsed(){
			if (type == 'price'){
				table_sort(table_id, column, 'table_sort__get_td_price');
			}else if(type == 'link'){
				table_sort(table_id, column, 'table_sort__get_td_link_text');
			}else if(type == 'date'){
				table_sort(table_id, column, 'table_sort__get_td_date');
			}else{
				table_sort(table_id, column, 'table_sort__get_td_text');
			}
		}
		setTimeout(on_sort_selected_collapsed, 500);
	}else{
		if (type == 'price'){
			table_sort(table_id, column, 'table_sort__get_td_price');
		}else if(type == 'link'){
			table_sort(table_id, column, 'table_sort__get_td_link_text');
		}else if(type == 'date'){
			table_sort(table_id, column, 'table_sort__get_td_date');
		}else{
			table_sort(table_id, column, 'table_sort__get_td_text');
		}
	}	
}

function table_sort__get_td_price(td){
	return parseInt(price_to_string(td.innerHTML));
}

function edit_if_moderator(){
	var mod_iface = document.getElementById('moderator_iface');
	if  (mod_iface){
		edit_post();
	}
}


function on_report_as_inappropriate(el){
	var post_id = get_selected_post_id();
	if (!post_id) {
		return;
	}
	var p = sync_text_req('/category.php?mode=report_as_inappropriate&post_id='+ post_id, 'GET', '');
	var parent = el.parentNode;
	var b_width = el.offsetWidth;
	var div = document.createElement('div');
	div.id = 'inappropriate_rollover';
	div.innerHTML='thank you for your feedback';
	
	parent.removeChild(el);
	parent.appendChild(div);	
	//alert(div.offsetWidth);
}

function restore_current_post(){
	var post_id = readCookie('current_post');
	if (post_id) {
		var selected_tr = document.getElementById('post_'+post_id);
		if (selected_tr) {	
			setTimeout(function(){show_details(selected_tr);}, scroll_to(selected_tr));
		}
	}
}



function on_subscribe(){
	var sub = document.getElementById('subscribtion');
	if (sub.className.indexOf('hidden') >= 0){
		t8 = new Tween(sub.style, 'height', Tween.regularEaseInOut, 1, 200, 0.5, 'px');
		eval( 	't8.onMotionChanged = function (){'+ 
			get_vieport_property_name('scroll_top')+
			' = '+ 
			get_vieport_property_name('page_height') +
			' ;}'
		);
		t8.start();
		del_class(sub, 'hidden');
		return 500;
	}else{
		t8 = new Tween(sub.style, 'height', Tween.regularEaseInOut, 200, 1, 0.5, 'px');
		t8.start();
		setTimeout(function(){ add_class(sub, 'hidden');}, 500);
		return 505;
	}
}

function hide_special(){
	var d1 = hide_subsribe();
	var d2 = hide_bookmark();
	var d3 = hide_heads_up_login();

	return 	(d1 > d2)
		? ((d1 > d3)? d1 : d3)
		: ((d2 > d3)? d2 : d3) ;
}




function fill_email_with_registred(el){
	var p = sync_text_req('/category.php?mode=get_registered_email', 'GET', '');
	if (p){
		var form = el.parentNode.getElementsByTagName('form')[0];
		form.elements['email'].value = p;
	}
}

function append_author_notification(el, url){
	var email = el.form.elements['email'];
	var hours = el.form.elements['hours_to_timeout'];
	insertAtCaret(email, '\nI have unlocked your post so that you can edit it for the next '+hours.value+' hours.\n' + url);
	//email.value += '\nI have unlocked your post so that you can edit it for the next '+hours.value+' hours.\n' + url;
	email.focus();
}


function hide_suggest_box(){
	//alert('hide_suggest_box');
	var div =  document.getElementById('suggest_box');
	if (div){
		div.parentNode.removeChild(div);
	}
}

function display_suggest_box(el, html){
	var coords = get_absolute_offset(el);
	var div = document.createElement('div');
	div.id = 'suggest_box';
	div.style.position = 'absolute';
	div.style.zIndex = '3';
	div.style.top = coords.y + el. offsetHeight;
	div.style.left = coords.x;
	div.style.width = el.offsetWidth + 'px';

	div.innerHTML = html;
	document.body.appendChild(div);
	window.suggest_category_el = el;
	//alert(html);
}

function set_suggest_url(url){
	if (window.suggest_category_el != undefined){
		window.suggest_category_el.value = url;
	}
}


function display_category_suggest(el, data){
	var html = '';
	for (d in data) {
		html += '<a href="javascript:void(0)" onclick='+"'"+'set_suggest_url("'+data[d]['url']+'"); return false;'+"'"+' >' + data[d]['name'] + '</a><br>';
	}

	display_suggest_box(el, html);
}

function display_category_suggest_error(el, msg){
	display_suggest_box(el, '<b>' + msg + '</b>');
}
function append_basic_template_to_email( user_name, moderator_name, category_name){
	var email = document.getElementById('email');

	var first_part = 'Greetings, '+user_name+'!\n'
			+ 'Thank you for sharing your experiences at WisePrice! \n\n'
			+ 'We really appreciate your post' +((category_name)? ' about '+category_name : '')+', and we were hoping that you would be able to '
	var second_part = '\n\n\n'
			+ 'Thank you so much!\n'
			+ 'If you have questions, feel free to respond to moderator@wiseprice.com\n'
			+ 'Your friendly WisePrice Moderator'
	if (moderator_name){
			second_part += ',\n'+moderator_name
	}
	insertAtCaret(email, first_part + second_part);
	var off = email.value.indexOf(second_part);
	setSelRange(email, off, off)
	email.focus();
}
function append_recomended_template_to_email(){
	var email = document.getElementById('email');
	var message = "Greetings! \n"
		+ "Thanks for doing a great job with our HIT! Your post was above average quality and I've selected a small snippet to add to our recommended reading links. As a thank you, I have added a 50 cent bonus to your compensation. Thanks again, and we hope you write more for us! \n"
		+ "Best, \n"
		+ "Lindsay \n"
		+ "Conjecture Corp. \n"
		+ 'lindsay@conjecture.com \n'
	;
	insertAtCaret(email, message);
	email.focus();
}

function append_reject_template_to_email(username){
	var email = document.getElementById('email');

	var first_part = 'Greetings, '+username+'! \n\n'
		+ " Thank you for your work. Unfortunately, we have had to reject this particular HIT due to it being in the wrong category. Our preview page has the following text: \"Please look at the categories carefully before choosing what you will write about. We will be forced to reject posts that are submitted into the wrong category.\" \n" 
		+ " You submitted this post to  "
	;
	var second_part = ", although it was about . While we have a category specifically for , it is full and we are no longer paying for these posts. \n\n"
		+ " You are a valuable contributor to our project, and I hope that you continue to accept our HITs. \n\n"
		+ 'Thanks for your work, and feel free to try again!\n'
		+ 'Best, \n'
		+ 'Lindsay \n'
		+ 'lindsay@conjecture.com \n'
	;
	insertAtCaret(email, first_part + second_part);
	var off = email.value.indexOf(second_part);
	setSelRange(email, off, off)
	email.focus();
}
function append_block_template_to_email(){
	var email = document.getElementById('email');

	var first_part = 'Greetings! \n'
		+ "Thank you for taking the time to accept and submit your work for our HIT. Unfortunately, we have found that your work has been of consistently low quality. \n"
		+ "For this reason, we are blocking your ability to accept HITs like this one from us in the future. If you have any questions or concerns, please feel free to contact me directly. \n"
		+ "Lindsay \n"
		+ "lindsay@conjecture.com \n"
	insertAtCaret(email, first_part );
	//var off = email.value.indexOf(second_part);
	//setSelRange(email, off, off)
	email.focus();
}


