//history listener
function handleChange(evt){

	if(evt.pathNames[0]!=undefined){
	
		var section=evt.pathNames[0];
		
		if(section=='headlines'){
			loadPage('index.php?ajax=true');
		}
		if(section=='membership'){
			loadPage('membership.php');
		}
		if(section=='publications'){
			loadPage('publications_awards.php');
		}
		if(section=='events'){
			loadPage('events.php');
		}
		if(section=='about'){
			loadPage('about.php');
		}
	}
	
}

SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);




$(function() {				
	
	//gets the state of the browser
	//var State = History.getState();
	//console.log(State);
	//if(State.data.section=='main'){
	//	loadPage(State.data.url);
	//}
	
	
	//initialise navigation links
	$('#navigation a').each(function(index){
		/*
		$(this).bind('click', function(e) {	
			e.preventDefault();
			loadPage($(this).attr('href'));
		});
		*/
	});
	
	//initialise login dialog
	$("#loginbox").dialog({
		autoOpen: false,
		modal: true,
		width:290,
		height:250,
		buttons:{
			'Login':function(){
				login();
			}			
		}
	});
	//trigger the login when enter pressed
	$("#login_password").keyup(function(event){
	  if(event.keyCode == 13){
	    login();
	  }
	});

	
	//initialise login link in the header
	$('#header_login_link').click(function(e){
		e.preventDefault();
		$('#loginbox').dialog('open');
	});
	
	//initialise login link in the header
	$('#header_members_link').click(function(e){
		e.preventDefault();
		loadPage('members.php');
	});
	
	
	//configure the forgot password functionality
	$('#forgot_password_okay').dialog({
		autoOpen:false,
		modal:true,
		buttons:{
			'OK':function(){
				$(this).dialog('close');
			}
		}
	});
	
	$('#forgot_password_dialog').dialog({
		autoOpen: false,
		modal: true,
		buttons: {
			'Continue': function(){
				var win=$(this);
				$.ajax({
				  url: 'forgot_password.php',
				  type: 'post',
				  data: 'email='+$('#forgot_email').val(),
				  success: function(data) {
				  	if(data=='email_not_found'){
						alert('E-mail not found. Please try a different e-mail address.');				  	
				  	}else{
				  		win.dialog('close');
				  		$('#forgot_password_okay').dialog('open');
				  	}				    
				    
				  }
				});					
			}
		
		}
	});
	
	$('#login_forgot_link').click(function(){
		$("#forgot_password_dialog").dialog('open');		
	});
	
	//configure the mailing list functionality
	$('#login_mailing').click(function(){
		$("#mailing_list_dialog").dialog('open');		
	});
	
	$("#mailing_list_dialog").dialog({
		autoOpen: false,
		modal: true,
		width:600,
		buttons:{
			'Continue':function(){
				var win=$(this);
				var postdata='';
				var okay=true;
				$('.sendit').each(function(){
					if($(this).val()==''){
						$(this).focus();
						alert('All fields are required');
						okay=false;
						return false;
					}
					postdata+='&'+$(this).attr('name')+'='+$(this).val();
				});
				
				if(($('#mailing_email').val() != $('#mailing_email2').val()) || !validateEmail($('#mailing_email').val())){
					alert('Please check your email');
					okay=false;
				}
				
				
				
				if(okay){
					$.ajax({
						  url: 'mailing_list.php',
						  type: 'post',
						  data: postdata,
						  success: function(data) {
						  	
						  	if(data=='already_suscribed'){
								alert('Our records show that a person with your name and email address is already on the ISPIM mailing list. If you are certain that you are not on the mailing list, then please send an email to membership@ispim.org with your details. Otherwise, we have already your details, and you will continue to receive regular updates from ISPIM.');
						  	}else{
						  		win.dialog('close');
					  			$('#mailing_list_okay').dialog('open');								  	
						  	}
						  	
					  		
						  }
					});	
				}
			}
		}
	});
	
	
	
	
	//configure the forgot password functionality
	$('#mailing_list_okay').dialog({
		autoOpen:false,
		modal:true,
		buttons:{
			'OK':function(){
				$(this).dialog('close');
			}
		}
	});
	
	//enable dialog for nonmembers
	$("#become_member_dialog").dialog({
		autoOpen:false,
		modal:true,
		buttons:{
			'OK':function(){
				$(this).dialog('close');
			}
		}
	});
	
	
	initPage();
	$("#flash").delay(2000).fadeOut('slow');

});



//login function
function login(){
	var username=$('#login_username').val();
	var password=$('#login_password').val();
	$("#loginbox").mask('loading...');
	$.ajax({
		  url: 'login.php?username='+username+'&password='+password,
		  success: function(data) {
		  		$("#loginbox").unmask();
		  		if(data=='ok'){
		  			$('#header_login_link').fadeOut();
		  			$('#header_members_link').fadeIn();
		  			$("#loginbox").dialog('close');
		  			loadPage('members.php');
		  		}else{
		  			$('#login_password').css('background','#ff9d9d');
		  		}
		  }
	 });	
}


function refreshShareThis(){
	
	$("#sharethis").html('<span class="st_sharethis_button" id="share_this_button" st_url="'+ document.location.href + '" displayText="Share this Page"></span>');
	
	 stButtons.makeButtons();
     
}


function initPage(){
	$( "#tabs" ).tabs();
	$( "#subtabs" ).tabs();
	$( "#accordion" ).accordion({active:false,'clearStyle': true,'collapsible':true});
	
	
	//refresh sharethis
	refreshShareThis();
	
	$('#slider').nivoSlider({directionNav:false, controlNav:false, effect:'fade'});
	$('.slider').jshowoff({links:false, controls:false});
	
	
	//assign in-field labels
	$(':input[title]').each(function() {
	  var $this = $(this);
	  if($this.val() === '') {
	    $this.val($this.attr('title'));
	  }
	  $this.focus(function() {
	    if($this.val() === $this.attr('title')) {
	      $this.val('');
	    }
	  });
	  $this.blur(function() {
	    if($this.val() === '') {
	      $this.val($this.attr('title'));
	    }
	  });
	});
	
	
	

									
	$('.readMoreLink').click(function(e){
		e.preventDefault();
		var thisid=$(this).attr('id').split('_');
		thisid=thisid[1];
		openReadMore(thisid);										
	});	
	
	
	//check if the user is logged in before showing content
 	$('a.blocked').click(function(e){
 		e.preventDefault();
 		var dest=$(this).attr('href');
 		var target=$(this).attr('target');
 		var thislink=$(this);
 		$.ajax({
		  url: 'check_logged_in.php',
		  success: function(data) {
		  	//try with unbind click
		    if(data!='yes'){		    	
		    	$("#become_member_dialog").dialog('open');
		    }else{
		    	//$(this).unbind('click');
		    	//$(this).click();
		    	if(target=='_blank'){
		    		window.open(dest);
		    	}else{
		    		document.location=dest;
		    	}

		    	/*
		    	var link = document.createElement('<a>');
				link.href = dest;
				link.target = target;
				link.id = "newlink"
				$('#newlink').click();
				*/
		    	//$('<a target="' + target + '" href="' + dest + '"></a>').click();
		    	//document.location=dest;
		    }
		  }
		}); 		
 	});

	
	
}




function openReadMore(id){
	$('#readMoreLink_'+id).unbind('click');
	$('#readMoreLink_'+id+' span').html('close');
	$('#readMoreLink_'+id).click(function(e){
		e.preventDefault();
		var thisid=$(this).attr('id').split('_');
		thisid=thisid[1];
		closeReadMore(thisid);
	});
	$('#readMoreItem_'+id).fadeIn();
}

function closeReadMore(id){
	$('#readMoreLink_'+id).unbind('click');
	$('#readMoreLink_'+id+' span').html('read more');
	$('#readMoreLink_'+id).click(function(e){
		e.preventDefault();
		var thisid=$(this).attr('id').split('_');
		thisid=thisid[1];
		openReadMore(thisid);
	});
	$('#readMoreItem_'+id).fadeOut();
}



function slide_to(num){

	$('#slider').data('nivoslider').slideTo(num-1);

}


function loadPage(url){
	
	//highlights the proper button in the navigation
	$('#navigation a').removeClass('selected');
	$('#navigation a[href=\''+url+'\']').addClass('selected');
	
	//History.pushState({url:url,section:'main'}, "", "?tab="+url);
	
	$('#content').mask("Loading...");
	$.ajax({
	  url: url,
	  success: function(data) {
	  	
	  	$('#content').animate({ opacity: 0 },200,'linear',function(){
	  		$('#content').html(data);
	  		$('#content').animate({ opacity: 1 },200,'linear');
	  		//$('#content').fadeIn();
	  		$('#content').unmask();
	  		initPage();
	  	});
	    
	  }
	});	
}


function loadContent(url){
	
	$('#dynamic_content').mask("Loading...");
	$.ajax({
	  url: url,
	  success: function(data) {
	  	
	  	$('#dynamic_content').animate({ opacity: 0 },200,'linear',function(){
	  		$('#dynamic_content').html(data);
	  		$('#dynamic_content').animate({ opacity: 1 },200,'linear');
	  		//$('#content').fadeIn();
	  		$('#dynamic_content').unmask();
	  		initPage();
	  	});
	    
	  }
	});	
}

function validateEmail(elementValue){
	   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	   return emailPattern.test(elementValue);
}





function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}




