$(document).ready(function(){
    
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	
    var evt = $.browser.msie ? "change" : "change";		// dropdown events need click in IE
	
    // On all pages, hide the open login form until clicked
    if ($("#login_open_1").length > 0)
    {
        $('#login_open_1, .login_open_2').hide();
        $('<div id="login_closed"><a href="myaccount.php">Login</a></div>').appendTo('#login');
        $('#login_closed a').hover(function(e){
            $('#login_closed').hide();
            $('#login_open_1, .login_open_2').show();
            $('#login').hover(function(){}, function(e){
                $('#login_open_1, .login_open_2').hide();
                $('#login_closed').show();
            });
        });
    }
	
    // Fix up broken login form layout on IE6
    /*if ($.browser.msie && $.browser.version == 6)
	{
		$('#loginpassword').css({left: '-51px'});
		$('#loginsubmit').css({top: '10px'});
	}*/
	
    if (sPage == 'forgotten.php') {
        $('#reminder_form').validationEngine({
            validationEventTriggers:"keyup blur"
        });
    }
	
    var regionddval = $('#regiondd').val();
	
    if (sPage == 'newprojects.php') {
        // Setup navigation dropdowns for project pages
        $('#regiondd').bind(evt, function(e){
            var thisval = $(this).val();
            if (thisval != regionddval)
            {
                window.location.href = 'newprojects.php?regionid='+thisval;
            }
        });
		
        $('#projectdd').bind(evt, function(e){
            $.scrollTo('#project_'+$(this).val(), {
                duration: 300
            });
        });
    }
	
    if (sPage == 'pastprojects.php') {
        // Setup navigation dropdowns for project pages
        $('#regiondd').bind(evt, function(e){
            var thisval = $(this).val();
            if (thisval != regionddval)
            {
                window.location.href = 'pastprojects.php?regionid='+thisval;
            }
        });
		
        $('#projectdd').bind(evt, function(e){
            $.scrollTo('#project_'+$(this).val(), {
                duration: 300
            });
        });
		
        setupGallery();
		
        if (window.location.href.match('#photouploaded')) {
            $.prompt('Thanks<br>Your photo has been uploaded successfully.<br>Please allow time for the admin to approve your image.');
        }
		
        if (window.location.href.match('#commentadded')) {
            $.prompt('Thanks<br>Your feedback has been posted successfully.<br>Please allow time for the admin to approve your comment.');
        }
        
        if (window.location.href.match('#commenterror')) {
            $.prompt('The reCAPTCHA was not entered correctly. Go back and try it again.');
        }
        
        $('#uploadphoto_form').hide();
        var upload_open = false;
        $('#uploadphoto').focus(function(e){
            this.blur();
        });
        $('#uploadphoto').click(function(){
            if (upload_open == true) {
                $('#uploadphoto_form').fadeOut();
                upload_open = false;
            } else {
                $('#uploadphoto_form').fadeIn();
                upload_open = true;
            }
        });
		
        $('#uploadphoto_form').validationEngine({
            validationEventTriggers:"keyup blur"
        });

		
        $('#addcomment_form').hide();
        $('<div class="floatLeft" style="margin: 0 0 20px 102px;"><a id="addcomment" href="">Add Comment</a></div>').insertAfter('h2#feedback');
        var addcomment_open = false;
        $('#addcomment').focus(function(e){
            this.blur();
        });
        $('#addcomment').click(function(e){
            e.preventDefault();
            if (addcomment_open == true) {
                $('#addcomment_form').fadeOut();
                addcomment_open = false;
            } else {
                $('#addcomment_form').fadeIn();
                addcomment_open = true;
            }
        });
		
        $('#addcomment_form').validationEngine({
            validationEventTriggers:"keyup blur"
        });
    }
	
    if (sPage == 'contact.php') {
        $('#contact_form').validationEngine({
            validationEventTriggers:"keyup blur"
        });
    }
	
    if (sPage == 'faq.php') {
		
        $('#faqs dd').hide();
        $('#faqs dt').click(function(){
            var c = $(this).attr('class');
            $('#faqs dd.' + c).animate({
                opacity: 'toggle'
            });
        });
    }
    
    
    if (sPage == 'myaccount.php') {
        
        setupMyAccountForm();
		
        $('#agree').click(function(){
            if ( $(this).attr('checked') == true ) {
                $('#register_btn').attr('disabled', null);
                $('#agree_notice').fadeOut();
            } else {
                $('#register_btn').attr('disabled', 'disabled');
                $('#agree_notice').fadeIn();
            }
        });
        if (window.location.href.match('#regsitererror')) {
            $.prompt('The reCAPTCHA was not entered correctly. Go back and try it again.');
        }
	
	
    }
	
    var categoryddval = $('#categorydd').val();
    var articleddval = $('#articledd').val();
	
    if (sPage == 'media.php') {
        var loc = location.search;
        var id 	= loc.indexOf('id=') > 0 ? loc.substring(loc.indexOf('id=') + 3) : '';
				
        // Setup navigation dropdowns
        $('#categorydd').bind(evt, function(e){
            var thisval = $(this).val();
            if (thisval != categoryddval)
            {
                window.location.href = 'media.php?category='+thisval;
            }
        });
		
        $('#articledd').bind(evt, function(e){
            if (!id)
            {
                $.scrollTo('#article_'+$(this).val(), {
                    duration: 300
                });
            }
            else
            {
                var thisval = $(this).val();
                if (thisval != articleddval)
                {
                    window.location.href = 'media.php#article_'+thisval;
                }
            }
        });
				
        $('#addcomment_form').hide();
        $('<div class="floatLeft" style="margin: 0 0 20px 90px;"><a id="addcomment" href="">Add Comment</a></div>').insertAfter('h2#comments');
        var addcomment_open = false;
        $('#addcomment').focus(function(e){
            this.blur();
        });
        $('#addcomment').click(function(e){
            e.preventDefault();
            if (addcomment_open == true) {
                $('#addcomment_form').fadeOut();
                addcomment_open = false;
            } else {
                $('#addcomment_form').fadeIn();
                addcomment_open = true;
            }
        });
		
        $('#addcomment_form').validationEngine({
            validationEventTriggers:"keyup blur"
        });
		
        setupGallery();
		
        if (window.location.href.match('#commentadded')) {
            $.prompt('Thanks<br>Your feedback has been posted successfully.<br>Please allow time for the admin to approve your comment.');
        }
        
        if (window.location.href.match('#commenterror')) {
            $.prompt('The reCAPTCHA was not entered correctly. Go back and try it again.');
        }
    }
});


function setupGallery() {
    var imgs = [];
    $('#gallery_table_inner img').each(function(){
        var img = $(this).attr('src');
        img = img.split('&image=');
        img = img[1];
		
        imgs.push(img);
    });
	
    $.preloadImages(imgs);
	
    $('#gallery_table_inner img').css('cursor', 'pointer');
    $('#gallery_table_inner img').click(function () {
        var url = this.src;
		
        url = url.split('&image=');
        url = url[1];
		
        $('#gallery_img').attr('src', url);
        $('#gallery_caption').text(this.alt);
    });
}

function galleryPage(num, total, projectID) {
    if (num == total) {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;" onclick="galleryPage(' + (num-1) + ',' + total + ',' + projectID + ');">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;">next &raquo;</a></span>');
    } else if (num == 1) {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;" onclick="galleryPage(' + (num+1) + ',' + total + ',' + projectID + ');">next &raquo;</a></span>');
    } else {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;" onclick="galleryPage(' + (num-1) + ',' + total + ',' + projectID + ');">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;" onclick="galleryPage(' + (num+1) + ',' + total + ',' + projectID + ');">next &raquo;</a></span>');
    }
	
    $('#gallery_thumbs').load('ajax_gallery.php', {
        page:num,
        id:projectID
    }, galleryLoaded);
}

function mediaGalleryPage(num, total, mediaID) {
    if (num == total) {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;" onclick="mediaGalleryPage(' + (num-1) + ',' + total + ',' + mediaID + ');">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;">next &raquo;</a></span>');
    } else if (num == 1) {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;" onclick="mediaGalleryPage(' + (num+1) + ',' + total + ',' + mediaID + ');">next &raquo;</a></span>');
    } else {
        $('#gallery_pagination').html('<span id="prev"><a href="javascript:;" onclick="mediaGalleryPage(' + (num-1) + ',' + total + ',' + mediaID + ');">&laquo; previous</a></span> page ' + num + ' of ' + total + ' <span id="next"><a href="javascript:;" onclick="mediaGalleryPage(' + (num+1) + ',' + total + ',' + mediaID + ');">next &raquo;</a></span>');
    }
	
    $('#gallery_thumbs').load('ajax_mediagallery.php', {
        page:num,
        id:mediaID
    }, galleryLoaded);
}

function galleryLoaded(responseText, textStatus, XMLHttpRequest) {
    //alert(responseText);
    setupGallery();
}


jQuery.preloadImages = function() {
    var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
    for(var i = a.length -1; i > 0; i--) {
        jQuery("<img>").attr("src", a[i]);
    }
}

function setupMyAccountForm() {
    // form validations
    $('#login_form').validationEngine({
        validationEventTriggers:"keyup blur"
    });
	
    $('#register_form').validationEngine({
        validationEventTriggers:"keyup blur change"
    });
    
    var loc = location.search;
    var pg = loc.substring(loc.indexOf('?'), loc.indexOf('&'));
	
    if (loc == '?edit') {
        // ONLY FOR 'EDIT' PAGE
		
        $('#editvolunteer_form').validationEngine({
            validationEventTriggers:"keyup blur change"
        });
		
        // calendar
        $('#dateOfBirth').datepick({
            mandatory:true,
            yearRange:'1900',
            dateFormat:'dd/mm/yy',
            showOn:'both',
            buttonImageOnly:true,
            buttonImage:'../datepick/calendar.gif',
            buttonText:'Select date'
        });
        $('#dateOfBirth').css("width","182px");
		
        if ($('#isPostSameAsHome').attr('checked') == true) {
            $('.postaladdress').hide();
        }
        $('#isPostSameAsHome').click(function(){
            if (this.checked == false) {
                $('.postaladdress').fadeIn(200);
            } else {
                $('.postaladdress').fadeOut(200);
            }
        });
		
        if ($('#dietaryRequirements').val() != 'OTHER') {
            $('#dietaryreqs').hide();
        }
        $('#dietaryRequirements').change(function(){
            if ($('#dietaryRequirements').val() == 'OTHER') {
                $('#dietaryreqs').fadeIn(200);
            } else {
                $('#dietaryreqs').fadeOut(200);
            }
        });
		
		
        if ($('#medical_yes').attr('checked') == false) {
            $('.medicalconditions, .q2').hide();
        }
        $('#medical_yes').click(function(){
            $('.medicalconditions').fadeIn(200);
			
            if ($('#medical_treatment').attr('checked') || $('#life_threatening').attr('checked')) {
                $('.q2').fadeIn(200);
            }
        });
        $('#medical_no').click(function(){
            $('.medicalconditions, .q2').fadeOut(200);
        });
		
        if ($('#medical_treatment').attr('checked') == false && $('#life_threatening').attr('checked') == false) {
            $('.q2').hide();
        }
        $('#medical_treatment').click(function(){
            if ($('#medical_treatment').attr('checked') == true || $('#life_threatening').attr('checked') == true) {
                $('.q2').fadeIn(200);
            } else {
                $('.q2').fadeOut(200);
            }
        });
        $('#life_threatening').click(function(){
            if ($('#medical_treatment').attr('checked') == true || $('#life_threatening').attr('checked') == true) {
                $('.q2').fadeIn(200);
            } else {
                $('.q2').fadeOut(200);
            }
        });
    // END OF 'EDIT' PAGE
		
    } else {
		
        // FOR ALL MY ACCOUNT PAGES
        // calendar
        $('#dateOfBirth').datepick({
            mandatory:true,
            yearRange:'1900',
            dateFormat:'dd/mm/yy',
            showOn:'both',
            buttonImageOnly:true,
            buttonImage:'datepick/calendar.gif',
            buttonText:'Select date'
        });
        $('#dateOfBirth').css("width","182px");
		
        $('.postaladdress').hide();
        $('#isPostSameAsHome').click(function(){
            if (this.checked == false) {
                $('.postaladdress').fadeIn(200);
            } else {
                $('.postaladdress').fadeOut(200);
            }
        });
		
        $('#dietaryreqs').hide();
        $('#dietaryRequirements').change(function(){
            if ($('#dietaryRequirements').val() == 'OTHER') {
                $('#dietaryreqs').fadeIn(200);
            } else {
                $('#dietaryreqs').fadeOut(200);
            }
        });
		
        $('.medicalconditions').hide();
		
        $('#medical_yes').click(function(){
            $('.medicalconditions').fadeIn(200);
        });
        $('#medical_no').click(function(){
            $('.medicalconditions').fadeOut(200);
        });
		
        $('.q2').hide();
        $('#medical_treatment').click(function(){
            if ($('#medical_treatment').attr('checked') == true || $('#life_threatening').attr('checked') == true) {
                $('.q2').fadeIn(200);
            } else {
                $('.q2').fadeOut(200);
            }
        });
        $('#life_threatening').click(function(){
            if ($('#medical_treatment').attr('checked') == true || $('#life_threatening').attr('checked') == true) {
                $('.q2').fadeIn(200);
            } else {
                $('.q2').fadeOut(200);
            }
        });
    }
	    
}

// when joining new projects and not logged in
function confirmLogin() {
    var txt = 'You must be logged in before joining a project.<br />Please click OK to login or register a new account.';
    $.prompt(txt, {
        buttons:{
            OK:true,
            Cancel:false
        },
        callback:function(v,m,f){
            if (v == true) {
                window.location = "myaccount.php";
            }
        }
    });
}

(function(){
    anchor = document.location.hash, handlers = [];

    jQuery.extend({
        anchorHandler: {
            add: function(regexp, callback) {
                if (typeof(regexp) == 'object') {
                    jQuery.map(regexp, function(arg){
                        args = {
                            r: arg[0],
                            cb: arg[1]
                            };

                    });
            }
            else  args = {
                r: regexp,
                cb: callback
            };
            handlers.push(args);
            return jQuery.anchorHandler;
        }
    }
    })(document).ready(function(){
    jQuery.map(handlers, function(handler){
        match = anchor.match(handler.r) && anchor.match(handler.r)[0] || false;
        if (match) handler.cb.apply(this, [match, (anchor || false)]);
    });
});
})();
