
if (typeof console=="undefined"){console={log:function(A){var B=false;if(B){ }}}}



$(document).ready(function(){


$('.result').pinball();


if( document.getElementById('google_analytics') ) {
	ajax("#google_analytics", "/admin/misc/graph");
	ajax("#google_analytics_text", "/admin/misc/analytics");
	$("a.update_graph").click(function() {
		update_graph($(this).attr("href"));
		return false;
	});
}

		// Basic Bling	
			$("table.sortable tr").hover(
			  function () {
				$(this).addClass("ruled");
			  }, 
			  function () {
				$(this).removeClass("ruled");
			  }
			);


			$("a[href*=.pdf]").click(function(){
				window.open(this.href);
				return false;
			});	

			$("a[href*=.xls]").click(function(){
				window.open(this.href);
				return false;
			});	

			$("a.new_window").click(function(){
				window.open(this.href);
				return false;
			});	


			if(!document.getElementById('quick'))
			{
				jQuery.validator.setDefaults({
	//				debug: true,
					success: "valid"
				});

				$("#editForm").validate({
					rules: {
						name: "required"
					}
				});

			}


			$("a.delete").click(
				function() {
					var answer = confirm('Delete '+jQuery(this).attr('title')+'?');
					return answer;
				}
			);

	$('.date-pick').datePicker();


	$('#booking_jump_month').submit(function() {


		var data = $(this).serialize();
		tmp = data.split('&');
		var month = tmp[0].split('=');
		var year = tmp[1].split('=');

		var to_url = '/admin/bookings/view_month/'+month[1]+'/'+year[1];
		console.log(to_url);

		//e.preventDefault();
		window.location = to_url;

		return false;
	});


	$('#bus_jump_month').submit(function() {


		var data = $(this).serialize();
		tmp = data.split('&');
		var month = tmp[0].split('=');
		var year = tmp[1].split('=');

		var to_url = '/admin/bookings_groups/view_month/'+month[1]+'/'+year[1];
		console.log(to_url);

		//e.preventDefault();
		window.location = to_url;

		return false;
	});

	$('#renewals_jump_month').submit(function() {


		var data = $(this).serialize();
		tmp = data.split('&');
		var month = tmp[0].split('=');
		var year = tmp[1].split('=');

		var to_url = '/admin/fold_cron/index/'+month[1]+'/'+year[1];
		console.log(to_url);

		//e.preventDefault();
		window.location = to_url;

		return false;
	});


	$('#fold_jump_month').submit(function() {


		var data = $(this).serialize();
		tmp = data.split('&');
		var month = tmp[0].split('=');
		var year = tmp[1].split('=');

		var to_url = '/admin/fold/renewals/'+month[1]+'/'+year[1];
		console.log(to_url);

		//e.preventDefault();
		window.location = to_url;

		return false;
	});



		// Validation	
			$('a').tooltip();


	$(".calendar").equalHeights();

	$(".calendar td a div.nada").each(function(){

		$(this).parent().addClass('grey_out');

	});


	$(".calendar th").each(function() {
		var c_current = $(this).html();
		var c_url = c_current.replace('&nbsp; ', '/');
		var c_link = '<a href="/admin/bookings/view_month/'+c_url+'">'+c_current+'</a>';	
		$(this).html(c_link);
	});

	//$('div.nada',$(this).parent('td:first')).addClass('grey_out');

	$(".half_block").equalHeights();

	$("table.events_table th:first").addClass("date_field");

	//limit remarks columns
	$(".sortable th").each(function() {
		var c_current = $(this).html();
		if(c_current == 'Remarks')
		{
			$(this).addClass("remarks_field");
		}
	
	});


	$("table.booking_table th:first").addClass("no_print");
	$("table.booking_table th:last").addClass("no_print");



});

$(document).ready(function(){



		//$(".error").hide().slideDown(1500);
		//$(".info").hide().fadeIn(1500);
		//$(".alert").hide().fadeIn(1500);
		/*$(".success").fadeIn('fast')
					.slideDown('fast')
					.animate({opacity: 1.0}, 3000)
					.slideUp('fast');
		*/


			$("#quick").autocomplete("/admin/contacts/search_ajax", {
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false,
				onFindValue:findValue,
				formatItem:formatItem,
				selectFirst: false
			}).result(function(event, item) {
				item = String(item);
				var tmp_url = item.split(",");
				tmp_url.reverse();

				var url = tmp_url[0];

				location.href = "/admin/contacts/view/"+url;
				return false;
			});



			$("#quick_booking").autocomplete("/admin/contacts/search_ajax", {
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false,
				onFindValue:findValue,
				formatItem:formatItem,
				selectFirst: false
			}).result(function(event, item) {
				item = String(item);
				var tmp = item.split(",");
				tmp.reverse();

				var PilgrimID = tmp[0];

				var tmp = window.location.pathname.split("/");
				tmp.reverse();
				var event_id = tmp[0] 


				var url = '/admin/bookings/booking_type/'+event_id+'/'+PilgrimID;
				location.href = url;
				return false;
			});
			
			$("#quick_booking_reference").autocomplete("/admin/contacts/search_ajax", {
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false,
				onFindValue:findValue,
				formatItem:formatItem,
				selectFirst: false
			}).result(function(event, item) {
				item = String(item);
				var tmp = item.split(",");
				tmp.reverse();

				var PilgrimID = tmp[0];

				var tmp = window.location.pathname.split("/");
				tmp.reverse();
				var event_id = tmp[1];
				
				var BusReference = tmp[0];

				var url = '/admin/bookings/booking_add/'+event_id+'/'+PilgrimID+'/n/'+BusReference;
				location.href = url;
				return false;
			});
			

			$("#quick_draws").autocomplete("/admin/contacts/search_ajax", {
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false,
				onFindValue:findValue,
				formatItem:formatItem,
				selectFirst: false
			}).result(function(event, item) {
				item = String(item);
				var tmp = item.split(",");
				tmp.reverse();

				var PilgrimID = tmp[0];

				var url = '/admin/draws/view_person/'+PilgrimID;
				location.href = url;
				return false;
			});


			$("#quick_bus").autocomplete("/admin/bookings_groups/search_ajax", {
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false,
				onFindValue:findValue,
				formatItem:formatItem,
				selectFirst: false
			}).result(function(event, item) {
				item = String(item);
				var tmp = item.split(",");
				//tmp.reverse();

				var Reference = tmp[0];

				var url = '/admin/bookings_groups/view/'+Reference;
				location.href = url;
				return false;
			});

});


function addFormField(label, type) {
	var id = document.getElementById("id").value;


	switch(type)
	{
		case 'varchar':
			form_input = "<label for='"+label+'_'+id+"'> " + label + " </label><br />";
			form_input += '<select name="'+id+'_comp"><option value="LIKE">MATCHES</option><option value="NOT LIKE">DOES NOT MATCH</option></select>';
			form_input += '<input type="text" name="'+id+'_'+label+'"/>';
		break;

		case 'date':
			form_input = "<label for='"+label+'_'+id+"'> " + label + " <small>(dd-mm-yyyy)</small></label><br />";
			form_input += '<select name="'+id+'_comp"><option value="=">ON DATE</option><option value="<">BEFORE</option><option value=">">AFTER</option></select>';
			form_input += '<input type="text" class="date-pick" name="'+id+'_'+label+'" />';
		break;

		case 'int':
			form_input = "<label for='"+label+'_'+id+"'> " + label + " </label><br />";
			form_input += '<select name="'+id+'_comp"><option value="=">EQUALS</option><option value=">">IS GREATER THAN</option><option value="<">IS LESS THAN</option></select>';
			form_input += '<input type="text" name="'+id+'_'+label+'" />';
		break;

		case 'text':
			form_input = "<label for='"+label+'_'+id+"'> " + label + " </label><br />";
			form_input += '<select name="'+id+'_COMP_'+label+'"><option value="LIKE">MATCHES</option><option value="NOT LIKE">DOES NOT MATCH</option></select>';
			form_input += '<input type="text" name="'+id+'_'+label+'"/>';
		break;

	}

	form_input += '<input type="hidden" name="'+id+'_'+'type" value="'+type+'"/>';
	form_input += '<input type="hidden" name="'+id+'_'+'field" value="'+label+'"/>';

	form_frag = '<p id="row' + id + '" class="block">';
	form_frag += '<a href="#" onClick="removeFormField(\'#row'+id+'\'); return false;" class="remove">Remove</a>';

	form_frag += form_input;
	form_frag += '<br />';
	form_frag += '<select name="'+id+'_cond"><option value="AND">AND</option><option value="OR">OR</option></select>';

	form_frag += '<p>';

	$("#divTxt").append(form_frag);
	
	$('#row' + id).animate({ backgroundColor: "#eff6f8" }, "slow");
	
	id = (id - 1) + 2;
	document.getElementById("id").value = id;

	if ( $("#advanced_search p.block").length > 0 )
	{ 
		$("#adv_submit").show(); 
	}
	else
	{
		$("#adv_submit").hide(); 
	}


}

function removeFormField(id) {

	$(id).animate({ backgroundColor: "#fbc7c7" }, "fast")
		.animate({ opacity: "hide" }, "slow")
		.remove();


}



function removeHTMLTags(text) {
	var strInputCode = text;
	/*
	This line is optional, it replaces escaped brackets with real ones,
	i.e. < is replaced with < and > is replaced with >
	*/
	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) {
		return (p1 == "lt")? "<" : ">";
	});
 
	var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
	//alert(”Output text:\n” + strTagStrippedText);
	// Use the alert below if you want to show the input and the output text
	// alert(”Input code:\n” + strInputCode + “\n\nOutput text:\n” + strTagStrippedText);
	return strTagStrippedText;
}

function findValue(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

	alert("The value you selected was: " + sValue);
}

function selectItem(li) {
	findValue(li);
}


function formatItem(row) {
	return row[0] + " [# " + row[1] + "]";
	return row[0];
}




function toggleBlock(id) {


	var ctrl = document.getElementById(id);

	if ( ctrl.className != 'collapse' ) {
		ctrl.className = 'collapse';
	}
	else {
		ctrl.className = 'expand';
	}


	var child = id.split('_');
	var obj = 'collapse_'+child[1];

	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		$('#'+el.id).slideUp();
	}
	else {
		$('#'+el.id).show("slow");
	}
}



$(document).ready(function(){

	$('.custom').hide('fast');


});


function toggleCustom(id) {

// 	alert(id);

	var el = document.getElementById(id);
	if ( el.style.display != 'none' ) {
		$('.custom').hide('fast');
	}
	else {
		$('#'+el.id).show("slow");
	}

}



/*
 * jQuery Pinball
 * Copyright 2009 Eoin McGrath
 * Released under the MIT and GPL licenses.
 */

(function($) {
	$.fn.pinball = function(options) {


	this.each(function() {

		var $this = $(this);

			$this.hover(function(e) {

				$this.addClass('active');

			}, function() {
				$this.removeClass('active');
			});

			$this.click(function (e) {
			  	var $link = $('a.target', this).attr("href");

				if($link) {
					window.location = $link;
				}

			});

		  });

		  return this;

	}
})(jQuery);




/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);


/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008


 * 29 May 09	- EDITED to work without dependencies & doesn't bother with children just the class passed to the fn
				- eoin@starfish.ie
--------------------------------------------------------------------*/

$.fn.equalHeights = function() {
	var currentTallest = 0;
	$(this).each(function(){

			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
	});

	$(this).each(function(){

		$(this).css({'height': currentTallest}); 

	});

	return this;
};



function ajax(id, url)
{

//	if(!document.getElementById(id)) {
//		return false;
//	}

	$(id).html('<img src="/assets/admin/i/loading.gif" alt="loading" /> Loading');

	$.ajax({
		type: 'POST',
		url: url,
		success: function(data) {
			$(id).hide();
			$(id).html(data);
			$(id).slideDown("slow");
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$(id).html('Timeout contacting server..');
		}
	});


}


function update_graph(link)
{

	ajax("#google_analytics", link);
}


