// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
Object.extend(Number.prototype, {
	px: function() {
		return Math.round(this).toString() + 'px';
	}
});
Object.extend(Number.prototype, {
	digits: function(num) {
		var to_s = Math.round(this).toString();
		while (to_s.length < num) {
			to_s = "0" + to_s;
		}
		return to_s;
	}
});
Object.extend(Math, {
	negate: function(num) {
		return num * -1;
	}
});
Object.extend(String.prototype, {
	capitalizeFirst: function() {
		return this.charAt(0).toUpperCase() + this.substring(1);
	}
});

function radio_toggle(id, value) { parseInt(value) == 1 ? $(id).show() : $(id).hide(); }

var idToExistingRatings = new Array();

function rating_slider(type, id, rating) {
	width_multiplier = 10;
	idToExistingRatings[id + ""] = rating;
	$('fill_' + type + '_' + id).style.width = (rating*width_multiplier).px();
	new Control.Slider('handle_' + type + '_' + id, 'track_' + type + '_' + id, {
		range:$R(0, 10), sliderValue:rating,
		onSlide: function(value){
			value = Math.round(value);
			$('current_value_' + type + '_' + id).innerHTML = value > 0 ? value : 'unrated';
			$('fill_' + type + '_' + id).style.width = (value*width_multiplier).px();
		}, 
		onChange:function(value) {
			if (value > 0) {
				new Ajax.Request('/ratings', {
					method: 'post',
					asynchronous:true,
					evalScripts:true,
					parameters: {
						'rating[rateable_type]': type.capitalizeFirst(),
						'rating[rateable_id]': id,
						'rating[value]': Math.round(value)
					}
				});
			}
		}
	});
};


function survey_slider(answer_id, rating) {
	type = 'answer'
	width_multiplier = 10;
	
	$('fill_' + type + '_' + answer_id).style.width = (rating*width_multiplier).px();
	new Control.Slider('handle_' + type + '_' + answer_id, 'track_' + type + '_' + answer_id, {
		range:$R(0, 10), sliderValue:rating,
		onSlide: function(value){
			value = Math.round(value);
			$('current_value_' + type + '_' + answer_id).innerHTML = value > 0 ? value : 'unrated';
			$('fill_' + type + '_' + answer_id).style.width = (value*width_multiplier).px();
		}, 
		onChange:function(value) {
			if (value > 0) {
				document.getElementById('answer_ids[' + answer_id + ']').value=Math.round(value);
			}
		}
	});
}

/** WATCHING */

toggle_watch = function(event) {
	event.stopPropagation();
	event.preventDefault();
	var a = $(this); // $('watch_' + type + '_' + id);
	var id_params = a.identify().split('_');
	var type = id_params[1].capitalizeFirst();
	var id = id_params[2];
	var url = '/watches';
	var request_params = {
		asynchronous:true,
		evalScripts:true,
		method:'post',
		parameters: {
			'watch[watchable_type]': type,
			'watch[watchable_id]': id
			//, authenticity_token':authenticity_token
		},
		onSuccess: function(transport) {
			a.addClassName('watched').update('watched');
			a.href += transport.responseText;
		}
	}
	if (a.hasClassName('watched')) {
		url += ('/'+ a.hash.split('#')[1]);
		request_params.parameters['_method'] = 'delete';
		request_params.onSuccess = function(transport) {
			a.removeClassName('watched').update('watch');
			a.href = a.href.split('#')[0]+'#';
		}
	}
	new Ajax.Request(url, request_params);
}

function activateWatchLinks() {
	$$('a.watch').each(function(a) {
		Event.observe(a, 'click', toggle_watch);
	});
}

confirm_flag = function(select, span) {
	if (select.value != '' && confirm('Are you sure you want to flag this as '+select.value+'?')) {
		select.form.onsubmit();
	} else {
		$(span).hide();
		select.selectedIndex = 0;
	}
}
function activateNavDrops() {
	$$('#navigation li a.arrow').each(function(a) { Event.observe(a, 'click', showDropDown); });
}
function hideDropDowns() {
	$$('#navigation li a.arrow').each(function(a) { a.removeClassName('greenDown'); });
	$$('#navigation li ul').each(function(s) { s.hide(); });
}
function showDropDown(event) {
	event.stopPropagation();
	event.preventDefault();
	var a = $(this); // $('watch_' + type + '_' + id);
	var dropdown = a.next('ul');
	var was_visible = dropdown.visible();
	hideDropDowns();
	if(was_visible) {
		dropdown.hide();
		a.removeClassName('greenDown');
	} else {
		dropdown.show();
		a.addClassName('greenDown');
	}
}
function activateTabs() {
	for (var i = 0; i < arguments.length; i++) {
		$$(arguments[i]).each(function(a) { Event.observe(a, 'click', showTab); })
	}
}
function showTab(event) {
	var link = $(this);
	link.siblings().each(function(a) { $(a.hash.split('#')[1]).hide(); a.removeClassName('viewLinkCurrent'); });
	link.addClassName('viewLinkCurrent');
	$(link.hash.split('#')[1]).show();
	event.stopPropagation();
	event.preventDefault();
}

function showAndHideSiblingsOf(id) {
	showme = $(id); showme.show();
	showme.siblings().each(function(a) { $(a).hide(); });
}


/*
function reply_to_comment(id, authenticity_token) {
	$$('.comment_reply_form').invoke('remove');
	new Ajax.Updater('comment_10_reply', '/comments/10/replies/new', {
		asynchronous:true, evalScripts:true, insertion:Insertion.Bottom, method:'get', parameters:'authenticity_token=' + encodeURIComponent(authenticity_token)
	});
	return false;
}
function toggle_comment_replies(id, authenticity_token) {
	new Ajax.Updater('comment_10_replies', '/comments/10/replies', {
		asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(authenticity_token)
	});
	return false;
	// $(this).up('.comment_replies').update("\u003Ca href=\"#\" onclick=\"new Ajax.Updater('comment_10_replies', '/comments/10/replies', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent('9bef463d1a4f2c0a706f1ce6579e67484c81de10')}); return false;\"\u003E+ View 3 replies to this comment\u003C/a\u003E");
	// 	return false;
}
*/

//http://blog.stevenlevithan.com/archives/faster-than-innerhtml
function replaceHtml(el, html) {
	var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
	/*@cc_on // Pure innerHTML is slightly faster in IE
	oldEl.innerHTML = html;
	return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

Sortable.id_array = function(element) {
	element = $(element);
	var options = Object.extend(Sortable.options(element), arguments[1] || {});
	var name = encodeURIComponent(
		(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
	return Sortable.sequence(element, arguments[1]).map( function(item) {
		return encodeURIComponent(item);
	}).join(',');
}

liveNotice = function(html) {
	var notice = 'flashnotice';
	if ($('extraLinks')) {
		new Insertion.After('extraLinks', '<div class="'+notice+'"><span style="float: right; margin-top: -3px"><img src="/stylesheets/skins/default/images/closeIcon.gif" onclick="$(this.parentNode.parentNode.hide());" /></span>'+html+'</div>');
		var fade_args = { duration: 0.4, queue: { position:'end', scope: notice } };
		notice_object = $$('.'+notice).last();
		Effect.Appear(notice_object, fade_args);
		if(arguments[1] != true) {
			var to = setTimeout(function(){
				Effect.Fade(notice_object, fade_args);
				notice_object.remove();
				clearTimeout(to);
			}, 4000);
		}
	} else {
		alert('extraLinks div not present');
	}
}

function initOverLabels () {
	if (!document.getElementById) return;			

	var labels, id, field;

	// Set focus and blur handlers to hide and show labels with 'overlabel' class names.
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {

		if (labels[i].className == 'overlabel') {

			// Skip labels that do not have a named association with another field.
			id = labels[i].htmlFor || labels[i].getAttribute('for');
			if (!id || !(field = document.getElementById(id))) { continue; } 

			// Change the applied class to hover the label over the form field.
			labels[i].className = 'overlabel-apply';

			// Hide any fields having an initial value.
			if (field.value !== '') {
				hideLabel(field.getAttribute('id'), true);
			}

			// Set handlers to show and hide labels.
			field.onfocus = function () {
				hideLabel(this.getAttribute('id'), true);
			};
			field.onblur = function () {
				if (this.value === '') {
					hideLabel(this.getAttribute('id'), false);
				}
			};

			// Handle clicks to label elements (for Safari).
			labels[i].onclick = function () {
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id))) {
					field.focus();
				}
			};

		}
	}
};
function phaseDetails(a, element) {
	var closed = 'phasearrow_closed';
	var open = 'phasearrow';
	a.className = (a.className == closed) ? open : closed;
	$(element).toggle();
}
function hideLabel (field_id, hide) {
	var field_for;
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		field_for = labels[i].htmlFor || labels[i].getAttribute('for');
		if (field_for == field_id) {
			labels[i].style.textIndent = (hide) ? '-10000px' : '0px';
			return true;
		}
	}
}
function classifyTextInputs() {
	inputs = document.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		var type = inputs[i].getAttribute('type');
		if (type == 'text') {
			$(inputs[i]).addClassName('');
		} else if (type == 'hidden') {
			$(inputs[i]).addClassName('hidden');
		}
	}
}
function loadFileUploadSWF() {
	if (document.getElementById('file-uploader')) {
		var auth_token = $('auth-token').innerHTML;
		var _illuminator2_session = escape(getSessionCookie());
		var success = swfobject.embedSWF("/swf/UploadExample.swf?auth_token=" + auth_token
			+ "&_klustr_session=" + _illuminator2_session
			, "file-uploader", "800", "240", "8", "/swf/expressInstall.swf");
	}
}
function displayAndValidateMinimumAdBuy(field, display_id, total_reward_id, handling_fee_id, total_id) {
	var dollars = parseInt(field.value);
	if((field.value != '' && dollars < 5) || isNaN(dollars)) {
		alert('you must enter a valid amount greater than or equal to $5');
	} else {
		var total_ad_dollars   = parseInt(field.value);
		var total_reward       = parseInt($(total_reward_id).innerHTML);
		var total_handling_fee = parseFloat($(handling_fee_id).innerHTML);
		var total_price        = total_ad_dollars + total_reward + total_handling_fee;
		$(display_id).update(total_ad_dollars*100);
		$(total_id).update(total_price.toFixed(2));
	}
}
function toggleComment(a, id) {
	// alert(id);
	replies_div = $('comment_'+id+'_replies');
	if (replies_div.childElements.length == 0 && replies_div.innerHTML.length < 1) {
		new Ajax.Updater('comment_'+id+'_replies', '/comments/'+id+'/replies', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(getAuthToken())});
	} else {
		replies_div.toggle();
	}
}
function getSessionCookie() {
	return  $('_illuminator2_session').innerHTML;
}
function loadVid(path, div) {
	var so = new SWFObject("http://www.klusterfck.com/videos/main.swf", "sotester", "764", "350", "9", "#333333");
	so.addVariable("theVid", path);
	// so.addParam("scale", "noscale");
	return so.write(div);
}
function getAuthToken() {
	if ($('auth_token')) {
		return $('auth_token').innerHTML
	}
}

Event.observe(window, 'load', function() {
	setTimeout(initOverLabels, 50);
	classifyTextInputs();
	activateWatchLinks();
	activateNavDrops();
	activateTabs('div.tabbed_links a');
	loadFileUploadSWF();
	Event.observe(window, 'click', hideDropDowns);
});
