$(document).ready(function() {
	
	$(document).bind('mouseover',function(e){
		if(!$(e.target).closest("#header_menus").length) {
			$("#header_menus ul.menu_list:visible").slideUp('fast');
		}
	});
	
	var lightbox_autoplay = function(){
		var opts = opts || {};
		var A = {};
		A.start = function(o){
			opts = o || opts;
			var autoplay_delay = opts.delay || 10000;
			
			if(window.lightbox_autoplay && window.lightbox_autoplay!=null) {
				clearInterval(window.lightbox_autoplay);
			}
			window.lightbox_autoplay = setInterval(function(){
				var go_next = $(".jquery-lightbox-button-right:visible");
				if(go_next.length) {
					go_next.click();
				}
				else {
					window.lightbox_autoplay && clearInterval(window.lightbox_autoplay);
				}
			}, autoplay_delay);
			
			$(".jquery-lightbox-button-autoplay-play, .jquery-lightbox-button-autoplay-pause").remove();
			
			$("<a>",{
				'class': 'jquery-lightbox-button-autoplay-play',
				'href': 'javascript:void(0)'
			}).insertBefore(".jquery-lightbox-button-right");
			$("<a>",{
				'class': 'jquery-lightbox-button-autoplay-pause',
				'href': 'javascript:void(0)'
			}).insertBefore(".jquery-lightbox-button-right");
			$(".jquery-lightbox-button-autoplay-play").hide();
			
			return this;
		};
		A.stop = function(){
			if(window.lightbox_autoplay && window.lightbox_autoplay!=null) {
				clearInterval(window.lightbox_autoplay);
				window.lightbox_autoplay = null;
			}
			return this;
		};
		A.is_running = function(){
			return (window.lightbox_autoplay && window.lightbox_autoplay!=null ? true : false);
		};
		A.reset = function(o){
			opts = o || opts;
			$(".jquery-lightbox.autoplay_paused").removeClass("autoplay_paused");
			$(".jquery-lightbox-button-autoplay-play, .jquery-lightbox-button-autoplay-pause").remove();
		};
		
		return A;
	};
	
	var gallery_autoplay = lightbox_autoplay();

    // lightbox handler // move to the bottom
    $('.lightbox').lightbox({
		onBeforeLoad:function(opts,api){
		},
		onShow:function(opts,api){
			if($(opts.self).attr('rel')=="group" && $(opts.self).hasClass("autoplay")) {
				/*gallery_autoplay.start({
					delay: $(opts.self).attr("data-autoplay-delay") || null
				});*/
				gallery_autoplay.stop();
			}
		},
		onAppendHTML:function(opts,api){
			var content = $(".lightbox-inner-upper-html.video_desc",opts.self).text();
			if(content!=null && content!="") {
				return {
					width:$(".jquery-lightbox").width() + 160,
					height:$(".jquery-lightbox").height()+ (content.length>350 ? 200 : 170)
				};
			}
		},
		onComplete:function(opts,api){
			var content = $(".lightbox-inner-upper-html",opts.self).html();
			if(content!=null && content!="") {
				$("<div>", {
					'class': "jquery-lightbox-inner-upper-html",
					'html': content
				}).insertBefore($(".jquery-lightbox-html").children()[0]);
			}
		},
		onClose:function(opts,api){
			gallery_autoplay.stop().reset();
		}
	});
	
	// RESUME autoplay
	$(".jquery-lightbox-button-autoplay-play, .jquery-lightbox.autoplay_paused:visible img").live("click",function(){
		$(this).parents(".jquery-lightbox").removeClass("autoplay_paused");
		gallery_autoplay.start();
		$(".jquery-lightbox-button-autoplay-play").hide();
		$(".jquery-lightbox-button-autoplay-pause").show();
		return false;
	});
	// PAUSE autoplay
	$(".jquery-lightbox-button-autoplay-pause, .jquery-lightbox:visible:not(.autoplay_paused) img").live("click",function(){
		if( $("a.lightbox.autoplay").length && lightbox_autoplay().is_running ) {
			$(this).parents(".jquery-lightbox").addClass("autoplay_paused");
			$(".jquery-lightbox-button-autoplay-pause").hide();
			$(".jquery-lightbox-button-autoplay-play").show();
			gallery_autoplay.stop();
		}
		return false;
	});

    // menu handler
    //$('ul.mainmenu li').click(function() { // make this an id like this $(#).find(li)
    //    var menu = '#'+$(this).attr("id")+'menu';
    //    $(menu).slideDown('fast');
    //});


    $('.clicktoshop').click(function() {
        window.open('http://shop.britto.com/');
    });

    // menu handler
    $("#header_menus p.menu_title").live("click mouseover",function(e){
		var ul = $(this).parents("li").find("ul.menu_list");
		$("#header_menus ul.menu_list:visible").slideUp('fast');
		if(cssua.userAgent.mobile && e.type=="click") {
			ul.not(":visible").toggle('fast');
		}
		else {
			ul.not(":visible").toggle('fast');
		}
        return false;
    });
    $("#header_menus li.solo").live("mouseover",function(){
		$("#header_menus ul.menu_list").slideUp('fast');
		return false;
	});


    // FORMS -----------------------------

    // forms datepicker
    $('#purchasedate').datepicker({
		onClose: function() {
			validate_required_fields("form.validating:visible").check_all();
		}
    });
	$('#eventdate').datepicker({
		onClose: function() {
			validate_required_fields("form.validating:visible").check_all();
		}
    });
    $('#deadline').datepicker({
		onClose: function() {
			validate_required_fields("form.validating:visible").check_all();
		}
    });

    $('#donatedate').datepicker({
		onClose: function() {
			validate_required_fields("form.validating:visible").check_all();
		}
    });

    
    $('#collaborationdate').datepicker({
		onClose: function() {
			validate_required_fields("form.validating:visible").check_all();
		}
    });
    
    $('#donation_history_yes').click(function() {
    	$('#donation_history_item').show();
    	$('#donation_history_date').show();
    	$('#donation_minvalue').show();
    	$('#donation_maxvalue').show();
    	
    });
    
    $('#donation_history_no').click(function() {
    	$('#donation_history_item').hide();
    	$('#donation_history_date').hide();
    	$('#donation_minvalue').hide();
    	$('#donation_maxvalue').hide();

    });
    
    $('#auction_yes').click(function() {
    	$('#auction_item').show();    	
    });
    
    $('#auction_no').click(function() {
    	$('#auction_item').hide();    	
    });
    
    $('#collaboration_yes').click(function() {
    	$('#collaboration_item').show();    	
    });
    
    $('#collaboration_no').click(function() {
    	$('#collaboration_item').hide();    	
    });

    
    // subscription form
    $('#submit').click(function() {
        $('#subscribeform').submit();
    });

    // coa form
    $('#submitcoa1').click(function() {
		captcha_values();
		$('#coaform').ajaxSubmit({ dataType:'text', 
			success:function(json){
				var json = $.parseJSON(json);
				if(json.status && json.status=="success") {
					$(".contentgrp_c_righttextholder").slideUp('slow',function(){
						$('.contentgrp_c_righttextholder_ty').slideDown('slow');
					});
				}
				else {
					alert(json.error || "Sorry, could not submit form.");
				}
			}
		});
    });

    $('#submitcoa2, #submitcoa3').click(function() {
		if(validate_coa.validated() == false) {
			validate_coa.highlight();
			return false;
		}
		captcha_values();
		$('#coaform').ajaxSubmit({ dataType:'text', 
			success:function(json){
				var json = $.parseJSON(json);
				if(json.status && json.status=="success") {
					$(".contentgrp_c_righttextholder").slideUp('slow',function(){
						$('.contentgrp_c_righttextholder_ty').slideDown('slow');
					});
				}
				else {
					alert(json.error || "Sorry, could not submit form.");
				}
			}
		});
		return false;
    });

    // restorations form
    $('#submitrestorations').click(function() {
		if(validate_restoration.validated() == false) {
			validate_restoration.highlight();
			return false;
		}
		captcha_values();
		$('#restorationsform').ajaxSubmit({ dataType:'text', 
			success:function(json){
				var json = $.parseJSON(json);
				if(json.status && json.status=="success") {
					$(".contentgrp_c_righttextholder").slideUp('slow',function(){
						$('.contentgrp_c_righttextholder_ty').slideDown('slow');
					});
				}
				else {
					alert(json.error || "Sorry, could not submit form.");
				}
			}
		});
		return false;
    });

    // charities form
    $('#submitcharities').click(function() {
		if(validate_charities.validated() == false) {
			validate_charities.highlight();
			return false;
		}
		captcha_values();
		$('#charitiesform').ajaxSubmit({ dataType:'text', 
			success:function(json){
				var json = $.parseJSON(json);
				if(json.status && json.status=="success") {
					$(".contentgrp_c_righttextholder").slideUp('slow',function(){
						$('.contentgrp_c_righttextholder_ty').slideDown('slow');
					});
				}
				else {
					alert(json.error || "Sorry, could not submit form.");
				}
			}
		});
		return false;
    });

    // subscribe forms validation
    $('#subscribeform').validate({
        errorPlacement: function(error, element){
            $(element).attr({'title': error.append()});
        },
        highlight: function(element) {
            $(element).parentsUntil('.inputsholder').prev().prev().addClass("redlabel");

        },
        unhighlight: function(element) {
            $(element).parentsUntil('.inputsholder').prev().prev().removeClass("redlabel");

        },
        submitHandler: function(form) {
			captcha_values();
			$(form).ajaxSubmit({ dataType:'text', 
				success:function(json){
					var json = $.parseJSON(json);
					if(json.status && json.status=="success") {
						$(".contentgrp_a_righttextholder").slideUp('slow',function(){
							$('.contentgrp_a_righttextholder_ty').slideDown('slow');
						});
					}
					else {
						alert(json.error || "Sorry, could not submit form.");
					}
				}
			});
        }
    });

    // scrollpane handler
    $(function() { // get rid of
        $('.contentgrp_a_righttextholder').jScrollPane();
    });
    
    $(function() { // get rid of
        $('.contentgrp_c_righttextholder').jScrollPane();
    });

    $(function() { // get rid of
       $('.contentgrp_b_cont_text').jScrollPane();
    });

    $('.contentgrp_a_leftbigimages').innerfade({
        animationtype: 'fade',
	speed: 'normal',
	timeout: '10000',
	type: 'random',
	containerheight: 'auto',
	runningclass: 'innerfade'
    });

    $('div.first').innerfade({
        animationtype: 'fade',
	speed: 'normal',
	timeout: '10000',
	type: 'random',
	containerheight: '150px',
	runningclass: 'innerfade'
    });

    $('div.mid').innerfade({
        animationtype: 'fade',
	speed: 'normal',
	timeout: '10000',
	type: 'random',
	containerheight: '150px',
	runningclass: 'innerfade'
    });

    $('div.last').innerfade({
        animationtype: 'fade',
	speed: 'normal',
	timeout: '10000',
	type: 'random',
	containerheight: '150px',
	runningclass: 'innerfade'
    });
    
    window.scroll_inner = function(){
		$(".contentgrp_c_righttextholder").jScrollPane();
		captcha_img_refresh();
	};


// I'm pretty sure I can combine these into one function, but i'll do it later
    // forms handling
    var validate_coa = validate_required_fields("form#coaform");
    var validate_restoration = validate_required_fields("form#restorationsform");
    var validate_charities = validate_required_fields("form#charitiesform");
    
    $('#go_coa_step2').click(function() {
        $('#coa_step1').slideUp('slow',function() {$('#coa_step2').slideDown('slow');});
        
    });

    $('#go_coa_step3_a').click(function() {
		/*if(validate_coa.validated() == false) {
			validate_coa.highlight();
			return false;
		}*/
        $('#coa_step2').slideUp('slow',function() {
			$('#coa_step3_a').slideDown('slow',scroll_inner);
        });
        $('#artworktype').val('1');
    });

    $('#go_coa_step3_b').click(function() {
		/*if(validate_coa.validated() == false) {
			validate_coa.highlight();
			return false;
		}*/
        $('#coa_step2').slideUp('slow',function() {
			$('#coa_step3_b').slideDown('slow',scroll_inner);
		});
        $('#artworktype').val('2');
    });

    $('#go_coa_step3_c').click(function() {
		/*if(validate_coa.validated() == false) {
			validate_coa.highlight();
			return false;
		}*/
        $('#coa_step2').slideUp('slow',function() {
			$('#coa_step3_c').slideDown('slow',scroll_inner);
		});
        $('#artworktype').val('3');
    });

    $('.go_back_coa_step2').click(function() {
        var leavingdiv = $(this).parent().attr("id");;
        $('#'+leavingdiv).slideUp('slow',function() {$('#coa_step2').slideDown('slow');});
    });

    $('.submitcoa').click(function(){

       $('coaform').submit();
    });

    $('#go_restorations_step2').click(function() {
		if(validate_restoration.validated() == false) {
			validate_restoration.highlight();
			return false;
		}
        $('#restorations_step1').slideUp('slow',function() {
			$('#restorations_step2').slideDown('slow',scroll_inner);
		});
    });

    $('.go_back_restorations_step1').click(function() {
        var leavingdiv = $(this).parent().attr("id");;
        $('#'+leavingdiv).slideUp('slow',function() {$('#restorations_step1').slideDown('slow');});
    });

    $('#go_cand_step2').click(function() {
        $('#cand_step1').slideUp('slow',function() {$('#cand_step2').slideDown('slow');});
    });

    $('#go_cand_step3').click(function() {
		if(validate_charities.validated() == false) {
			validate_charities.highlight();
			return false;
		}
        $('#cand_step2').slideUp('slow',function() {
			$('#cand_step3').slideDown('slow',scroll_inner);
		});
    });

    $('.go_back_cand_step2').click(function() {
        var leavingdiv = $(this).parent().attr("id");;
        $('#'+leavingdiv).slideUp('slow',function() {$('#cand_step2').slideDown('slow');});
    });

    $('.submitcand').click(function(){
       $('candform').submit();
    });

    // searchbox stuff -------------------
    // searchbox text disappear
    $('#searchbox').focus(function() {
        $(this).val('');
    })

    // search submit
    $('#quicksearch').click(function(){
       $('#searchform').submit();
    });


// i'm sure I could make this into one function and limit the markup but for now this is it.
    // search results page

    $('#showmediaresults').click(function(){
        $('#thenewsresults').slideUp();
        $('#theeventresults').slideUp();
        setTimeout(function() {$('#themediaresults').slideDown('slow',function() {
            $(function() {
                var settings = {autoReinitialise: true};
                $('.resultswrapper').jScrollPane(settings);
            });
        });
        },1000);
        $('#showmediaresults').addClass('activesearch');
        $('#shownewsresults').removeClass('activesearch');
        $('#showeventresults').removeClass('activesearch');
    });

    $('#shownewsresults').click(function(){
        $('#themediaresults').slideUp();
        $('#theeventresults').slideUp();
        setTimeout(function() {$('#thenewsresults').slideDown('slow',function() {
            $(function() {
                var settings = {autoReinitialise: true};
                $('.resultswrapper').jScrollPane(settings);
            });
        });
        },1000);
        $('#showmediaresults').removeClass('activesearch');
        $('#shownewsresults').addClass('activesearch');
        $('#showeventresults').removeClass('activesearch');
    });

    $('#showeventresults').click(function(){
        $('#thenewsresults').slideUp();
        $('#themediaresults').slideUp();
        setTimeout(function() {$('#theeventresults').slideDown('slow',function() {
            $(function() {
                var settings = {autoReinitialise: true};
                $('.resultswrapper').jScrollPane(settings);
            });
        });
        },1000);
        $('#showmediaresults').removeClass('activesearch');
        $('#shownewsresults').removeClass('activesearch');
        $('#showeventresults').addClass('activesearch');
    });
    
    var got_event_prev_next = function(step){
		var step = step || null;
		if(step && window.pic_id_current && window.pics_in_year) {
			var index_curr = pics_in_year.indexOf(pic_id_current);
			var index_last = pics_in_year.length-1;
			var index_prev = index_curr - 1;
			var index_next = index_curr + 1;
			var first = pics_in_year[0];
			var last = pics_in_year[index_last];
			var prev = (index_prev<0 ? first : pics_in_year[index_prev]);
			var next = (index_next<0 ? last : pics_in_year[index_next]);
			var get_id = (step=="next" ? next : prev);
			return {go:step, id:get_id, curr:pic_id_current, first:first, last:last, prev:prev, next:next };
		}
		return false;
	};
    
    $("#next_event, #prev_event").live("click",function(){
		var go_step = $(this).attr('id').match(/next/) ? "next" : "prev";
		var event = got_event_prev_next(go_step);
		if(event) {
			var url = window.location.pathname.replace(/[0-9]+$/,'') + event.id + " #contentgrp_a";
			$("#contentgrp_a").load(url,function(){
				window.pic_id_current = event.id;
				//window.location.hash = "ve="+event.id;
				
                $(function() {
                var settings = {autoReinitialise: true};
                    $('.contentgrp_a_righttextholder').jScrollPane(settings);
                });

				$("#next_event, #prev_event").show();
				if(event.first==event.id) {
					$("#prev_event").hide();

				}
				if(event.last==event.id) {
					$("#next_event").hide();
				}
			});
		}
		return false;
	});
	if($("#next_event").length) {
		var event = got_event_prev_next("next");
		if(event && event.first!=event.curr) {
			$("#prev_event").show();
		}
		if(window.pics_in_year && window.pics_in_year.length==0) {
			$("#next_event, #prev_event").hide();
		}
	}
	
	$("img#captcha-refresh").live("click",function(){
		captcha_img_refresh();
		return false;
	});
	
	window.captcha_img_refresh = function(){
		$("#captcha:visible").attr('src', "/ajax/get_captcha?rnd=" + Math.random() );
	};
	
	window.captcha_values = function(f){
		$("input[name="+ (f||"captcha")+"]").val( $("input[name="+ (f||"captcha")+"]:visible").val() );
	};
	
	$("#search_navigation a[rel]").live("click",function(){
		var rel = $(this).attr('rel');
		$("#search_title").text(rel.toUpperCase() + " RESULTS");
		$("#search_results .results").hide().filter("#sr_"+rel).show();
		$("#search_results").jScrollPane();
		return false;
	});
	$("#search_results").jScrollPane();
	
	// capture a[href=#] links before it escapes to URL/#.
	$("a[href=#]").live("click.safe",function(){ return false; });

});

$(window).load(function() { // window.load -----

    placeFooter();
    if(homepagerotator == 1) {resizeBackground();placeContentContainer();homepageRotator();} else {resizeBackground_all();placeContentContainer_all()}
    if(galleryjs == 1) {galleryHandler();}
    if(eventsjs == 1) {eventsHandler();}
    if(eventcaljs == 1) {eventCalHandler();}
    if(eventssubgalleryjs == 1) {eventsSubGalleryHandler();}
    if(specialprojjs == 1) {specialProjHandler();}
    if(videosjs == 1) {videosHandler();}
    if(searchresults == 1) {showMediaResultsFirst();}
    if(newslettersjs == 1) {newsletterHandler();}
    
});

$(window).resize(function() { // window.refresh -----

    placeFooter();
    getSizes();
    if(homepagerotator == 1) {resizeBackground();placeContentContainer();} else {resizeBackground_all();placeContentContainer_all()}
    if(galleryjs == 1) {galleryHandler();}
    if(eventsjs == 1) {eventsHandler();}
    if(eventcaljs == 1) {eventCalHandler();}
    if(eventssubgalleryjs == 1) {eventsSubGalleryHandler();}
    if(specialprojjs == 1) {specialProjHandler();}
    if(videosjs == 1) {videosHandler();}
    if(searchresults == 1) {showMediaResultsFirst();}
    if(newslettersjs == 1) {newsletterHandler();}

});

LoadAfterJS = function(){
	$(function(){
		$("select, input:checkbox, input:radio, input:file").uniform();
	});
};

//

