// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/*
* function addTactic
* Used to add the tactic to the list
*/
function switchTacticOptions()
{
	var options = '';
	pos = $("#category_select").val();
	if(!parseInt(pos)) return
	for(i = 0; i < tacticOptions[pos].length; i++)
	{
		options += '<option value="' + tacticOptions[pos][i][0] + '">' + tacticOptions[pos][i][1] + '</option>' + "\n";
	}
	$('#tactic_select').html(options).show();
}

var doprompt = true;

function confirmExit()
{
	if (!doprompt) return;
	return "If you have made any changes without clicking the Update button your changes will be not be saved"
}

$(document).ready( function(){
	$('a.tooltip').cluetip({local: true, showTitle: false, cursor: 'help'});
});

// $ command for rounded boxes
// Originally inspired by http://15daysofjquery.com/wrap-it-up-pretty-corners/13/

$(document).ready(function(){ $("div.roundbox-start") .wrap(
	'<div class="rnd-start">'+
     '<div class="bd">'+
     '<div class="c">'+
     '<div class="s">'+
     '</div>'+
     '</div>'+
     '</div>'+
     '</div>'
	);

	$('div.rnd-start').prepend('<div class="hd">'+
	        '<div class="c"></div>'+
	        '</div>')
});


$(document).ready(function(){ $("div.roundbox") .wrap(
	'<div class="rnd">'+
     '<div class="bd">'+
     '<div class="c">'+
     '<div class="s">'+
     '</div>'+
     '</div>'+
     '</div>'+
     '</div>'
	);

	$('div.rnd').prepend('<div class="hd">'+
	        '<div class="c"></div>'+
	        '</div>')
	.append('<div class="ft">'+
	        '<div class="c"></div>'+
	        '</div>');

});

$(document).ready(function(){ $("div.roundbox-segment") .wrap(
	'<div class="rnd-segment">'+
     '<div class="bd">'+
     '<div class="c">'+
     '<div class="s">'+
     '</div>'+
     '</div>'+
     '</div>'+
     '</div>'
	);

	$('div.rnd-segment').prepend('<div class="hd">'+
	        '<div class="c"></div>'+
	        '</div>')

});


$(document).ready(function(){
	$("div.roundbox-segment-stop") .wrap(
	'<div class="rnd-segment-stop">'+
     '<div class="bd">'+
     '<div class="c">'+
     '<div class="s">'+
     '</div>'+
     '</div>'+
     '</div>'+
     '</div>'
	);

	$('div.rnd-segment-stop').prepend('<div class="hd">'+
	        '<div class="c"></div>'+
	        '</div>')
	.append('<div class="ft">'+
	        '<div class="c"></div>'+
	        '</div>');

	$('.textedit-inactive').hover(
		function(){
				$(this).css({
					"border": "inset 1px",
					"padding": "2px",
					"cursor": "pointer"
					});
			},
			function () {
				$(this).css({
					"border": "none",
					"padding" : "3px"
				});
			}
	)

  $(".cut-text").truncate( 300, {
      chars: /\s/,
      trail: [ " <a href='#' class='truncate_show'>Read More... </a>", " ...<a href='#' class='truncate_hide'>Read Less</a> " ]
  });

});


if( document.images )
{
<!--Small button-->
	btn0_off 	= new Image(180,28);
  btn1_off 	= new Image(180,28);
  btn2_off 	= new Image(180,28);
  btn3_off 	= new Image(180,28);
  btn4_off 	= new Image(180,28);
  btn5_off 	= new Image(180,28);
  btn6_off 	= new Image(180,28);

	btn0_on 	= new Image(180,28);
  btn1_on 	= new Image(180,28);
  btn2_on 	= new Image(180,28);
  btn3_on 	= new Image(180,28);
  btn4_on 	= new Image(180,28);
  btn5_on 	= new Image(180,28);
  btn6_on 	= new Image(180,28);

  btn0_off.src 	= "/images/top_btn_0_off.gif";
  btn1_off.src 	= "/images/top_btn_1_off.gif";
  btn2_off.src 	= "/images/top_btn_2_off.gif";
  btn3_off.src 	= "/images/top_btn_3_off.gif";
  btn4_off.src 	= "/images/top_btn_4_off.gif";
  btn5_off.src 	= "/images/top_btn_5_off.gif";
  btn6_off.src 	= "/images/top_btn_6_off.gif";

  btn0_on.src 	= "/images/top_btn_0_on.gif";
  btn1_on.src 	= "/images/top_btn_1_on.gif";
  btn2_on.src 	= "/images/top_btn_2_on.gif";
  btn3_on.src 	= "/images/top_btn_3_on.gif";
  btn4_on.src 	= "/images/top_btn_4_on.gif";
  btn5_on.src 	= "/images/top_btn_5_on.gif";
  btn6_on.src 	= "/images/top_btn_6_on.gif";

}

/* This is used to add users for the admin area */
function addNewUser(formName, login, email, pass, passconfirm, is_admin, id)
{
	form = document.forms[formName];
	var newId = Math.round(Math.random()*1000)
	newuser = [login, email, pass, passconfirm, is_admin];
	users[newId] = newuser;
	form.users.value = joinEditUsers();

	// Draw on page
	var out = '';
	out += '<div id="user-' + newId + '" class="add-user">'
	out += '<div>' + login + '</div>'
	out += 	'<div>' + email + '</div>'
	out += 	'<div>' + is_admin + '</div>'
	out += '<div>'
	if(id != undefined) {
		out += '<a href="/users/' + id + '/edit">Edit User</a> or '
	}
	out += '<a href="#" onclick="removeUser(\'' + formName + '\',' + newId + '); return false;">Remove</a>'
	out += '</div>'
	out += '<br clear="all" />'
	out += '</div>'

	$("#add-user-list").append(out);

	form.new_user_login.value = '';
	form.new_user_email.value = '';
	form.new_user_password.value = '';
	form.new_user_password_confirmation.value = '';
	form.new_user_is_admin.checked = false;
}

// Used to add a selected tactic/category to a program for editing
function addProgramTactic(catId, catText, tacticId, tacticText)
{
    var isCat = false
    if(tacticId.charAt(0) == 'c') {
        var el = $("#selected_categories")
        if((';'+el.val()).indexOf(';' + catId + ";") != -1) return false
        el.val(el.val() + catId + ";")
        isCat = true
    } else {
        var el = $("#selected_tactics")
        if((';'+el.val()).indexOf(';' + tacticId + ";") != -1) return false
        el.val(el.val() + tacticId + ";")
    }
    var rand = Math.round(Math.random()*1000)
    html = '<div id="t' + rand + '">'
    html += '<a href="#" onclick="removeProgramTactic(\'t' + rand + '\', \'' + tacticId  +'\'); return false;">[remove]</a> '
    html += isCat ? catText + " (category only)" : catText + " > " + tacticText
    html += '</div>'
    $("#selected-category-list").append(html)

}

function clearFormErrors(id)
{
	form = $("#" + id);
	form.find(".form-error").text("");
}


function chkVer(imagename,objectsrc)
{
	var n=navigator.appName
	var v=parseInt(navigator.appVersion)
	var browsok=((n=="Netscape")&&(v>=3))
	var browsok2=((n=="Microsoft Internet Explorer")&&(v>=4))
	if ((browsok)||(browsok2))
		document.images[imagename].src=eval(objectsrc+".src")
}


/*
* function exceeded_limit(string field)
* Used to validate whether the user has selected more checkboxes
* than allowed
*/
function exceeded_checkbox_limit(form, field)
{
	var max = 10
	var cx = 0
	switch(field) {
		case 'tactic':
			var formname = 'program_tactic[]'
			var text = 'program tactics'
			break;
		default:
			var formname = 'category[]'
			var text = 'program categories'
			break;
	}
	for(var i=0;i<form.length;i++)
	{
		if(form.elements[i].type=="checkbox" && form.elements[i].name == formname && form.elements[i].checked == true) {
			cx++
			if(cx > max) {
				form.elements[i].checked = false
				alert('You may only select up to 10 ' + text)
				return;
			}
		}
	}
}

/*
* function hide_and_replace(string hide, string replace)
* Replace a given DOM element with id hide with replace
* hide		ID (include #) of element to replace
* replace 	HTML replacement text
*/
function fade_and_replace(hide, replace)
{
	$("#" + hide).before(replace)
	$("#" + hide).remove();
}

function fix_width()
{
	$('#wrapper').css('width', window.innerWidth);
}


function joinEditUsers()
{
	var str = '';
	var keys = new Array();

	// Associative array, get the keys for the users first
	for(i in users){
		keys.push(i);
	}
	// Now join the stringa
	for(var i=0; i < keys.length; i++)
	{
		str += users[keys[i]].join(";") + "|"
	}
	return str
}


/*
* function makeEditTextarea(string id [, bool convert])
* @param	convert		Change field from input text type to textarea
*/
function makeEditTextarea(id)
{
	var obj = $("#" + id);

	// Quit if already open
	if($("#" + id + '_actions').css('display')) return;

	// Replace BR tags first
	var regexp = /<br\s?\/?>/gi;
	var text = obj.html().replace(regexp, "");
	text = $.trim(text);

	// Strip HTML
	regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
	text = text.replace(regexp, "");

	var replace = '<textarea class="textedit-active" id="' + id + '" name="notes">' + text + '</textarea>';
	replace += '<div id="' + id + '_actions"><br /><input type="submit" value="Save Changes" /> &nbsp;';
	replace += '<input type="button" value="Cancel" onclick="revertEditTextarea(\'' + id + '\', true)" /></div>';
	obj.replaceWith(replace);
}

function programCompareTab(id)
{
	$("#compare-tabs div.compare-tab-current").removeClass().addClass("compare-tab")
	$('#program_' + id + '_tab').addClass("compare-tab-current")
	$("#compare-block").children().hide()
	$("#program_" + id + "_details").show();
}


/*
 * function removeProgramTactic
 * use this to remove a tactic/category in Program#edit
 * @param   divId       ID of DOM element  to remove
 * @param   tacticId    string containing tactic/category ID
 */
function removeProgramTactic(divId, tacticId)
{
   if(tacticId.charAt(0) == 'c') {
       var el = $("#selected_categories")
       var needle = tacticId.slice(1)
   } else {
       var el = $("#selected_tactics")
       var needle = tacticId
   }
   var regex = new RegExp("(;|^)" + needle + ";", "gi")
   el.val(el.val().replace(regex, "$1"))
   $("#" + divId).remove()
}

/*
* function removeUser(string, string, int)
* removes user from list in the new user / edit user admin management area
* Only affects JS variables
* @param	formName
* @param	id				DIV id of object to hide
*/

function removeUser(formName, id)
{
	var form = document.forms[formName];
	var agree = confirm("Really delete this user?")
	if(agree == false) return false;

	// loop through keys and remove slice
	var temp = new Array();
	for(key in users) {
		if(key != id) {
			temp[key] = users[key];
		}
	}
	users = temp;
	form.users.value = joinEditUsers();

	// Remove from DOM
	$("#user-" + id).fadeOut("fast", function(){
		$(this).remove()
	});
	form.submit();
}

function revertEditTextarea(id, cancel)
{
	var obj = $("#" + id);

	// Get current text
	var text = (cancel == true) ? obj.html() : obj.val();
	var replace = '<div onclick="makeEditTextarea(this.id, true)" id="' + id + '" class="textedit-inactive" title="Click to Edit">';

	// Replace newlines with <br />
	var regexp = /\n|\r/gi;
	text = text.replace(regexp, "<br />");
	replace += text;
	replace += '</div>';
	obj.replaceWith(replace)

	// Nix actions
	$("#" + id + '_actions').remove();
}

/*
* function setRating(string id, int rating)
* Use this to set a rating
*/
function setRating(id, rating)
{
	ratings = ["zerostar", "onestar", "twostar", "threestar", "fourstar", "fivestar"];
	$("#" + id).removeClass().addClass("rating " + ratings[rating])
	$("#review_"+ id).val(rating)
	return
}

/*
* function swap_visibility(string show, string hide)
* Uses jQuery toggle() function to hide one, show two
* @params						show			ID of object
* @param						hide			ID of object
*/
function swap_visibility(show, hide)
{
	$("#" + show).toggle();
	$("#" + hide).toggle();
}
function toggleDetails(id, clicked)
{
	var oDiv = $("#" + id);

	if(oDiv.css('display') == 'none') {
		clicked.innerHTML = '[ Hide Details ]';
		oDiv.slideDown();
	} else {
		clicked.innerHTML = '[ Show Details ] ';
		oDiv.slideUp();
	}
}

/*
* Used as a callback function for jQuery. jQuery improperly replaces
* HTML code before a given function has run, this will set a timeout
* and then run the proper code
*/

function wait_for_replace(hide, replace)
{
	setTimeout("fade_and_replace('" + hide + "', '" + replace +"')", 500)

}


/*
*  Table Sorter function, originally developed by Michael and found at
* http://www.leigeber.com/2008/11/javascript-table-sorter/
* Code was extracted from script.js

* function sorter(string id[, int column])
* @param	id	the ID of the table element to apply sorting to
* @param	column	index of the column for initial sorting
*/
var table=function(){
	function sorter(n){
		this.n=n; this.t; this.b; this.r; this.d; this.p; this.w; this.a=[]; this.l=0
	}
	sorter.prototype.init=function(t,f){
		this.t=document.getElementById(t);
		this.b=this.t.getElementsByTagName('tbody')[0];
		this.r=this.b.rows; var l=this.r.length;
		for(var i=0;i<l;i++){
			if(i==0){
				var c=this.r[i].cells; this.w=c.length;
				for(var x=0;x<this.w;x++){
					if(c[x].className!='nosort'){
						c[x].className='head';
						c[x].onclick=new Function(this.n+'.work(this.cellIndex)')
					}
				}
			}else{
				this.a[i-1]={}; this.l++;
			}
		}
		if(f!=null){
			var a=new Function(this.n+'.work('+f+')'); a()
		}
	}
	sorter.prototype.work=function(y){
		this.b=this.t.getElementsByTagName('tbody')[0]; this.r=this.b.rows;
		var x=this.r[0].cells[y],i;
		for(i=0;i<this.l;i++){
			this.a[i].o=i+1; var v=this.r[i+1].cells[y].firstChild;
			this.a[i].value=(v!=null)?v.nodeValue:''
		}
		for(i=0;i<this.w;i++){
			var c=this.r[0].cells[i];
			if(c.className!='nosort'){c.className='head'}
		}
		if(this.p==y){
			this.a.reverse(); x.className=(this.d)?'asc':'desc';
			this.d=(this.d)?false:true
		}else{
			this.p=y; this.a.sort(compare); x.className='asc'; this.d=false
		}
		var n=document.createElement('tbody');
		n.appendChild(this.r[0]);
		for(i=0;i<this.l;i++){
			var r=this.r[this.a[i].o-1].cloneNode(true);
			n.appendChild(r); r.className=(i%2==0)?'even':'odd'
		}
		this.t.replaceChild(n,this.b)
	}
	function compare(f,c){
		f=f.value,c=c.value;
		var i=parseFloat(f.replace(/(\$|\,)/g,'')),n=parseFloat(c.replace(/(\$|\,)/g,''));
		if(!isNaN(i)&&!isNaN(n)){f=i,c=n}
		return (f>c?1:(f<c?-1:0))
	}
	return{sorter:sorter}
}();


-->
