$(document).ready(function(){
	jQuery.validator.addClassRules({
	  min_length: {
	    required: true,
	    min: $('#'+$('.min_length').attr('id')+'_min').val()
	  }
	});
	//custom event for page load
	$(document).bind("basic_functions", function(ev){tc_basic_functions(this)});
	//ajax events
	$('body').ajaxComplete(function(event,request, settings){$(this).trigger('basic_functions');});
	//normal live events
	$("table.ajax_checkbox").live("click", function(event){ajax_checkbox_click(event,this)});
	$(".do_show_hide,table.row_link tr").live("mouseover", function(){$(this).css("cursor","pointer")});
	$(".do_show_hide").live("click", function(event){show_hide_element(this,false)});
	$(".do_record_show_hide").live("click", function(){record_show_hide(this)});
	$(".do_record_show_hide").live("click", function(){record_show_hide(this)});
	$("input.multiple_show").live("click", function(){multiple_show_elments(this)});
	$("table.row_link").live("click", function(event){row_link(event,this)});
	$("table.row_check").live("click", function(event){row_check(event,this)});
	$(".audio_player").live("click", function(event){create_audio_player(event,this)});
	$(".audio_player_wav").live("click", function(event){create_audio_player_wav(this)});
	$(".do_print").live("click", function(){window.print()});
	$("input.js_select_all").live("click", function(event){check_select_all(this,true)});
	$("input.js_deselect_all").live("click", function(event){check_select_all(this,false)});
	$("a.do_show_hide_sub_list").live("click", function(event){show_sub_list(event,this)});
	//trigger the custom event on load
	$('body').trigger('basic_functions');
	//apply_functions($(document));
	/*
	 Possible event values: click, dblclick, mousedown, mouseup, mousemove, 
	 mouseover, mouseout, keydown, keypress, keyup 
	 
	 Currently not supported: blur, focus, mouseenter, mouseleave, change, submit
	*/
	/* seem to not work if added with below */
	$("input.ajax_check_string").each(function(){
		$(this).change(function(event){check_string_ajax(this)});
	});
});
function tc_basic_functions(el){
	$(el).find(".do_show_hide_element").each(function(){
		if(check_add_enhancement(this,'do_show_hide_element')){
			show_hide_element_default(this,true);
		}
	});
	$(el).find("input.search_textbox").each(function(){
		if(check_add_enhancement(this,'search_textbox')){
			$(this).focus(function(){$(this).select()});
		}
	});
	$(el).find("form.validate_form").each(function(){
		if(check_add_enhancement(this,'validate_form')){
			$(this).validate({submitHandler: function(form_el) {
				show_working_ani($('#'+$(form_el).attr("id")+" input[type='submit']"));
				form_submit_ajax(form_el);
			   }
			});
		}
	});
	if($.isFunction($.facebox)){
		$(el).find("a.max_lookup").each(function(){
			if(check_add_enhancement(this)){
				$(this).facebox()
			}
		});
	}
	$(el).find(".required").each(function(){
		if(check_add_enhancement(this,'required')){
			required_change_icon(this);			
			$(this).change(function(event){required_change_icon(this)});
		}
	});
	$(el).find(".js_text_count").each(function(){
		if (check_add_enhancement(this,'js_text_count')) {
			add_text_count_total(this);
		}
	});
	$(el).find('.label_tooltip').each(function(){
		if (check_add_enhancement(this,'label_tooltip')) {
			create_tooltip_icon(this);
		}
	});
	$(el).find("table.sortable_table").each(function(){
		if(check_add_enhancement(this,'sortable_table')){$(this).tablesorter({widgets: ['zebra','highlight_row']});}
	});
	 
	$(el).find("select.select_date").each(function(){
		if(check_add_enhancement(this,'select_date')){$(this).change(function(event){date_select_change(this)});}
	});
	$(el).find(".show_selected_option").each(function(){if (check_add_enhancement(this,'show_selected_option')) {
		show_selected_option(this);
		$(this).change(function(event){show_selected_option(this)});
	}});
	
	$(el).find("select.select_update").each(function(){
		if(check_add_enhancement(this,'select_update')){$(this).change(function(event){select_ajax_update(this)});}
	});
	
	$(el).find("a.do_show_hide_sub_list").each(function(){
		if(check_add_enhancement(this,'do_show_hide_sub_list')){show_sub_list('',this);}
	});
}
function show_sub_list(e,el){
	if(e!=''){
		e.preventDefault();	
	}
	if($(el).hasClass("icon_minus")){
		$(el).removeClass("icon_minus");
		$(el).parent('li').find('ul:first ').hide('slow');
	}else{
		$(el).addClass("icon_minus");	
		$(el).parent('li').find('ul:first ').show('slow');
	}
	
}
function check_string_ajax(el){
	var my_id=$(el).attr('id');
	var ajax_url=$('#'+my_id+'_ajax_check_url').val();
	var ignore_word=$('#'+my_id+'_ajax_check_ignore').val();
	//ajax submit
	$.ajax({
		type: 'get',
		url: ajax_url,
		data: my_id+'='+$(el).val()+'&ignore_word='+ignore_word,
		success: function(msg){
			//alert( msg );
			validator = $("form.validate_form").validate();
			if(msg=='true'){
				eval('obj={"'+my_id+'": "In use please try a different one"}');
				validator.showErrors(obj);	
			}
			
		},
		error: function (xhr, desc, exceptionobj) {
			alert("Error please contact the admin with these details: \n"+xhr.responseText);
		}
	});
}

function check_add_enhancement(el,item){
	if (typeof(item) == "undefined") {
		item='';
	}
	var test=$(el).data('js_enhanced'+item);
	
	if (typeof(test) == "undefined") {
		$(el).data('js_enhanced'+item, {'is_enhanced': true});		
		return true;
	}else{
		return false;
	}
}
function form_submit_ajax(form_el){
	var info=$(form_el).data('info');
	if(typeof(info) != "undefined"){
		info.theevent(form_el,info);
	}else{
		form_el.submit();	
	}
}
//abxdefghijklmnopqrstwvxyz
function ajax_checkbox_click(event,el){
	//find the source of the click - event delagation!
	var tgt = $(event.target);
    if (tgt.is("input[type='checkbox']")){
    	if(! tgt.is("input.not_ajax_checkbox_click")){
	    	//set vars
			var form_el=$(tgt).parents("form");
			var form_url=$(form_el).attr("action");
			var form_method=$(form_el).attr("method");
			var form_action=$(form_el).find('input#form_action').val();
			var ids_list=$(tgt).val();
			
			var url_vars='ajax_update=true&ids_list='+ids_list+'&form_action='+form_action;
			var parent_td=$(tgt).parents("td");
			if ($(tgt).is(":checked")) {
				$(parent_td).addClass("sale_paid2");
				url_vars += '&' + $(tgt).attr('name') + '=' + $(tgt).val();
			}else{
				$(parent_td).removeClass("sale_paid2");
			}
			//ajax submit
			$.ajax({
				type: form_method,
				url: form_url,
				data: url_vars,
				success: function(msg){
					//alert( "Data Saved: " + msg );
				},
				error: function (xhr, desc, exceptionobj) {
					alert("Error please contact the admin with these details: \n"+xhr.responseText);
				}
			});
			//update the css class of the td wrapping
    	}
		
    }
}
function add_text_count_total(el){
	var randomnumber=Math.floor(Math.random()*11);
	var my_id='count_total'+randomnumber;
	var my_id2='count_left'+randomnumber;
	var the_fieldset = $(el).after('<fieldset class="sub_controls"><div>Total characters available <span id="'+my_id+'">#x#</span></div><div>Total characters left <span id="'+my_id2+'">#x#</span></div></fieldset>');
	var el_max=$('#'+$(el).attr("id")+'_max_chars');
	if(el_max){
		var max_chars=$(el_max).val();	
	}else{
		var max_chars=160;
	}
	update_total(null,$(el),my_id,my_id2,max_chars);
	$(el).keypress(function(event){update_total(event,this,my_id,my_id2,max_chars)});
}
function create_audio_player(event, el){
	event.preventDefault();
	the_href = $(el).attr("href");
	if($(el).attr("id") == ''){
		var randomnumber = Math.floor(Math.random() * 11);
		var my_id = 'audio_player'+ randomnumber;
		$(el).attr("id", my_id);
	}else{
		var my_id = $(el).attr("id");
	}
	
	if($(el).hasClass("icon_play")){
		$(el).addClass("icon_stop");
		$(el).removeClass("icon_play");
		$(el).text('Stop ' + $(el).attr("title"));
		soundManager.createSound({
			id: my_id,
			url: the_href,
			onfinish: function(){
				//change the play icon to a pause icon
				$(el).removeClass("icon_stop");
				$(el).addClass("icon_play");
				$(el).text('Play ' + $(el).attr("title"));
			}
		});
		soundManager.play(my_id);
	}else{
		soundManager.pause(my_id);
		$(el).removeClass("icon_stop");
		$(el).addClass("icon_play");
		$(el).text('Play ' + $(el).attr("title"));	
	}
}
function create_audio_player_wav(el){
	var the_href = $(el).attr("href");
	var play_el=$('<input type="button" value="Play Wav">');
	$(play_el).click(function(){play_wav(the_href)});
	var new_el='<bgsound id="wav_sound" src="boo">\
	<!--[if ! IE]>-->\
	<applet code="AudioPlay.class" id="wav_sound_applet" CODEBASE="\helpline" width="40" height="40">\
	  <param name=image value="play.gif">\
	  <param name=audio value="'+the_href+'">\
	  <param name=bkgray value="0">\
	</applet>\
	<!--<![endif]-->\
	';
	$(el).replaceWith($(play_el));
	$(play_el).after(new_el);
}
function play_wav(wav){
	//play for IE
	$('#wav_sound').attr('src', wav);
	//play for applet
	if ($('#wav_sound_applet').length > 0) {
		 var thissound=document.getElementById('wav_sound_applet');
  		 thissound.Play();
	}
}
function update_total(event,el,count_total,count_left,max_chars){
	var total_chars=$(el).val().length;
	$('#'+count_total).text(total_chars);
	var left_chars=max_chars-total_chars;
	if(left_chars < 1 && event.which != '8'){
		//cancel the event apart from the delete key
		event.preventDefault();
	}
	$('#'+count_left).text(left_chars);	
}
function add_tooltip_text(event,el,b_mouse){
	event.preventDefault();
	var tooltip_el=$('#tooltip_'+$(el).attr('for'));
	if(jQuery.trim(tooltip_el.html())!=''){
		tooltip_el.toggle("fast");
		//(b_mouse)?tooltip_el.show(200):	tooltip_el.hide(200);	
	}
}
function create_tooltip_icon(el){
	var tooltip_el=$('#tooltip_'+$(el).attr('for'));
	if (jQuery.trim(tooltip_el.html()) != '') {
		var me = $(el).append('<a href="#" class="icon_link help_inline_icon">&nbsp;</a>');
		$(me).click(function(event){add_tooltip_text(event,el, true)});
	}
}
function date_select_change(el){
	var my_id=$(el).attr("id");
	
	//extract the sufix for the other date pickers.
	var select_group=my_id.substr(my_id.indexOf("_")+1);
	var day_elem=$('#day_'+select_group);
	var month_elem=$('#month_'+select_group);
	var year_elem=$('#year_'+select_group);
	
	var timeA = new Date($(year_elem).find("option:selected").val(),$(month_elem).find("option:selected").val(),1);
	var selectDay=$(day_elem).find("option:selected").val();
	timeB = new Date(timeA - 86400000);
	var daysInMonth = timeB.getDate();
	//remove all the options
	$(day_elem).html('');
	//add them again
	var options='';
	for (var i = 0; i < daysInMonth; i++) {
		options +='<option value="'+(i+1)+'">'+(i+1)+'</option>';
	}
	$(day_elem).html(options);
	//if day in range
	daysInMonth=daysInMonth;//-1 ;
	//console.log(daysInMonth);
	(daysInMonth < selectDay)? $(day_elem).val([daysInMonth]): $(day_elem).val([selectDay]);
}
function multiple_show_elments(el){
	//get the show list
	var show_list=$('#'+$(el).attr('id')+'_multiple_show').val();
	var show_array=show_list.split(',');
	for(i=0;i<show_array.length;i++){
		$('#'+show_array[i]+'_show_hide').show();
	}
}
function required_change_icon(el){
	var em_el=$(el).prevAll('label').find('em');
	val=($(el).val() =='')? $(em_el).removeClass("tick_icon") : $(em_el).addClass("tick_icon");
}
function show_hide_element(el,me_or_linked){
	//val=(condition)? iftrue : iffalse
	var add_icon=false;
	var b_checked=false;
	var icon_el=false;
	if(me_or_linked){
		
		var show_hide_el=$(el);
		var my_id=$(el).attr("id");
		var sutracted_el='#'+my_id.substr(0,my_id.length-10);
		
		if(sutracted_el !='#'){
			b_checked=$(sutracted_el).is(':checked');
			icon_el=$(sutracted_el);
		}
		
	}else{
		var show_hide_el=$('#'+$(el).attr("id")+'_show_hide');
		if($(el).is("input[type='checkbox']")){
			var b_checked=$(el).is(':checked');
		}else{
			($(show_hide_el).is(":visible"))? b_checked=false : b_checked=true;
		}
		icon_el=$(el);
	}
	if(b_checked){
		var width_store='';
		if((show_hide_el)[0].tagName == 'TABLE'){
			//get the css width
			width_store=$(show_hide_el).css('width');
		}
		if(width_store !=''){
			show_hide_el.show();	
		}else{
			show_hide_el.show("slow");	
		}
		add_show_hide_icon(icon_el,true);	
	}else{
		show_hide_el.hide();
		add_show_hide_icon(icon_el,false);	
	}	
}
function show_working_ani(button_el){
	$(button_el).toggle();
	if($(button_el).is(":hidden")){
		$(button_el).before('<strong class="working_link" id="js_working_link">working...</strong>');
	}else{
		$('#js_working_link').remove();
	}
}
function add_show_hide_icon(el,b_show){
	if(b_show){
		$(el).addClass("icon_minus");
		$(el).removeClass("icon_plus");	
	}else{
		$(el).addClass("icon_plus");
		$(el).removeClass("icon_minus");
	}
}
function show_hide_element_default(el,me_or_linked){
	
	if(typeof show_list != "undefined"){
		var find_id=$(el).attr("id");
		var find_el=find_id.substring(0,(find_id.length-10));
		var find_pos=show_list.indexOf(find_el);
		
		if(find_pos ==-1){
			show_hide_element(el,me_or_linked);
		}else{
			
			record_show_hide($('#'+find_el));
			add_show_hide_icon($('#'+find_el),true);	
		}	
	}else{
		show_hide_element(el,me_or_linked);
	}
}
function show_selected_option(el){
	//get all options and set to invisible
	$("fieldset[id*='"+$(el).attr('id')+"']").each(
		function(){
			$(this).hide();
			$(this).find('input').attr("disabled", true); 
		});
	var el_val=$(el).val();
	var el_id=$(el).attr('id');
	$('#'+el_id+'_'+el_val).fadeIn("slow");
	$('#'+el_id+'_'+el_val).find('input').removeAttr("disabled"); 
}
function row_link(event,el){
	var ev_tr=$(event.target).parents('tr').find('a');
	window.location=$(ev_tr).attr('href');
}
function row_check(event,el){
	if(! $(event.target).is('input')){
		var ev_tr=$(event.target).parents('tr').find('input');
		($(ev_tr).attr('checked'))? $(ev_tr).attr('checked',''):$(ev_tr).attr('checked','checked');	
	}
}
function check_select_all(el,b_check){
	var el_id=$(el).attr('id');
	if(b_check){
		var check_name=el_id.substring(0,el_id.length-10);
	}else{
		var check_name=el_id.substring(0,el_id.length-12);
	}
	$("input[name=" + check_name + "]").attr('checked',b_check);
}
function record_show_hide(el){
	var show_hide_el=$('#'+$(el).attr("id")+'_show_hide');
	if($(show_hide_el).is(":hidden")){
		$(el).removeClass("js_record_id_show");
	}else{
		$(el).addClass("js_record_id_show");
	}
	var show_list_el=$('#show_list');
	show_list_el.val('');
	$('.js_record_id_show').each(function(){
		var string_show=show_list_el.val();
		string_show+=$(this).attr('id')+',';
		show_list_el.val(string_show);
	});
}
// table sorter widgets
$.tablesorter.addWidget({
	// give the widget a id
	id: "highlight_row",
	// format is called when the on init and when a sorting has finished
	format: function(table) {
		if(!$(table).hasClass('no_click')){
			$(table).click(function(event){
					var ev_tr=$(event.target).parents('tr');
					$('tr.stripe_click').removeClass('stripe_click');
					ev_tr.addClass('stripe_click');
				}
			);
		}
	}
});
function select_ajax_update(el){
	//get the hidden el that has the name of el to update as value
	var el_update_id=$('#'+$(el).attr('id')+'_update_el').val();
	var el_update_url=$('#'+$(el).attr('id')+'_update_url').val();
	var el_update=$('#'+el_update_id);
	if(typeof(el_update)!= 'undefined' && typeof(el_update_url)!= 'undefined'){
		var el_form=$(el).parents('form');
		var el_form_vars=$("form").serialize();
		//ajax submit
		$.ajax({
			type: 'get',
			url: el_update_url,
			data:  $("form").serialize(),
			success: function(msg){
				//replace the options in the select list with the new options
				$(el_update).html(msg);
			},
			error: function (xhr, desc, exceptionobj) {
				alert("Error please contact the admin with these details: \n"+el_update_url+'?'+el_form_vars);
			}
		});
		
	}
}