document.observe("dom:loaded", function() {

// This handles Manage Groups and Manage Leaders pages

      // working with delete
      deleteLinks = function(b_setBehaviours){
	    b_setBehaviours.each( function(currentElement, index){
		currentElement.observe('click', function(currentEvent){
 		      Event.stop(currentEvent);

		      if(currentElement.readAttribute('href')!=null) {

				continuteevent = confirm(commonSubTexts_json.confirm_delete);

				if(continuteevent == true) {
				  // get url from element
				  submitUrl = currentElement.readAttribute('href');
				  new Ajax.Request(submitUrl, {
				      method: 'get',
				      onComplete: function(){
					    location.reload();
					    }
				    });

				}
			}

		});
	    });
      }

      // working with view
      viewLinks = function(b_setBehaviours){
	      b_setBehaviours.each( function(currentElement, index){
		  currentElement.observe('click', function(currentEvent){
		      Event.stop(currentEvent);

		      var submitUrl = currentElement.readAttribute('href');
		      var link_id = currentElement.up(0).next('div');
		      // look at the manage ul and loop through closing when they are not equal to the inspected.
		      $$('ul.manage li').each(function(element, index1) {
			  if(index!==index1) {

			      element.select('div')[0].style.display="none";
			      element.select('span')[0].style.display="";
			      element.select('span')[1].style.display="";
			  }
		      });

		      if($('ajax_viewlink_add')) {
			      $('ajax_viewlink_add').hide();
		      }

		      if(link_id.innerHTML.empty()==true) {
			  link_id.style.display="none";
		      }

		      new Ajax.Updater(link_id, submitUrl, {
			  method: 'get',
			  evalScripts: true,
			  onComplete: function(){
				makeLinks(true);
			  }
		      });

		      Effect.toggle(link_id, 'appear', { duration: 0.3 });
		});
	    });
     }

     // working with edit
      editLinks = function(b_setBehaviours){
	      b_setBehaviours.each( function(currentElement, index){
		  currentElement.observe('click', function(currentEvent){
		      Event.stop(currentEvent);
		     if(currentElement.readAttribute('href')!=null) {
			      var submitUrl = currentElement.readAttribute('href');
			      var spanclass_title = currentElement.up('span');
			      var spanclass_options = currentElement.up('span').previous('span');

			      var link_id = currentElement.up(0).next('div');
			      // look at the manage ul and loop through closing when they are not equal to the inspected.
			      $$('ul.manage li').each(function(element, index1) {
				  if(index!==index1) {

				      element.select('div')[0].style.display="none";
				      element.select('span')[0].style.display="";
				      element.select('span')[1].style.display="";
				  }
			      });

			      $('ajax_viewlink_add').hide();

			      spanclass_title.style.display="none";
			      spanclass_options.style.display="none";

				  if(link_id) {
				      link_id.display="none";
				  }

			      new Ajax.Updater(link_id, submitUrl, {
				  method: 'get',
				  evalScripts: true,
				  onComplete: function(){
	       			        link_id.appear({ duration: 0.3 });
				  }
			      });
			}
		});     
	    });
     }

     // working with add
      addLinks = function(b_setBehaviours){
	      b_setBehaviours.each( function(currentElement){
		  currentElement.observe('click', function(currentEvent){
		      Event.stop(currentEvent);
		      var submitUrl = currentElement.readAttribute('href');

		      if($('ajax_viewlink_add').empty()==true) {
			  $('ajax_viewlink_add').hide();
		      }

		      // hide all elements (showing the headings)
		      $$('ul.manage li').each(function(element, index1) {
			    element.select('div')[0].style.display="none";
			    element.select('span')[0].style.display="";
			    element.select('span')[1].style.display="";
		      });

		      new Ajax.Updater('ajax_viewlink_add', submitUrl, {
			  method: 'get',
			  evalScripts: true
		      });

			Effect.toggle('ajax_viewlink_add', 'appear', { duration: 0.3 });
		});
	    });
     }

    // working with cancel button.
     cancelLinks = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){
		currentElement.observe('click', function(currentEvent){
		      Event.stop(currentEvent);
		      if(currentElement.descendantOf($('empty_modal'))) {
				Control.Modal.close();
		      } else {

				currentElement.up(9).down('span').show();
				currentElement.up(9).down('span').next('span').show();
				currentElement.up(8).hide();

		      }
		  });
	  });
    }

    // working with submit button
      submitLinks = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){
		currentElement.observe('click', function(currentEvent){

			var formValues = $("edit_leaders").serialize();
			var submitUrl = $("edit_leaders").readAttribute('action');

			new Ajax.Request(submitUrl, {
				parameters: formValues,
				onSuccess: function(transport){

					if((transport.responseText.include("<p id=\"error_message\"></p>"))) {
						// update and close.

					      if(currentElement.descendantOf($('empty_modal'))) {

							Control.Modal.close();
						         new Ajax.Request("/ajax/manageleadersreturn", {
								  method: 'get',
								  evalScripts: true,
								  onSuccess: function(transport){
									$('key_contact').innerHTML = transport.responseText;
								}
  							 });
					      } else {
							$$('ul.manage li').each(function(element) {
								element.select('div')[0].style.display="none";
								element.select('span')[0].style.display="";
								element.select('span')[1].style.display="";
							});
							$("ajax_viewlink_add").style.display="none";
							location.reload();
					      }
					} else {
						// send error message
						alert(commonSubTexts_json.error_completedetails);
					}
				}
			});

			Event.stop(currentEvent);
		});
	});
    }

    // working with add button.
     addbutton = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){
		currentElement.observe('click', function(currentEvent){
		 var user_ids = currentElement.up(0).next(0).down('select');
		      Event.stop(currentEvent);

		      var submitUrl = "/ajax/addleadertogroup/?user_id=" + $F("organisationleaders") + "&organisationid=" + currentElement.identify();
	
		      new Ajax.Updater(user_ids, submitUrl, {
				  method: 'get',
				  evalScripts: true,
				  onComplete: function(){
				}
			});

		  });
	    });
    	 }

    // working with add button.
     removebutton = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){

		currentElement.observe('click', function(currentEvent){
		 var user_ids = currentElement.up(0).next(0).down('select');
		      Event.stop(currentEvent);

		      var submitUrl = "/ajax/deleteleadertogroup/?user_id=" + $F(user_ids) + "&organisationid=" + currentElement.identify();	
		      new Ajax.Updater(user_ids, submitUrl, {
				  method: 'get',
				  evalScripts: true,
				  onComplete: function(){
				}
			});
		  });
	    });
    	 }

    showlink = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){

		currentElement.observe('click', function(currentEvent){
		 var divelement = currentElement.up(0).next('div');
		      Event.stop(currentEvent);
	     		      Effect.toggle(divelement, 'appear', { duration: 0.3 });
		  });
	    });


    }

    toggleCourseSubscriptions = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){
		currentElement.observe('click', function(currentEvent){
			var select_td = currentElement.up(0).next(0).next('td');

			if(currentElement.checked==true) { 
				var updatetag = "action=insert&name=" + currentElement.name;
			} else {
				var updatetag = "action=delete&name=" + currentElement.name;
			}

			new Ajax.Updater(select_td, "/ajax/updatecoursesubscrip?" +updatetag, {
			  method: 'get',
			  evalScripts: true,
			  onComplete: function(){
				makeLinks(true);
			  }
			});
		  });
	  })
   }

    resetCourseSubscription = function(b_setBehaviours) {
	  b_setBehaviours.each( function(currentElement){
		currentElement.observe('click', function(currentEvent){
			continuteevent = confirm(commonSubTexts_json.confirm_reset);
			if(continuteevent == true) {

				var select_input = currentElement.up(0).previous(2).down('input');
				var select_td = currentElement.up(0).previous('td');
				var updatetag = "action=reset&name=" + select_input.name;
				new Ajax.Updater(select_td, "/ajax/updatecoursesubscrip?" +updatetag, {
					method: 'get',
					evalScripts: true,
					onComplete: function(){
					makeLinks(true);
					}
				});	
			}
		      	Event.stop(currentEvent);
		});
	});
    }	

    // initiate objects.
    viewLinks( $$('a.ajax_viewlinks')); 
    editLinks( $$('a.ajax_editlinks')); 
    addLinks( $$('a.ajax_addlinks')); 
    deleteLinks( $$('a.ajax_deletelinks')); 
    viewLinks($$('a.ajax_edit_courselinks'));
    addbutton( $$('input.ajax_addbutton'));
    removebutton( $$('input.ajax_removebutton'));
    showlink($$('a.show_group'));
    resetCourseSubscription($$('a.reset_course_subscription'));
    toggleCourseSubscriptions($$('input.cb_course_subscriptions'));


	if($('view_by_agegroups')) {
		$('view_by_agegroups').observe('click', function(currentEvent){

			if($('view_by_agegroups').checked==true) {
				window.location.href = "/viewleaders?groupview=1";
			} else {
				window.location.href = "/viewleaders";
			}
		});
	}

	prepareSelectAllCheckBox = function(b_setBehaviours) {
		b_setBehaviours.each( function(currentElement){
			currentElement.observe('click', function(currentEvent){
				currentElement.up(0).select('input').each(function(element) {
					element.checked = currentElement.checked;
				});
			});
		});
	}

// This handles Email Groups

	prepareSelectCheckBox = function(b_setBehaviours) {
		b_setBehaviours.each( function(currentElement){
			currentElement.observe('click', function(currentEvent){
				if(currentElement.checked==false) {
					currentElement.up(0).up(1).select('input.selectall').each(function(element) {
						element.checked = currentElement.checked;
					});
				}
			});
		});
	}

	prepareSelectAllCheckBox( $$('input.selectall')); 
	prepareSelectCheckBox( $$('input.select')); 


     // This handles Subscription pages


    // apply input action to make billing details same as group details on change
    inputboxAction = function(b_setBehaviours, inputvalues2, indexvalue){
	b_setBehaviours.observe('change', function(currentEvent){

	    // get billing details checkbox value
	    var billingdetails = Form.getInputs('my_subscription','radio','same_billing').find(function(radio) { return radio.checked; }).value;
	    if (billingdetails=="yes") {
		//alert(indexvalue);
		inputvalues2.value = b_setBehaviours.value;

	    }

	});
    }


	inputSelect = function(b_setBehaviours) {

		// show if user details and delivery details are different.
		if(b_setBehaviours.value != $("billing" + b_setBehaviours.id).value) {
			  $$('tr.billingdetails').each(function(element) {
			      element.style.display = "";
			  });
			  // ensure that radio button is set to 'no'
			$('my_subscription').getInputs('radio','same_billing').find(function(radio) {return radio.value=='no'}).checked  = true; 

		}

		// handle the onchange event.
		b_setBehaviours.observe('change', function(currentEvent){

			// this enforces values change if billing details are same.
			if($('my_subscription').getInputs('radio','same_billing').find(function(radio) {return radio.value=='no'}).checked == false) {

				$("billing" + b_setBehaviours.id).value = b_setBehaviours.value;

			}

		});

	}

	countrySelect = function(currentElement, type) {
				currentElement.observe('change', function(currentEvent){
					if(currentElement.value!="United Kingdom") {
						$(type + 'form_region').value="International";
						$(type + 'hiddenregion').style.display = "none";

					} else {
						$(type + 'form_region').value="East England"
						$(type + 'hiddenregion').style.display = "";
					}
				});
			}

	// 




    if($('subscription_table')) {

	/*    */

	if($("form_country").value!="United Kingdom") {
		$("form_region").value="International";
		$("billingform_region").value="International";

		$("hiddenregion").style.display = "none";
	}
		
	  /* Show all billing details */

	  $$('tr.billingdetails').each(function(element) {
	      element.style.display = "none";
	  });

	/* loop through and check if same as billing details */

	$$('.input_subscription').each(function(element) {
			inputSelect(element);
	})
	
    	countrySelect($('form_country'),'');
    	countrySelect($('billingform_country'),'billing');

	$('my_subscription').getInputs('radio','same_billing').each(function(element) {
		element.observe('click', function(currentEvent) {
			var billingdetails = Form.getInputs('my_subscription','radio','same_billing').find(function(radio) { return radio.checked; }).value;
			
			if(billingdetails=="no") {
				$$('.input_subscription').each(function(element) {
							  $$('tr.billingdetails').each(function(element) {
							      element.style.display = "";
							  });
				})
			} else {

				// set all the same



				$$('.input_subscription').each(function(element) {
					$("billing" + element.id).value = element.value;
				});

				$$('tr.billingdetails').each(function(element) {
				element.style.display = "none";
				});
			}
		});
	});

     }
})
