var lastDialogRequest = null;
PlanShortcuts = Class.create();
PlanShortcuts.prototype  = {
    initialize: function(plan_id, ministry_id) {
        Event.observe(document, 'keypress', this.onKeyPress.bindAsEventListener(this));
        this.plan_id = plan_id;
        this.ministry_id = ministry_id;
    },

	onKeyPress: function(event) { 
		 if (event.keyCode == Event.KEY_ESC) {
		   if(lastDialogRequest) { lastDialogRequest.transport.abort(); }
	       Dialog.close();
			return;
		 }
		
		 // Apparently we still see Firefox shortcuts like control-T for a new tab -
		 // checking for modifiers lets us ignore those
		 if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
		 return false;
		 }
		
		 // We also don't want to interfere with regular user typing
		 if (event.target && event.target.nodeName) {
		 var targetNodeName = event.target.nodeName.toLowerCase();
		 if (targetNodeName == "textarea" ||
		 targetNodeName == "select" ||
		 (targetNodeName == "input" && event.target.type &&
		 event.target.type.toLowerCase() == "search") ||
		 (targetNodeName == "input" && event.target.type &&
		 event.target.type.toLowerCase() == "password") ||
		 (targetNodeName == "input" && event.target.type &&
		 event.target.type.toLowerCase() == "text")) {
		 return false;
		 }
		 }
		
		 Event.stop(event);
		if (window.event) {
			var key = window.event.keyCode;
		} else {
			var key = event.charCode;
		}http://www.planningcenteronline.com/plans/442394/plan_items/new
		 switch(String.fromCharCode(key).toLowerCase()) {
		 	case 'i': Dialog.open('/plans/' + this.plan_id + '/plan_items/new', 700); break;
		 	case 's': Dialog.open('/plans/' + this.plan_id + '/plan_items/new?add=song', 700); break;
		 	case 'm': Dialog.open('/plans/' + this.plan_id + '/plan_items/new?add=media', 700); break;
		 	case 'h': Dialog.open('/plans/' + this.plan_id + '/plan_items/new?plan_item%5Btype%5D=PlanHeader', 700); break;
		 	case 'n': Dialog.open('/plans/' + this.plan_id + '/plan_notes/new/'); break;
		 	case 'p': Dialog.open('/planning_center/ministry/' + this.ministry_id + '/plan/' + this.plan_id + '/person/search'); break;
		 	case 't': Dialog.open('/plans/' + this.plan_id + '/times/new'); break;
		 	case 'e': Dialog.open('/planning_center/plan_emailers?plan_ids=' + this.plan_id, 700); break;
		 }		
		
	}
};



var PlanItem = {
    Recolor: function() {
        color_item = false;
        header_before = false;
        $$('#plan_items li').each(function(item) {
            if(item.hasClassName("plan_header")) {
                header_before = true;
            }
            else if (header_before) {
                header_before = false;
                color_item = true;
                item.style.backgroundColor = "White";
            }
            else if(color_item) {
                item.style.backgroundColor = "#EEE";
                color_item = false;
            }
            else { 
                color_item = true; 
                item.style.backgroundColor = "White";
            }
        }
        );
    }
}

var Plan = {
    ShowPersonCategory: function(category_id)
    {
        setCookie("category_" + category_id + "_expanded","True", 100, "/");        
        Element.hide('people_compressed_' + category_id);
        Element.show('people_expanded_' + category_id);
        new Effect.BlindDown('people_list_' + category_id, {duration:0.5});
    },
    
    HidePersonCategory: function(category_id)
    {
        deleteCookie("category_" + category_id + "_expanded", "/");        
        Element.show('people_compressed_' + category_id);
        Element.hide('people_expanded_' + category_id);
        new Effect.BlindUp('people_list_' + category_id, {duration:0.5});
    }
}

var SectionBlinder = {
    Show: function(id)
    {
        setCookie("section_blinder_" + id,"true", 100, "/");        
        Element.hide(id + '_compressed');
        Element.show(id + '_expanded');
        new Effect.BlindDown(id, {duration:0.5});
    },
    
    Hide: function(id)
    {
        setCookie("section_blinder_" + id,"false", 100, "/");        
        Element.show(id + '_compressed');
        Element.hide(id + '_expanded');
        new Effect.BlindUp(id, {duration:0.5});
    }
	
}


var Hoverer = {
    BeginHover: function(id, element_class, effect)  {
            if(element_class == null)
                element_class = 'hover';
           
			elements_to_show = $$('#' + id + ' .' + element_class);
			elements_to_hide = $$('#' + id + ' .no_' + element_class);
			$(id).addClassName('hovering')
			if(effect == null) {
			     for (i=0;element=elements_to_show[i];i++){ Element.show(element); }
			     for (i=0;element=elements_to_hide[i];i++){ Element.hide(element); }
			} else {
			     for (i=0;element=elements_to_show[i];i++){ new Effect.SlideDown(element, {duration:0.25, queue:'end'}); }
			     for (i=0;element=elements_to_hide[i];i++){ new Effect.SlideUp(element, {duration:0.25, queue:'end'}); }			
			}
    },
    EndHover: function(id, element_class, effect) {
            if(element_class == null)
                element_class = 'hover';
           
			$(id).removeClassName('hovering')
			elements_to_hide = $$('#' + id + ' .' + element_class);
			elements_to_show = $$('#' + id + ' .no_' + element_class);
			if(effect == null) {
			     for (i=0;element=elements_to_show[i];i++){ Element.show(element); }
			     for (i=0;element=elements_to_hide[i];i++){ Element.hide(element); }
			} else {
			     for (i=0;element=elements_to_show[i];i++){ new Effect.SlideDown(element, {duration:0.25, queue:'end'}); }
			     for (i=0;element=elements_to_hide[i];i++){ new Effect.SlideUp(element, {duration:0.25, queue:'end'}); }			
			}
    }
}

var WindowUtilities = {
 	getPageScroll :function() {
		var yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
		}

		arrayPageScroll = new Array('',yScroll) 
		return arrayPageScroll;
	},

	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org
	// Edit for Firefox by pHaez
	getPageSize: function(){
		var xScroll, yScroll;
	
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
	
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}

		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}
}


// Extension to Ajax allowing for classes of requests of which only one (the latest) is ever active at a time
// - stops queues of now-redundant requests building up / allows you to supercede one request with another easily.

// just pass in onlyLatestOfClass: 'classname' in the options of the request

Ajax.currentRequests = {};

Ajax.Responders.register({
  onCreate: function(request) {
    if (request.options.onlyLatestOfClass && Ajax.currentRequests[request.options.onlyLatestOfClass]) {
            // if a request of this class is already in progress, attempt to abort it before launching this new request
           try { Ajax.currentRequests[request.options.onlyLatestOfClass].transport.abort(); } catch(e) {}
        }
        // keep note of this request object so we can cancel it if superceded
        Ajax.currentRequests[request.options.onlyLatestOfClass] = request;
  },
    onComplete: function(request) {
        if (request.options.onlyLatestOfClass) {
            // remove the request from our cache once completed so it can be garbage collected
             Ajax.currentRequests[request.options.onlyLatestOfClass] = null;
        }
        Dialog.dialogifyPage();
    }
});


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	//return Cookie.erase(name);
}

//http://www.jsfromhell.com/forms/masked-input
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

MaskInput = function(f, m){ //v1.0
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/   , "8": /./ },	rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};

var UploadProgress = {
  uploading: null,
  monitor: function(upid) {
    if(!this.periodicExecuter) {
      this.periodicExecuter = new PeriodicalExecuter(function() {
        if(!UploadProgress.uploading) return;
        new Ajax.Request('/planning_center/attachment/upload_update?upload_id=' + upid);
      }, 2);
    }
    
    $('status-text').innerHTML   = "Initializing Upload<br /><small></small>";
    $('status-bar').style.width = "0%";

	$A($('files_list').getElementsByTagName('input')).each(function(node){
			Element.hide(node);
		});
    this.uploading = true;
  },

  update: function(total, current) {
    if(!this.uploading) return;
    if(total == 1)
    {
    }
    else
    {
        var status     = current / total;
        var statusHTML = status.toPercentage();
        $('status-text').innerHTML   = statusHTML + "<br /><small>" + current.toHumanSize() + ' of ' + total.toHumanSize() + " uploaded.</small>";
        $('status-bar').style.width = status.toPercentage();
    }
  },
  
  finish: function(type, id, table) {
    this.uploading = false;
    $('status-text').innerHTML   = "Finished uploading...updating file list.<br /><small></small>";
    $('status-bar').style.width = "100%";
	new Ajax.Updater(type + '_' + id + '_attachments', "/planning_center/attachment/update/" + type + '/' + id + '?table=' + table, { asynchronous:true, evalScripts:true, onComplete: UploadProgress.finishComplete } );
  },
  
  finishComplete: function() {
    Dialog.close();
  },
  
  cancel: function(msg) {
    if(!this.uploading) return;
    this.uploading = false;
    if(this.StatusBar.statusText) this.StatusBar.statusText.innerHTML = msg || 'canceled';
  }
}

Number.prototype.bytes     = function() { return this; };
Number.prototype.kilobytes = function() { return this *  1024; };
Number.prototype.megabytes = function() { return this * (1024).kilobytes(); };
Number.prototype.gigabytes = function() { return this * (1024).megabytes(); };
Number.prototype.terabytes = function() { return this * (1024).gigabytes(); };
Number.prototype.petabytes = function() { return this * (1024).terabytes(); };
Number.prototype.exabytes =  function() { return this * (1024).petabytes(); };
['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte', 'exabyte'].each(function(meth) {
  Number.prototype[meth] = Number.prototype[meth+'s'];
});

Number.prototype.toPrecision = function() {
  var precision = arguments[0] || 0;
  var s         = Math.round(this * Math.pow(10, precision)).toString();
  var pos       = s.length - precision;
  var last      = s.substr(pos, precision);
  return s.substr(0, pos) + (last.match("^0{" + precision + "}$") ? '' : '.' + last);
}

// (1/10).toPercentage()
// # => '10%'
Number.prototype.toPercentage = function() {
  return (this * 100).toPrecision(0) + '%';
}

Number.prototype.toHumanSize = function() {
  if(this < (1).kilobyte())  return this + " Bytes";
  if(this < (1).megabyte())  return (this / (1).kilobyte()).toPrecision()  + ' KB';
  if(this < (1).gigabytes()) return (this / (1).megabyte()).toPrecision()  + ' MB';
  if(this < (1).terabytes()) return (this / (1).gigabytes()).toPrecision() + ' GB';
  if(this < (1).petabytes()) return (this / (1).terabytes()).toPrecision() + ' TB';
  if(this < (1).exabytes())  return (this / (1).petabytes()).toPrecision() + ' PB';
                             return (this / (1).exabytes()).toPrecision()  + ' EB';
}

// Multiple file selector by Stickman -- http://www.the-stickman.com 
// with thanks to: [for Safari fixes] Luis Torrefranca -- http://www.law.pitt.edu and Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com [for duplicate name bug] 'neal'
function MultiSelector( list_target, max ){this.list_target = list_target;this.count = 0;this.id = 0;if( max ){this.max = max;} else {this.max = -1;};this.addElement = function( element ){if( element.tagName == 'INPUT' && element.type == 'file' ){element.name = 'file_' + this.id++;element.multi_selector = this;element.onchange = function(){var new_element = document.createElement( 'input' );new_element.type = 'file';this.parentNode.insertBefore( new_element, this );this.multi_selector.addElement( new_element );this.multi_selector.addListRow( this );this.style.position = 'absolute';this.style.left = '-1000px';};if( this.max != -1 && this.count >= this.max ){element.disabled = true;};this.count++;this.current_element = element;} else {alert( 'Error: not a file input element' );};};this.addListRow = function( element ){var new_row = document.createElement( 'div' );var new_row_button = document.createElement( 'input' );new_row_button.type = 'button';new_row_button.value = 'Remove';new_row.element = element;new_row_button.onclick= function(){this.parentNode.element.parentNode.removeChild( this.parentNode.element );this.parentNode.parentNode.removeChild( this.parentNode );this.parentNode.element.multi_selector.count--;this.parentNode.element.multi_selector.current_element.disabled = false;return false;};new_row.innerHTML = element.value;new_row.appendChild( new_row_button );this.list_target.appendChild( new_row );};};

PersonSelector = Class.create();
PersonSelector.prototype  = {
	needed: 0,
    initialize: function(needed, position) {
		this.needed = needed;
		this.position = position;
	},

	toggle: function(dom_id, tr_dom_id) {
		if($(tr_dom_id).down('input').checked) {
			this.needed = this.needed + 1;
			$(tr_dom_id).down('input').checked = !$(tr_dom_id).down('input').checked; 
			$(tr_dom_id).toggleClassName('selected');
		} else {
			if(this.needed != 0) {
				this.needed = this.needed - 1;
				$(tr_dom_id).down('input').checked = !$(tr_dom_id).down('input').checked; 
				$(tr_dom_id).toggleClassName('selected');
			}
		}
		if(this.needed == 0) {
			$('person_selector_needed').innerHTML = "The '" + this.position + "' position has been filled.";
		} else if(this.needed == 1) {
			$('person_selector_needed').innerHTML = "You still need " + this.needed + " person for the '" + this.position + "' position.";
		} else {
			$('person_selector_needed').innerHTML = "You still need " + this.needed + " people for the '" + this.position + "' position.";
		}
	}
}

var number_of_plans_selected = 0;
function addPlanToMatrix(e, ministry_id) {
    if(number_of_plans_selected < 20)
    {
        number_of_plans_selected++;
    	Element.hide(e.id);
    	new_element = document.createElement("div");
    	new_element.innerHTML = e.innerHTML;
    	new_element.id = e.id + '_selected';
    	new_element.className = "matrix_selector_plan";
    	$('selected_plans_' + ministry_id).appendChild(new_element);
    	$(e.id + '_selected').getElementsBySelector('img')[0].src = "/images/matrix_button_remove.gif";
    	$('selected_plans_' + ministry_id).show();
    	Event.observe(e.id + '_selected', 'click', removePlanFromMatrix);
    	new Effect.Highlight(new_element,{ duration: 2 });
    } else {
        alert('You can only have 20 plans selected for the matrix.');
    }
}

function removePlanFromMatrix(event) {
    number_of_plans_selected--;
	element = Event.element(event);
	if(element.tagName == "IMG") { element = element.parentNode; }
	original_element_id = element.id.gsub("_selected", "");
	if($(original_element_id)) {
		$(original_element_id).show();
		new Effect.Highlight(original_element_id, { duration: 2 });
	}
	element.remove();
}

function removeSelectedPlans() {
	$$('#selected_plans .matrix_selector_plan').each( function(item) {
		item.id.scan(/\d+/, function(id) { if($('container_for_' + id)) { Element.hide('container_for_' + id); } } );
	});
}

function updatePositionCount() {
	elements = $$('#position_criteria select');
	items = '';
	elements.each( function(item) { items += (item.id + '=' + item.value + '&'); } );
	new Ajax.Request('/people/count', { method: 'get', parameters: items, onComplete: function(t) { $('position_count').innerHTML = 'You currently have ' + t.responseText + ' people selected for this position.'; } } ); 
}


// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
	target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
	target.style.MozUserSelect="none"
else //All other route (ie: Opera)
	target.onmousedown=function(){return false}
	target.style.cursor = "default"
}

//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"

Blinder = {
	elements: {},
	onMouseOver: function(container, element, event) {
	  var currentTarget = container;
	  var relatedTarget = $(event.relatedTarget || event.fromElement);
	  if (relatedTarget==currentTarget ||	relatedTarget.childOf(currentTarget)) return;
	  Blinder.elements[element.id] = true
	  if (element.visible()) return;
	  $H(Blinder.elements).keys().each(function(e) { $(e).hide(); })
	  if(container.hasClassName('button_blinder')) { element.show(); } else {  new Effect.BlindDown(element, {duration:0.15, queue: 'end'}); }
	},

	onMouseOut: function(container, element, event) {
		  var currentTarget = container;
		  var relatedTarget = $(event.relatedTarget || event.toElement);
		  var otherTarget = $('last_viewed_plans')
		  if (relatedTarget==currentTarget || relatedTarget.childOf(currentTarget)) return;
		  if (relatedTarget==otherTarget || relatedTarget.childOf(otherTarget)) return;
		  Blinder.elements[element.id] = false
		  var f= function() { 
			if (Blinder.elements[element.id]) { return; }
		  	if(container.hasClassName('button_blinder')) { element.hide(); } else { new Effect.BlindUp(element, {duration:0.15, queue: 'end'}); }	
		  };
	  	  setTimeout(f, 700);
	}		
}

Date.parseInternational = function(format, value) {
	if(format == 'dd/mm/yyyy') {
	    parts = value.split('/');
            value = parts[1] + '/' + parts[0] + '/' + parts[2];
	}
	return Date.parse(value);
}

function killIt (e)
  {
  if (typeof e != 'undefined' && e.keyCode == 13)
    {
    return false;
    }
  return true;
  }


function setSelectionRange(input, selectionStart, selectionEnd)

{
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionStart);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}