function clearHints() {
    $("#Search").focus(function () {
        if (this.value == this.defaultValue) {
            this.value = "";
       } 
    }).blur(function () {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
}

function informForm() {

    $(".informed a").click(function () {
        $(this).toggleClass('open');
        $("#InformedForm").slideToggle(500, function () {
            $('html, body').animate({
                scrollTop: $(this).offset().top
            }, 500); //scrolls the page to the bottom so the user doesn't have to do it manually	 
        });
        return false;
    });
}

function informedFormClosed() {

    $("#module-submitted-link").click(function () {

        $(".informed a").trigger('click');
        showContactForm();
        return false;

    });
}

function videoLibrary() {

    flowplayer("player", "/assets/swfs/flowplayer-3.2.7.swf", {

        canvas: {
            backgroundColor: "#d9e6e9"
        },

        screen: {
            width: 463, height: 296, top: 0, right: 0
        },

        plugins: {
            controls: {
                autoHide: "never",
                sliderGradient: 'none',
                timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
                backgroundGradient: 'none',
                progressColor: '#7a949b',
                tooltipTextColor: '#fcb034',
                bufferColor: '#445566',
                volumeColor: '#ffffff',
                volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
                timeSeparator: ' ',
                sliderColor: '#000000',
                sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
                volumeSliderGradient: 'none',
                buttonColor: '#ffffff',
                bufferGradient: 'none',
                buttonOverColor: '#ffffff',
                backgroundColor: '#2a4a5f',
                durationColor: '#a3a3a3',
                volumeSliderColor: '#ffffff',
                timeColor: '#ffffff',
                buttonOffColor: 'rgba(130,130,130,1)',
                borderRadius: '0px',
                timeBgColor: 'rgb(0, 0, 0, 0)',
                progressGradient: 'none',
                tooltipColor: '#2a4a5f',
                height: 32,
                opacity: 1
            }
        },
        clip: {
            autoPlay: false,
            autoBuffering: false
        }
    });

    //$f("player", "/assets/swfs/flowplayer-3.2.7-0.swf", { clip: { autoPlay: false, autoBuffering: true} });
    $(".playlist ul li:nth-child(1) a").addClass("playing");

    $(".playlist a").click(function () {

        if ($(this).hasClass("playing")) {
            return false; //don't wanna do anything if the video is already playing
        } else {
            $(this).addClass("playing").parents("li").siblings().children("a").removeClass("playing");
            var index = $(".playlist a").index(this);
            var videoPlaylist = CreativeLynx.VideoGallery.Playlist;
            var vidToPlay = videoPlaylist[index];
            $("#selectedVideo h2").html(vidToPlay.Title);
            $("#selectedVideo .desc").html(vidToPlay.Description);
            $f().play(vidToPlay.VideoUrl);
            return false;
        }
    });

    $(".playlist").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        speed: 300,
        visible: 3,
        vertical: true,
        circular: false
    });

    $("a.prev, a.next").click(function () {
        return false;
    });
}

function formValidation() {

    var checkboxes = $('.require-one');
    var checkbox_names = $.map(checkboxes, function (e, i) {
        return $(e).attr("name");
    }).join(" ");

    $("#InformedForm").validate({
        groups: {
            checks: checkbox_names
        },
        errorPlacement: function (error, element) {
            if (element.attr("type") == "checkbox") error.insertAfter(checkboxes.last());
            else error.insertAfter(element);
        },
        submitHandler: function () {

            var formObj = buildSubmitForm();

            $.ajax({
                url: "/webservices/ContactService.asmx/ContactForm",
                dataType: 'json',
                contentType: "application/json",
                type: "POST",
                data: JSON.stringify(formObj),
                success: function () {

                    hideContactForm();

                }
            });
        }
    });

    $.validator.addMethod('require-one', function (value) {
        return $('.require-one:checked').size() > 0;
    }, 'Please choose at least one');

    $.validator.addMethod("OtherText", function (value, element) {
        return !($('input.othercheckbox:first').attr("checked") && !value);
    });

}

function hideContactForm() {

    $('#InformedForm').removeClass('normalForm');
    $('#InformedForm').addClass('submittedForm');

    $('#module-informed-normal').hide();
    $('#module-informed-submitted').show();

    $('#contact-form-submit').hide();
    $('#contact-form-confimration').show();
}


function showContactForm() {

    $('#InformedForm').removeClass('submittedForm');
    $('#InformedForm').addClass('normalForm');

    $('#module-informed-normal').show();
    $('#module-informed-submitted').hide();

    $('#contact-form-submit').show();
    $('#contact-form-confimration').hide();
}

function buildSubmitForm() {

    var form = {
        firstName : $(contactFirstNameId).val(),
        surname: $(contactSurnameId).val(),
        company: $(contactCompanyId).val(),
        email: $(contactEmailId).val(),
        biomedical: $(contactBioMedicalId).attr('checked'),
        offshore: $(contactOffshoreId).attr('checked'),
        carbon: $(contactCarbonlId).attr('checked'),
        manufacture: $(contactManufactureId).attr('checked'),
        knowledge: $(contactKnowledgeId).attr('checked'),
        other: $(contactOtherId).attr('checked'),
        otherText:  $(contactOtherTextId).val()
    };
    
    return form;
};

function moduleAnimation() {
    $(".JQ #ModuleContainer .module").each(function () {
        var endPos = $(this).position().top; //get css top pos of each module
        if ($(this).hasClass("row2")) {
            var startPos = parseInt(endPos - 60); //reset top pos, convert string to int, minus px for new pos
            $(this).css({
                "top": startPos
            }).animate({
                opacity: 1,
                top: endPos
            }, 600);
        } else {
            var startPos = parseInt(endPos - 30);
            $(this).css({
                "top": startPos
            }).animate({
                opacity: 1,
                top: endPos
            }, 500);
        }
    });
}


function rightColAnimation() {

    $("#MainBreakout .spotlight, #MainBreakout .imggal, #MainBreakout #Press, #MainThreeCol .spotlight, #MainThreeCol .imggal, #MainThreeCol #Press").css({ 'opacity': '0', 'margin-top': '-50px' });

    if ($('#MainBreakout .inner-right').length) {

        //console.log('breakout layout');

        if ($('.no-image-gallery').length || $('.only-widget').length || $('.no-featuredpage-widget').length) {

            //console.log('a widget is missing');
            
            $('.no-featuredpage-widget').animate({
                opacity: 1,
                marginTop: 22
            }, 600);

            $('.no-image-gallery').animate({
                opacity: 1,
                marginTop: 22
            }, 700);

            if ($('.only-widget').length) {
                $('.only-widget').animate({
                    opacity: 1,
                    marginTop: 22
                }, 700);

            }

            else {
                $('#Press').animate({
                    opacity: 1,
                    marginTop: 0
                }, 900);
             }
        }

        else {

           //console.log('all widgets are present');

            $('.spotlight').animate({
                opacity: 1,
                marginTop: 0
            }, 600);

            $('.imggal').animate({
                opacity: 1,
                marginTop: 78
            }, 700);

            $('#Press').animate({
                opacity: 1,
                marginTop: 0
            }, 900);

        }

    }//if mainbreakout innerright

    else if ($('#MainThreeCol .inner-right').length) {

       // console.log('three col');

        if ($('.no-image-gallery').length || $('.no-featuredpage-widget').length) {

            //console.log('a widget is missing');

            $('.no-featuredpage-widget').animate({
                opacity: 1,
                marginTop: 0
            }, 600);

            $('.no-image-gallery').animate({
                opacity: 1,
                marginTop: 0
            }, 700);

        }

        else {


            $('.spotlight').animate({
                opacity: 1,
                marginTop: 20
            }, 600);

            $('.imggal').animate({
                opacity: 1,
                marginTop: 0
            }, 700);

            $('#Press').animate({
                opacity: 1,
                marginTop: 20
            }, 600);

        }


    }//else if mainthreecol

}



function imgGal() { //img gallery widget in right hand column
    $(".imggal .thumbs a").click(function () {
        var image = $(this).attr("href");
        $(this).addClass("active").siblings("a").removeClass("active");
        $('.imggal #Selected').hide().html('<img src="' + image + '"/>').fadeIn('slow');
        return false;
    });
}

function tweets() {
    $("#tweet").tweet({
        username: "investinwirral",
        count: 1,
        loading_text: "loading tweets...",
        template: "{text} {time}"
    });
    window.setTimeout(function () {
        $('#tweet a').attr('target','_blank');
    }, 1500); 
}

$(document).ready(function () {

    /* Go to LinkedIn address */
    $("#LinkedIn").click(function (e) {
        e.preventDefault();
        var newWin = window.open('', '_blank');
        newWin.location = 'http://www.linkedin.com/groups?gid=4194009&mostPopular=&trk=tyah';
        //blank.location.href = 'http://www.linkedin.com/groups?gid=4194009&mostPopular=&trk=tyah';
    });

    $("#InformedForm").hide();
    $("html").removeClass("no-js").addClass("JQ");
    rightColAnimation();
    imgGal();
    clearHints();
    informForm();
    informedFormClosed();
    formValidation();
    $('a.print').click(function () {
        window.print();
        return false;
    });
    if ($("a#player").length) {

        flowplayer("player", "/assets/swfs/flowplayer-3.2.7.swf", {

            canvas: {
                backgroundColor: "#d9e6e9"
            },

            screen: {
                width: 384, height: 216, top: 0, right: 0
            },

            plugins: {
                controls: {
                    autoHide: "never",
                    sliderGradient: 'none',
                    timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
                    backgroundGradient: 'none',
                    progressColor: '#7a949b',
                    tooltipTextColor: '#fcb034',
                    bufferColor: '#445566',
                    volumeColor: '#ffffff',
                    volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
                    timeSeparator: ' ',
                    sliderColor: '#000000',
                    sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
                    volumeSliderGradient: 'none',
                    buttonColor: '#ffffff',
                    bufferGradient: 'none',
                    buttonOverColor: '#ffffff',
                    backgroundColor: '#2a4a5f',
                    durationColor: '#a3a3a3',
                    volumeSliderColor: '#ffffff',
                    timeColor: '#ffffff',
                    buttonOffColor: 'rgba(130,130,130,1)',
                    borderRadius: '0px',
                    timeBgColor: 'rgb(0, 0, 0, 0)',
                    progressGradient: 'none',
                    tooltipColor: '#2a4a5f',
                    height: 32,
                    opacity: 1
                }
            },
            clip: {
                autoPlay: true,
                autoBuffering: true
            }
        });
    }

    if ($("#tweet").length) {
        setTimeout(
				 "tweets();", 1500
			)
    }

    if ($(".video-gallery").length) {
        videoGallery();
    }
    if ($("#Press").length) {
        $("#Press").jCarouselLite({
            btnNext: "#Press .next",
            btnPrev: "#Press .prev",
            auto: 5000,
            speed: 300,
            visible: 1
        });
    }

    if ($("#MainBreakout .related, #MainThreeCol .related, #Main .related,").length) {
        $(".related").jCarouselLite({
            btnNext: ".related .next",
            btnPrev: ".related .prev",
            speed: 300,
            visible: 2
        });
    }

    if ($("#MainGallery .related").length) {
        $(".related").jCarouselLite({
            btnNext: ".related .next",
            btnPrev: ".related .prev",
            speed: 300,
            visible: 4
        });
    }

    if ($(".lightbox-img a[rel^='shadowbox']").length) {
        Shadowbox.init({
            overlayColor: "#2A4A5F",
            overlayOpacity: "0.9"
        });
    }
    if ($("#selectedVideo").length) {
        videoLibrary();
    }
    var pathname = window.location.pathname,
        pathname = pathname.replace("/", ""),
        pathname = pathname.split(".");

    if (pathname == ",") {
        $("html").addClass("index");
    } else {
        $("html").addClass(pathname[0]);
    }
    $('input.othercheckbox').live('change', function () {
        showOtherTextField();
    });
    moduleAnimation();



});

function showOtherTextField() {
    $('#ofield').toggleClass('s-h-o');

}

function videoGalleryHome() {

    flowplayer("home-vid", {
        src: '/assets/swfs/flowplayer-3.2.7.swf',
        wmode: 'opaque'
    }, {

        canvas: {
            backgroundColor: "#d9e6e9"
        },

        screen: {
            width: 384, height: 216, top: 0, right: 0
        },

        plugins: {
            controls: {
                autoHide: "never",
                sliderGradient: 'none',
                timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
                backgroundGradient: 'none',
                progressColor: '#7a949b',
                tooltipTextColor: '#fcb034',
                bufferColor: '#445566',
                volumeColor: '#ffffff',
                volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
                timeSeparator: ' ',
                sliderColor: '#000000',
                sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
                volumeSliderGradient: 'none',
                buttonColor: '#ffffff',
                bufferGradient: 'none',
                buttonOverColor: '#ffffff',
                backgroundColor: '#2a4a5f',
                durationColor: '#a3a3a3',
                volumeSliderColor: '#ffffff',
                timeColor: '#ffffff',
                buttonOffColor: 'rgba(130,130,130,1)',
                borderRadius: '0px',
                timeBgColor: 'rgb(0, 0, 0, 0)',
                progressGradient: 'none',
                tooltipColor: '#2a4a5f',
                height: 32,
                opacity: 1
            }
        },
        clip: {
            url: $("#pool a:first").attr("href"),
            autoPlay: true,
            autoBuffering: true,
            onBeforeFinish: function () {
                // loop clip by not finishing it
                return false;
            }
        }
    });

    var links = document.getElementById("pool").getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function () {
            $f().play(this.getAttribute("href", 2));
            var title = $(this).attr("title");
            $(this).addClass("active").siblings().removeClass("active");
            if (title == "") {
                $("#homeSelectedVideo h2").hide(); //don't show title if empty
            } else {
                $("#homeSelectedVideo h2").show().html("<span>" + title + "</span>");
            }

            return false;
        }
    }
}
