$(document).ready(function(){

		  FB.init({
			    appId  : '175733105796486',
			    status : true, // check login status
			    cookie : true, // enable cookies to allow the server to access the session
			    xfbml  : true  // parse XFBML
			  });
	
		  //FB.init("143598535668856", "modules/mod_jconnector/xd_receiver.htm");
		  // appId  : '175733105796486'  //aujs.com.au
	//topnav login wizardry (demo)
	$('.headeraccount-actions .headeraccount-login').click(function () {
		$('.headeraccount-actions').slideUp(400);
		$('.headeraccount-form').slideDown(400);
		return false;
	});

	$('.headeraccount-form a').click(function () {
		var form = $('.headeraccount-form');
		form.submit();
		return false;
	});	
	$('.fb-connect').click(function () {
		return fbookConnect();
	});		
	

	/*$('.headeraccount-form a').click(function() {
		$('.headeraccount-form').slideUp(400);
		$('.headeraccount-links').slideDown(400);
	});*/	
	$('#header_login').example('Email');
	$('#header_pwd').example('Password');
	$('#tablesearch').example('Search');
	$('#events-list-search').example('Search');
	
	$('form.campus-signup-confirm .button-formsubmit').click(function() {
		var form = $(this).parents('form:first');
		form.submit();
		return false;
	});
	
	//WORKAROUND FOR STUPID IE'S STUPID LACK OF STUPID PSEUDO-SELECTOR SUPPORT 
	if ($.browser.msie) {
		//if the browser is Internet Explorer
		$('input[type="submit"]').addClass('submit');
		//find all elements matching a given selector and add a class to them
		$('input[type="text"]').addClass('text');
		$('input[type="hidden"]').addClass('hidden');
		$(':last-child').addClass('last-child');
		$(':first-child').addClass('first-child');
		$(':nth-child(2n)').addClass('nth-child-two');
		$(':nth-child(5n)').addClass('nth-child-five');
	//	showIEwarning();
   	}
   	
   	//gallery switcher 
	$('.gallerythumbs li a').click(function() {
		thisIMG = $(this).attr('href');
		$('.gallerymain img').attr('src', thisIMG);
		return false;
	});
	
	
   //	function showIEwarning() {
	//	$('body').prepend('<div class="iewarning"><div class="centraliser"><p>Hi there. We can see you&rsquo;re using Internet Explorer.</p><p>To get the full aujs.com.au experience, we  recommend you use <a href="http://google.com/chrome" title="Download Chrome">Google Chrome</a>, <a href="http://apple.com/safari" title="Download Safari">Apple Safari</a> or <a href="http://firefox.com" title="Download Firefox">Mozilla Firefox</a> instead.</p><p><a href="#closeiewarning">Close this message</a> or <a href="#disableiewarning">Never show it again</a>.</p></div></div>');
	//	$('.iewarning').slideDown(600);
	//}
	
	//$('.iewarning a[href="#closeiewarning"]').live('click',function() {
	//	$('.iewarning').slideUp(600);
	//	return false;
	//});
	//$('.iewarning a[href="#disableiewarning"]').live('click',function() {
	//	$('.iewarning').slideUp(600);
	//});
	
	//Form Validation!
	

	$("#campus-signup-form").submit(function () {
		 var action=$('input[name="action"]').val();
		 var email_address=$('input[name="email_address"]').val();
		 var email_address_checked=$('input[name="email_address_checked"]').val();
		 if (email_address==email_address_checked){
			 return true;
		 }
		 if (!action && email_address){
			 $.getJSON('ajax.php?action=checkUserEmailAddress&email_address='+email_address, function(data) {
				 if (data.result){
						$('p.intro').after('<p class="intro error">That email address '+data.email_address+' has already been used, or this person has already become a member.</p>');
						$('input[name="email_address"]').val('');
						$('input[name="email_address_checked"]').val('');
						$('body').animate({scrollTop:0}, 'slow');
						return false;
				 }
				 $('input[name="email_address_checked"]').val(data.email_address);
				 $("#campus-signup-form").submit();
			 });			 
		 }else{
			 return true; 
		 }
		 return false;
	});		
	$('.button-formsubmit').click(function() {

		//required fields checkermajigger
		
		//reset the error count
		errorcount = 0;
		$('p.error').remove();
		$('.error').removeClass('error');
		
		
		//for textboxes, textareas and selects
		$(this).parent().children('label:contains("*")').each(function() {
			//if a label has a * in it, and the next form element is empty
			if ($(this).next('input, select, textarea').val() == "" || $(this).next('fieldset').children('input, select, textarea').val() == "") {
				//add .error to the label
				$(this).addClass('error');
				
				//get the label's position (relative to the top)
				var offset = $(this).position();
				//var offset_correction = -80;
				var offset_correction = $('#offset_correction').html();
				//$(this).text(offset.top);
				
				//add .error to the field as well
				$(this).next('input, select, textarea').addClass('error');
				$(this).next('fieldset').children('input, select, textarea').addClass('error');
				
				//show an error message with <label> + "is required" (hidden by default)
				$(this).next('input, select, textarea').after('<p id="'+$(this).attr('for')+'_error" class="error" style="top:'+(offset.top-offset_correction)+'px;">'+$(this).text().replace('*','')+'  is required</p>');
				$(this).next('fieldset').children('input, select, textarea').after('<p class="error" style="top:'+(offset.top-offset_correction)+'px;">'+$(this).text().replace('*','')+'  is required</p>');
				
				//add one to the error count
				errorcount = errorcount + 1;
				
				//show all the error messages
				$('p.error').slideDown('slow');
			}
		});
		
		//check the error count
		if (errorcount === 0) {
			//all good - submit the form and carry on
			//$(this).text('huzzah!');
			var form = $(this).parents('form:first');
			form.submit();
		} else if (errorcount === 1) {
			//something's wrong.
			$('body').animate({scrollTop:0}, 'slow');
			$('p.intro').after('<p class="intro error">There is an error with the form. Please check that all the fields have been entered correctly.</p>');
		}	else if (errorcount > 1) {
			$('body').animate({scrollTop:0}, 'slow');
			$('p.intro').after('<p class="intro error">There are '+errorcount+' errors with the form. Please check that all the fields have been entered correctly.</p>');
		}	
		return false;
	});
	
	
	//topnav page identifier
    if ($('#topnav').length>0){
	    thisURL = window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1);
	    $('#topnav li a[href=\"'+thisURL+'\"]').parent().addClass('current');
	    if ($('#crumbs').length>0){
	    	$('#crumbs li a').each(function() {
	    		$('#topnav li a[href=\"'+$(this).attr('href')+'\"]').parent().addClass('current');
	    	});	
	    }
    }
	//sidenav page identifier
    if ($('#sidenav').length>0){
	    thisURL = window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1);
	    $('#sidenav li a[href=\"'+thisURL+'\"]').parent().addClass('current');
    }	
    
	//sidenav page identifier
    if ($('#sidenav').length>0){
	    //thisURL = window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1);
	    //thisURL = window.location;
	    //$('#sidenav li a[href=\"'+thisURL+'\"]').parent().addClass('current');
	    //$('body').addClass(thisURL);
		thisPage = location.href.substring((location.href.lastIndexOf("/"))+1);
	    if (thisPage.indexOf("?")>0){
			thisPage = thisPage.substring(0,thisPage.indexOf("?"));
		}
	    $('body').addClass(thisPage);
	}
      	//<ul id="crumbs">
    
    
	//clear errors if the form field is corrected
	//$('input.error, select.error, textarea.error').live('blur', function() {	
	$('input, select, textarea').blur(function(){
		if ($(this).hasClass('error') == false) {
			return;
		} else {
			if (!$(this).val()) {
				return;
			} else {
				this_id = $(this).attr('id');
				$('label[for="'+this_id+'"]').removeClass('error');
				$(this).removeClass('error');
				$('p#'+this_id+'_error.error').fadeOut(300);
			}
		}
	});
	if ($('#event_start_date').length>0){
		$('#event_start_date').datePicker({clickInput:true});
	}
	if ($('#event_end_date').length>0){
		$('#event_end_date').datePicker({clickInput:true});
	}
	if ($('#news_date').length>0){
		$('#news_date').datePicker({clickInput:true, startDate:'01/08/2010'});
	}
    if ($('#date_to_be_sent_date').length>0){
		$('#date_to_be_sent_date').datePicker({clickInput:true});
	}
    $('.addemailsection').live('click',function(){
    	var tools_tr=$(this).parent().parent();
    	var repeater_tr=tools_tr.prev();
    	var repeater=$('#repeater_html');
    	var repeater_html=repeater.html();
    	var id_string=repeater_tr.attr('id').replace('repeater_','');
    	var id=parseInt(id_string);
    	var next_id=id+1;
 
    	repeater_html=repeater_html.replace(/_id_/g,next_id)
    	tools_tr.after(repeater_html); 
    	   	
        CKEDITOR.config.stylesCombo_stylesSet = 'base_style';
        var hEd = CKEDITOR.instances['CKEditrepeater_'+next_id];
        if (hEd) {
            CKEDITOR.remove(hEd);
        }       
        var editorCKEdit = CKEDITOR.replace( 'CKEditrepeater_'+next_id,
                {
                    contentsCss : 'ckeditorcontent.css',
                    extraPlugins : 'uicolor',
                    toolbar : 'base_toolbar',
                    height : '150px',
                    width: '360px'										                        	
                });   
        $(this).hide();
    	return false;
    });
    
    $('.deleteemailsection').live('click',function(){
    	var tools_tr=$(this).parent().parent();
    	var repeater_tr=tools_tr.prev();
    	var id_string=repeater_tr.attr('id').replace('repeater_','');
    	var id=parseInt(id_string);   	
        var hEd = CKEDITOR.instances['CKEditrepeater_'+id];
        if (hEd) {
            CKEDITOR.remove(hEd);
        } 

    	tools_tr.remove();
    	repeater_tr.remove();

    	$('#regional-email-container .addemailsection:last').show();
    	return false;
    });    
	// HOME PAGE SLIDES
	$('#homeslides').cycle({  
		fx: 'scrollHorz',
		speed: 750,
		timeout: 9000,
		pause: 1,
		pager:  '#homeslidescontroller',
		pagerAnchorBuilder: function(idx, slide) { 
        	return '<li><a href="#slide'+idx+'">Slide '+idx+'</a></li>'; 
   		} 
  	});
  	
	// Footer SLIDES
	$('.logos').cycle({  
		fx: 'fade',
		random: 1,
		speed: 563,
		timeout:3500
  	});

	//On-campus signup form-specific wizardry
	
	//Have you been on an AUJS program before?
	previous_program = 'label[for="previous_id_program"], select#previous_id_program, label[for="program_when"], select#program_when';
	$(previous_program).hide();
	$('input#program_before_yes').click(function() {
		$(previous_program).slideDown('slow');
	});
	$('input#program_before_no').click(function() {
		$(previous_program).slideUp('slow');
	});
	if ($('input#program_before_yes').is(':checked')){
		$(previous_program).show();
	}	
	
	//Other Campus
	campus_other = 'label[for="id_campus_other"], input#id_campus_other';
	$(campus_other).hide();
	$('select#id_campus').change(function() {
		if ($(this).val() == "other") {
			$(campus_other).slideDown('slow');
			$('label[for="id_campus_other"]').append('*');
		} else {
			$(campus_other).slideUp('slow');
		}
	});
	
	//How did you find out about AUJS? (Other)
	find_out_other = 'label[for="id_find_out_details"], input#id_find_out_details';
	$(find_out_other).hide();
	$('select#id_find_out').change(function() {
		if ($(this).val() == "other") {
			$(find_out_other).slideDown('slow');
			$('label[for="id_find_out_details"]').append('*');
		} else {
			$(find_out_other).slideUp('slow');
		}
	});

	
});

function fbookConnect(){
	FB.login(function(response) {
		  if (response.session) {
		    if (response.perms) {
				 $.getJSON('ajax.php?action=fbookConnect', function(data) {
					 //insert code
					 //alert(data);
					 
				 });
				 window.location.reload();
		      // user is logged in and granted some permissions.
		      // perms is a comma separated list of granted permissions
				 return false;
		    } else {
		      // user is logged in, but did not grant any permissions
		    	return false;
		    }
		  } else {
		    // user is not logged in
			  return false;
		  }
		//}, {perms:'rsvp_event,user_events,read_stream,publish_stream,offline_access,user_photos,user_photo_video_tags'});
	}, {scope:'rsvp_event,user_events,read_stream,publish_stream'});
		return false;
}


function fbookDisconnect(){
	//TODO if user not logged in, login them in.
	 FB.api({method:'auth.revokeAuthorization'}, function(result) { 
		 $.getJSON('ajax.php?action=fbookDisconnect', function(data) {
			 //insert code
			 //alert(data);
			 window.location.reload();
		 });		  
		 
	 });
	return false;
}

