$(document).ready(function() {
    if ($.browser.msie && $.browser.version < 6) {
        return false
    } else {
        $('ul.sf-menu').superfish({firstOnClick: true});
        var loopRSS = 0;
        var loopHomePic = 0;
        var loopSixty = 0;
        var loopExhibit = 0;
        var loopPhoto = 0;
        var loopAudience = 1;
        var changeValue = 2;
        var currentExhibit = 1;
        var $homePic = $(".cBlock .homePic");
        var $teamRight = $(".cBlock .team #teamRight img");
        var $rssFeed = $("#rssFeed div p");
        var $rssFeedMini = $("#miniRSS div ");
        var $sixtyQuotes = $(".aQuote");
        var $audienceRotator = $(".audience .audience-rotate .photos div");
        var $exhibit1 = $("#exhibit1 img");
        var $exhibit2 = $("#exhibit2 img");
        var $exhibit3 = $("#exhibit3 img");
        var $exhibit4 = $("#exhibit4 img");
        var $exhibit5 = $("#exhibit5 img");
        var $exhibit6 = $("#exhibit6 img");
        $(".noJS").addClass('hide');
        $(".filterCategory").css({
            'display': 'block'
        });
        $("#eventsContent h3").css({
            'display': 'block'
        });
        $("#eventsContent .filterDate a").addClass('showing');
        $("#eventsContent .filterCategory a").addClass('showing');
        $("#eventsContent a#filterAll").html("hide all");
        $(".research").click(function() {
            $(this).find(".noJS").slideToggle("fast")
        });
        $(window).scroll(function() {
            var scrollPosition = $(window).scrollTop();
            if (scrollPosition < 140) {
                $("#miniMenu").fadeOut('fast')
            } else {
                $("#miniMenu").fadeIn('fast')
            }
        });
        $("h3 a").click(function() {
            var chosenID = this.id;
            if (chosenID == "filterDate") {
                var otherID = "filterCategory"
            } else {
                var otherID = "filterDate"
            }
            if ($("." + chosenID).css("display") == "none") {
                $("." + otherID).slideToggle('fast',
                function() {
                    $("." + chosenID).slideToggle('fast')
                })
            }
            return false
        });
        $(".filterDate a, .filterCategory a").click(function() {
            var chosenID = this.id;
            $(".filterCategory a").removeClass("showing");
            $(".filterDate a").removeClass("showing");
            $("#eventsContent table:has(table):visible").fadeOut('fast',
            function() {
                $("#eventsContent table:has(table):hidden." + chosenID).fadeIn('fast')
            });
            if ($("#eventsContent table:has(table):visible").length == 0) {
                $("#eventsContent table:has(table):hidden." + chosenID).fadeIn('fast')
            }
            $("a#filterAll").html("show all");
            $(this).addClass('showing');
            return false
        });
        $("a#filterAll").click(function() {
            if ($(this).html() == "show all") {
                $("#eventsContent table:has(table):hidden").fadeIn('fast');
                $(".filterDate a").addClass('showing');
                $(".filterCategory a").addClass('showing');
                $(this).html("hide all")
            } else {
                $("#eventsContent table:has(table):visible").fadeOut('fast');
                $(".filterDate a").removeClass('showing');
                $(".filterCategory a").removeClass('showing');
                $(this).html("show all")
            }
            return false
        });
        window.setInterval(function() {
            $rssFeedMini.slice(loopRSS).fadeOut(300);
            $rssFeedMini.slice(loopRSS + 1, loopRSS + 2).fadeIn(300);
            $rssFeed.slice(loopRSS).fadeOut(300);
            $rssFeed.slice(loopRSS + 1, loopRSS + 2).fadeIn(300);
            loopRSS++;
            if (loopRSS + 2 > $rssFeed.size()) {
                loopRSS = 0
            }
        },
        4000);
        if ($audienceRotator.length > 0) {
            window.setInterval(function() {
                $(".ar" + loopAudience).fadeOut(600,
                function() {
                    if (loopAudience > 2) {
                        changeValue = -2
                    } else {
                        changeValue = 2
                    }
                    $(".ar" + (loopAudience + changeValue)).fadeIn(600,
                    function() {
                        loopAudience++;
                        if (loopAudience > 4) {
                            loopAudience = 1
                        }
                    })
                })
            },
            4000)
        }
        if ($homePic.length > 0) {
            window.setInterval(function() {
                $homePic.slice(loopHomePic).fadeOut(600);
                if (loopHomePic + 2 > $homePic.size()) {
                    loopHomePic = -1
                }
                $homePic.slice(loopHomePic + 1, loopHomePic + 2).fadeIn(600);
                loopHomePic++
            },
            5000)
        }
        if ($sixtyQuotes.length > 0) {
            window.setInterval(function() {
                $sixtyQuotes.slice(loopSixty).fadeOut(600);
                $sixtyQuotes.slice(loopSixty + 1, loopSixty + 2).fadeIn(600);
                loopSixty++;
                if (loopSixty + 2 > $sixtyQuotes.size()) {
                    loopSixty = -1
                }
            },
            15000)
        }
        if ($exhibit6.length > 0) {
            window.setInterval(function() {
                if (currentExhibit == 1) {
                    $exhibit1.slice(loopExhibit, loopExhibit + 1).fadeOut(300)
                } else if (currentExhibit == 2) {
                    $exhibit2.slice(loopExhibit, loopExhibit + 1).fadeOut(300)
                } else if (currentExhibit == 3) {
                    $exhibit3.slice(loopExhibit, loopExhibit + 1).fadeOut(300)
                } else if (currentExhibit == 4) {
                    $exhibit4.slice(loopExhibit, loopExhibit + 1).fadeOut(300)                    
                } else if (currentExhibit == 5) {
                    $exhibit5.slice(loopExhibit, loopExhibit + 1).fadeOut(300)                    
                } else {
                    $exhibit6.slice(loopExhibit, loopExhibit + 1).fadeOut(300)
                }
                loopExhibit++;
                if (loopExhibit + 1 > $exhibit1.size()) {
                    loopExhibit = 0;
                    if (currentExhibit == 1) {
	                    $("#exhibit2").css({
                            'z-index': '60'
                        });
                        $("#exhibit3").css({
                            'z-index': '50'
                        });
                        $exhibit3.slice(0).fadeIn(1);
                        currentExhibit = 2
                    } else if (currentExhibit == 2) {
	                    $("#exhibit3").css({
                            'z-index': '60'
                        });
                        $("#exhibit4").css({
                            'z-index': '50'
                        });
                       $exhibit4.slice(0).fadeIn(1);
                       currentExhibit = 3
                    } else if (currentExhibit == 3) {
	                    $("#exhibit4").css({
                            'z-index': '60'
                        });
                        $("#exhibit5").css({
                            'z-index': '50'
                        });
                       $exhibit5.slice(0).fadeIn(1);
                       currentExhibit = 4
                    } else if (currentExhibit == 4) {
	                    $("#exhibit5").css({
                            'z-index': '60'
                        });
                        $("#exhibit1").css({
                            'z-index': '50'
                        });
                       $exhibit6.slice(0).fadeIn(1);
                       currentExhibit = 5   
                   } else if (currentExhibit == 5) {
	                    $("#exhibit6").css({
                           'z-index': '60'
                       });
                       $("#exhibit1").css({
                           'z-index': '50'
                       });
                      $exhibit1.slice(0).fadeIn(1);
                      currentExhibit = 6                    
                    } else {
	                    $("#exhibit1").css({
                            'z-index': '60'
                        });
                        $("#exhibit2").css({
                            'z-index': '50'
                        });
                        $exhibit2.slice(0).fadeIn(1);
                        currentExhibit = 1
                    }
                }
            },
            1000)
        }
        if ($teamRight.length > 0) {
            window.setInterval(function() {
                $teamRight.slice(loopPhoto).fadeOut(600);
                $teamRight.slice(loopPhoto + 1, loopPhoto + 2).fadeIn(600);
                loopPhoto++;
                if (loopPhoto + 2 > $teamRight.size()) {
                    loopPhoto = 0
                }
            },
            4000)
        }
        $("#extraPop").addClass('hide');
        $("#extraPop2").addClass('hide');
		$('.registerPop').addClass('hide');
        $("#hear_about_us").change(function() {
            if ($("#hear_about_us").val() == "Other Website ->") {
                $("#extraPop").fadeIn('slow')
            } else {
                $("#extraPop").fadeOut('slow')
            }
        });
        $("#influence").change(function() {
            if ($("#influence").val() == "Other ->") {
                $("#extraPop2").fadeIn('slow')
            } else {
                $("#extraPop2").fadeOut('slow')
            }
        });
        $("#hear_about_event").change(function() {
            if ($(this).val() == "Conference brochure ->") {
                $(".registerPop").fadeOut('fast', function() {
	                $("#extraPopBrochure").fadeIn('fast');	
	                $("#extraPopBrochureInfo").fadeIn('fast');	
				});
            } else if ($(this).val() == "Web link ->") {
                $(".registerPop").fadeOut('fast', function() {
	                $("#extraPopWeb").fadeIn('fast');			
				});
            } else if ($(this).val() == "Email from association or institution ->") {
                $(".registerPop").fadeOut('fast', function() {
	                $("#extraPopAss").fadeIn('fast');			
				});
            } else if ($(this).val() == "Insert in publication ->") {
                $(".registerPop").fadeOut('fast', function() {
	                $("#extraPopPub").fadeIn('fast');			
				});
            } else if ($(this).val() == "Advert in publication ->") {
                $(".registerPop").fadeOut('fast', function() {
	                $("#extraPopPub").fadeIn('fast');			
				});
            } else {
                $(".registerPop").fadeOut('fast');				
            }
        });

        $("input[name='delegate_type']").click(function() {
            var type = this.id;
            if ((type == "delegate_type2") || (type == "delegate_type5")) {
                $("#chooseConference").fadeIn('slow');
                $("#chooseConference #choose2").fadeIn('fast');
                $("#chooseConference #choose3").fadeOut('fast');
                $("#chooseConference #chooseFree").fadeOut('fast')
            } else if ((type == "delegate_type3") || (type == "delegate_type6")) {
				if (($(this).val().substr(0,6)) == "I wish") {
	                $("#chooseConference").fadeIn('slow');
	                $("#chooseConference #choose2").fadeIn('fast');
	                $("#chooseConference #choose3").fadeIn('fast');					
	                $("#chooseConference #chooseFree").fadeIn('fast');					
				} else {
	                $("#chooseConference").fadeIn('slow');
	                $("#chooseConference #choose2").fadeIn('fast');
	                $("#chooseConference #choose3").fadeIn('fast');			
	                $("#chooseConference #chooseFree").fadeOut('fast')
				}
            } else {
                $("#chooseConference").fadeIn('slow');
                $("#chooseConference #choose2").fadeOut('fast');
                $("#chooseConference #choose3").fadeOut('fast')
                $("#chooseConference #chooseFree").fadeOut('fast')
            }
        });
        $("form").submit(function() {
            if (this.name == "brochure") {
                var thanks = "<h4>Thank you, we've received your information</h4>We will send you an email containing a link to the brochure when available."
            } else if (this.name == "uptodate") {
                var thanks = "<h4>Thank you, we've received your information</h4>Please use the following code to receive the £25 discount off your first event registration: <strong class=\"red\">update1</strong><br/>This code can only be used once. Only one discount can be used per event."
            } else if (this.name == "researchidea") {
                var thanks = "<h4>Thank you, we've received your information</h4>Your input will now help shape our future events."
            } else if (this.name == "informationpack") {
                var thanks = "<h4>Thank you, we've received your information</h4>We will contact you shortly."
            } else if (this.name == "friend") {
                var thanks = "<h4>Thank you, we've received your information</h4>Your friends have been sent an email with our details and your message."
            } else if (this.name == "register") {
                var thanks = "<h4>Thank you for your Registration</h4>You will receive an automatic email confirming your details and payment selections.<br/>We will then contact you via email within a few days to confirm your registration and payment details, please add <a href=\"mailto:bookings&#64;sbk-healthcare.co.uk\" title=\"Email the SBK Healthcare Bookings Team\">bookings&#64;sbk-healthcare.co.uk</a> to your safe list of email addresses to help to ensure you receive your registration and payment details.<script>document.getElementById('googleMessages').src='http://www.sbk-healthcare.com/thanks.html';</script>"
			} else if (this.name == "docsregister") {
                var thanks = "<h4>Thank you for your Documentation request</h4>You will receive an automatic email confirming your details and payment selections. We will be in contact over the next few days."
            } else if (this.name == "feedback2") {
                var thanks = "<h4>Thank you, we've received your feedback</h4>"
            }
            $("#ajaxResults").fadeOut('fast');
            var cancelForm = false;
            var inputs = [];
            var pleaseCheck = [];
            var errorType = "";
            if (this.name == "researchidea") {
                cancel = true;
                if ($("input[name='researchname']").val() == undefined) {
                    $(":input[name='interest[]']", this).each(function() {
                        if (this.checked == true) {
                            cancel = false
                        }
                    });
                    if (cancel != false) {
                        cancelForm = true;
                        errorType = "empty";
                        pleaseCheck.push(" relevant topics")
                    }
                }
            }
            if (this.name == "register") {
                if ($("input[@name='delegate_type']:checked").val() == undefined) {
                    errorType = "empty";
                    cancelForm = true;
                    pleaseCheck.push(" delegate type")
                }
                if ($("input[@name='tc_check']:checked").val() == undefined) {
                    errorType = "empty";
                    cancelForm = true;
                    pleaseCheck.push(" accept our terms and conditions")
                }
                if ($("#choose1").css("display") == "block") {
                    if ($("input[@name='chooseName1']").val() == "") {
                        $("input[@name='chooseName1']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" name of the first attendee")
                    } else {
                        $("input[@name='chooseName1']").removeClass('fail')
                    }
                    if ($("input[@name='chooseJob1']").val() == "") {
                        $("input[@name='chooseJob1']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" job title of the first attendee")
                    } else {
                        $("input[@name='chooseJob1']").removeClass('fail')
                    }
	                var str = $('input#chooseEmail1').val();
	                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
	                if (!filter.test(str)) {
	                    $('input#chooseEmail1').addClass('fail');
	                    emailValid = true;
	                    cancelForm = true;
	                    errorType = "email";
                        pleaseCheck.push(" valid email address of the first attendee")	                    
	                } else {
	                    $('input#chooseEmail1').removeClass('fail')
	                }
                }
                if ($("#choose2").css("display") == "block") {
                    if ($("input[@name='chooseName2']").val() == "") {
                        $("input[@name='chooseName2']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" name of the second attendee")
                    } else {
                        $("input[@name='chooseName2']").removeClass('fail')
                    }
                    if ($("input[@name='chooseJob2']").val() == "") {
                        $("input[@name='chooseJob2']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" job title of the second attendee")
                    } else {
                        $("input[@name='chooseJob2']").removeClass('fail')
                    }
	                var str = $('input#chooseEmail2').val();
	                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
	                if (!filter.test(str)) {
	                    $('input#chooseEmail2').addClass('fail');
	                    emailValid = true;
	                    cancelForm = true;
	                    errorType = "email";
                        pleaseCheck.push(" valid email address of the second attendee")	                    
	                } else {
	                    $('input#chooseEmail2').removeClass('fail')
	                }                    
                }
                if ($("#choose3").css("display") == "block") {
                    if ($("input[@name='chooseName3']").val() == "") {
                        $("input[@name='chooseName3']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" name of the third attendee")
                    } else {
                        $("input[@name='chooseName3']").removeClass('fail')
                    }
                    if ($("input[@name='chooseJob3']").val() == "") {
                        $("input[@name='chooseJob3']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" job title of the third attendee")
                    } else {
                        $("input[@name='chooseJob3']").removeClass('fail')
                    }
	                var str = $('input#chooseEmail3').val();
	                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
	                if (!filter.test(str)) {
	                    $('input#chooseEmail3').addClass('fail');
	                    emailValid = true;
	                    cancelForm = true;
	                    errorType = "email";
                        pleaseCheck.push(" valid email address of the third attendee")	                    
	                } else {
	                    $('input#chooseEmail3').removeClass('fail')
	                }                    
                }
                if ($("#chooseFree").css("display") == "block") {
                    if ($("input[@name='chooseNameFree']").val() == "") {
                        $("input[@name='chooseNameFree']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" name of the FREE fourth attendee")
                    } else {
                        $("input[@name='chooseNameFree']").removeClass('fail')
                    }
                    if ($("input[@name='chooseJobFree']").val() == "") {
                        $("input[@name='chooseJobFree']").addClass('fail');
                        errorType = "empty";
                        cancelForm = true;
                        pleaseCheck.push(" job title of the FREE fourth attendee")
                    } else {
                        $("input[@name='chooseJobFree']").removeClass('fail')
                    }
	                var str = $('input#chooseEmailFree').val();
	                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
	                if (!filter.test(str)) {
	                    $('input#chooseEmailFree').addClass('fail');
	                    emailValid = true;
	                    cancelForm = true;
	                    errorType = "email";
                        pleaseCheck.push(" valid email address of the third attendee")	                    
	                } else {
	                    $('input#chooseEmailFree').removeClass('fail')
	                }                            
                }
            }
            if (this.name == "friend") {
                var str1 = $('input#friend1_email').val();
                var str2 = $('input#friend2_email').val();
                var str3 = $('input#friend3_email').val();
                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
                for (i = 1; i <= 3; i++) {
                    if (eval("str" + i) != "") {
                        if (!filter.test(eval("str" + i))) {
                            $('input#friend' + i + '_email').addClass('fail');
                            emailValid = true;
                            cancelForm = true;
                            errorType = "email"
                        } else {
                            $('input#friend' + i + '_email').removeClass('fail')
                        }
                    }
                }
            }
            $(":input", this).each(function() {
                if ($(this).is('.required')) {
                    if (this.value == "") {
                        $(this).addClass('fail');
                        cancelForm = true;
                        pleaseCheck.push(" " + this.name);
                        errorType = "empty"
                    } else {
                        $(this).removeClass('fail')
                    }
                }
            });
            var formData = $("form").serialize();
            if (errorType != "empty") {
                var str = $('input#email').val();
                var filter = /^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i;
                if (!filter.test(str)) {
                    $('input#email').addClass('fail');
                    emailValid = true;
                    cancelForm = true;
                    errorType = "email"
                } else {
                    $('input#email').removeClass('fail')
                }
            }
            if (cancelForm != true) {
                $("#ajax").fadeIn('fast');
                $(".send").attr({
                    'value': 'sending',
                    'disabled': 'true'
                });
                $.ajax({
                    data: formData,
                    url: this.action,
                    type: 'post',
                    error: function() {
                        console.log("Failed to submit")
                    },
                    success: function(r) {
                        setTimeout(function() {
                            tempName = r.substr(0, 5);
                            if (tempName == "<!--S") {
                                $("#ajaxResults").addClass('success').html(thanks).fadeIn('slow');
                                $(".send").attr({
                                    'value': 'brochure request complete',
                                    'disabled': ''
                                });
                                $("#ajax").fadeOut('slow');
                                $(".formHide").addClass('hide')
                            } else {
                                $("#ajaxResults").removeClass().addClass('fail').html(r).fadeIn('slow');
                                $("#ajax").fadeOut('slow');
                                $(".send").attr({
                                    'value': 'send your request',
                                    'disabled': ''
                                })
                            }
                        },
                        2050)
                    }
                });
                return false
            } else {
                if (errorType == "empty") {
                    $("#ajaxResults").removeClass().addClass('fail').html("<h4>Sorry there was an error:</h4><strong>Please complete the following fields:</strong><br/>" + pleaseCheck).fadeIn('slow')
                }
                if (errorType == "email") {
                    $("#ajaxResults").removeClass().addClass('fail').html("<h4>Sorry there was an error:</h4><strong>You entered an invalid email address").fadeIn('slow')
                }
                return false
            }
        })
    }
});