$(document).ready(function () {

    initFilterDropdowns();
    initNotableRepresenation();
    initHero();
    initConnectForm();
    initPeopleGallery();
    initHistory();
    initTracking();
    initModernizer();
    ClosePeopleGallery();

    $('#connectMethodPhone').bind('change', function () {
        $('.EmailMethod').hide();
        $('.PhoneMethod').show();
    });
    $('#connectMethodEmail').bind('change', function () {
        $('.PhoneMethod').hide();
        $('.EmailMethod').show();
    });

    if ($('#emailShareLink').length > 0) {
        $('#emailShareLink').fancybox();
    }
    //$('#fancyPop').fancybox();

    initVideoPlayer();

    // load adventure.js
    $.getScript("/App_themes/Default/JS/adventure.js", function () {

    });


});

var initModernizer = function () {
    if (!Modernizr.input.placeholder) {

        $('[placeholder]').focus(function () {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function () {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();
        $('input:submit').submit(function () {
            $(this).find('input,textarea').each(function () {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                }
            })
        });
    }
}

/*
Function: ValidateDisclaimer

Validates the contact form terms of use checkbox, called from .net customvalidator

Parameters: 

none
*/
function ValidateDisclaimer(source, arguments) {

    if ($('#cbDisclaimer:checked').length > 0) {
        arguments.IsValid = true;
    }
    else {
        arguments.IsValid = false;
        source.errormessage = "You must agree to the terms of use.";
    }
}

/*
Function: ValidateContactPreference

Validates the contact form contact preference field, this is called from the .net customvalidator control

Parameters: 

none
*/
function ValidateContactPreference(source, arguments) {

    if ($('#connectMethodPhone:checked').length > 0) {

        if ($('#txtPhone').val().length > 0 && $('#txtPhone').val() != "555-555-5555") {
            arguments.IsValid = true;
        }
        else {
            arguments.IsValid = false;
            source.errormessage = "Please provide a phone number, including area code.";
        }
    }
    else if ($('#connectMethodEmail:checked').length > 0) {
        var emailAddress = $('#txtEmail').val();
        if (emailAddress.length > 0 && emailAddress != "username@domain.com") {
            if (isValidEmailAddress(emailAddress))
            {
                arguments.IsValid = true;
            }
            else
            {
                arguments.IsValid = false;
                source.errormessage = "The email address you entered isn't valid. Please enter an email in this format: name@domain.com";
            }
        }
        else {
            arguments.IsValid = false;
            source.errormessage = "Please provide an email address.";
        }
    }
    else {
        arguments.IsValid = false;
        source.errormessage = "Please select a contact preference.";
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};


/*
Function: initOurPeopleFilter

Initializes Our People filter dropdowns

Parameters: 

none
*/
var initFilterDropdowns = function () {
    if ($('.filter').length > 0) {


        $('#form1').click(function (e) {
            $('.filter').children('.dropdown-options').removeClass('filterActive');
        });

        $('.filter-button').click(function (e) {
            e.stopPropagation();
            e.preventDefault();

            if ($(this).parent().children('.dropdown-options').hasClass('filterActive')) {
                $('.filter').children('.dropdown-options').removeClass('filterActive');
            }
            else {
                $('.filter').children('.dropdown-options').removeClass('filterActive');
                $(this).parent().children('.dropdown-options').addClass('filterActive');
            }
        });



    }
}

/*
Function: initNotableRepresenation

Initializes Notable representation accordian control

Parameters: 

none
*/
var initNotableRepresenation = function () {
    if ($('.accordion').length > 0) {
        $('.accordion a.accordLink').click(function (e) {
            e.preventDefault();

            //check if the clicked one is already open
            var close = false;
            if ($(this).parent().next().hasClass('ShowPanel')) {
                close = true;
            }

            //close other panels
            $('.accordion > div').each(function () {
                if ($(this).hasClass('ShowPanel')) {
                    $(this).prev().children().removeClass();
                    $('.accordion > div').slideUp('fast', function () {
                        $(this).removeClass('ShowPanel');
                    });
                }
            });

            if (!close) {
                $(this).addClass('current');
                $(this).parent().next().slideDown('fast', function () {
                    // Animation complete.
                    $(this).addClass('ShowPanel');
                });
            }
        });
    }
}


/*
Function: initPeopleGallery

Initializes People Gallery control

Parameters: 

none
*/
var initPeopleGallery = function () {
    $('.ContactCard a.ShowDialog').click(function (e) {
        e.preventDefault();
        if ($(this).next('.Dialog').is(':visible') != true) {
            $('.Dialog').hide();
            if ($(this).parent().position().left > 580) {
                $(this).next('.Dialog').addClass('Left');
            }
            $(this).next('.Dialog').show();
        } else {
            $(this).next('.Dialog').hide();
        }
    });
}

var ClosePeopleGallery = function () {
    $('.closeGallery').click(function (e) {
        e.preventDefault();
        $('.Dialog').hide();
    });
}

/*
Function: initHero

Initializes Hero control

Parameters: 

none
*/
var initHero = function () {

    if ($("#hero-wrapper").length > 0) {
        var play = true;
        $(".sfimagesList li:first").show();
        var controls = "";
        $(".sfimagesList li").each(function () {
            var altText = '';
            if ($(this).find("img").attr("alt") == undefined) { altText = " "; } else { altText = $(this).find("img").attr("alt"); }
            $(this).append("<h2>" + altText + "</h2>");
            controls = controls + "<li><a href=\"" + $(this).find("img").attr("src") + "\">" + "o" + "</a></li>";
        });
        $(".sfimagesList").parent().append("<ul id=\"controls\">" + controls + "</ul>");
        $("#controls a").click(function (e) {
            e.preventDefault();
            play = true;
            var url = $(this).attr("href");
            if (!$(".sfimagesList li a img[src=\"" + url + "\"]").parent().parent().is(':visible')) {
                $("#controls a").removeClass("selected");
                $(this).addClass("selected");
                $(".sfimagesList li").fadeOut("slow");
                $(".sfimagesList li a img[src=\"" + url + "\"]").parent().parent().fadeIn("slow");
            }
        });


        $("#controls a:first").addClass("selected");
        setInterval(function () {
            var current = $("#controls li a").index($(".selected"))
            var next = current + 1;
            if (next >= $("#controls li a").length) { next = 0 };
            if (play == true) {
                $("#controls li a")[next].click();
            }
        }, 5000);
	if ($('a[href*=".flv"]').length > 0) {
	        $("#hero-wrapper .sfimagesList").mouseover(function () {
        	    play = false;
	        });
	}
    }
}



/*
Function: initConnectForm

Initializes Connect With Us form.

Parameters:
    
none
*/
var initConnectForm = function () {

    if ($(".connect-form").length > 0) {

        //cancels out the .net validation summary control scrollto 0,0
        window.scrollTo = function () { }

        //text box click to open rest of form
        $('.connect-message').click(function () {
            $('#connect-details').slideDown('fast');
        });

        //hide form on cancel
        $('#connect-cancel').click(function (e) {
            e.preventDefault();
            $('#connect-details').slideUp('fast');
        });

        // applies classes to style hightlight border for form elements
        var connectFormElements = $("input,textarea");
        connectFormElements.focus(function () {
            connectFormElements.removeClass('focus');
            $(this).addClass("focus");

            $('.message-arrow').removeClass('focus');

            if ($("textarea").hasClass('focus')) {
                $('.message-arrow').addClass('focus');
            }

        });
    }

}

//error handling - adds a .error class to the input fields that are invalid
function BtnClick() {
    var val = Page_ClientValidate();
    if (!val) {
        var i = 0;
        for (; i < Page_Validators.length; i++) {
            if (!Page_Validators[i].isvalid) {
                $("#" + Page_Validators[i].controltovalidate).addClass("error");
            }
        }
    }
    return val;
}
/*
Function: initHistory

Initializes history slider.

Parameters:
    
none
*/
var initHistory = function () {
    var currentSlide = 1;
    var slideWidth = 700;
    var totalSlides = 5;
    var nudge = 57;
    var speed = 1000;




    // bind click actions for year controls
    $("#history-controls a").click(function (e) {
        e.preventDefault();
        $("#history-controls li.active").removeClass("active");
        $(this).parent().addClass("active");
        currentSlide = $(this).attr("id").replace("control-", "");
        var newOffset = parseInt((currentSlide * slideWidth) - slideWidth);
        var wrapperOffset = parseInt($(this).parent().parent().offset().left);
        var buttonOffset = parseInt($(this).offset().left - ($(this).parent().width()));

        if (buttonOffset < parseInt(27 + wrapperOffset)) {
            buttonOffset = 0;
        } else {
            if (buttonOffset > 1000) {
                nudge = 59;
            }
            else {
                nudge = 57;
            }
            buttonOffset = parseInt(buttonOffset + nudge - wrapperOffset);
        }
        //console.log(buttonOffset);
        $("#history-timeline").animate({
            left: "-" + newOffset + "px"
        }, speed, 'easeOutCubic');

        //        if (navigator.appName == 'Microsoft Internet Explorer') {
        //            $("#history-controls ul").animate({
        //                backgroundPositionX: buttonOffset + "px"
        //            }, speed, 'easeOutCubic');

        //            //console.log('helo');
        //        }
        //        else {

        //$("#history-controls ul").css("backgroundPosition", buttonOffset + "px 1px").animate({ backgroundPosition: (buttonOffset + "px 1px") }, speed, 'easeOutCubic');
        $("#history-controls ul").animate({ backgroundPosition: (buttonOffset + "px") }, speed, 'easeOutCubic');

        $("#history-controls ul li:not('.active') a").animate({
            color: "#353535"
        }
            , speed
            , 'easeOutCubic'
            );

        $("#history-controls ul li.active a").animate({
            color: "#ffffff"
        }
            , speed
            , 'easeOutCubic'
            );

        //$("#history-controls ul").css("background-position",buttonOffset + "px 3px");
        //      }

        if (currentSlide >= totalSlides) {
            $("#arrow-control-right").hide();
        } else {
            $("#arrow-control-right").show();
        }

        if (currentSlide <= 1) {
            $("#arrow-control-left").hide();
        } else {
            $("#arrow-control-left").show();
        }
    });

    //bind click actions for arrow controls
    $("#arrow-control-left").click(function (e) {
        e.preventDefault();
        if (currentSlide > 1) {
            var prevSlide = currentSlide - 1;
            $("#control-" + prevSlide).click();

        }
    });

    $("#arrow-control-right").click(function (e) {
        e.preventDefault();
        if (currentSlide < totalSlides) {
            var nextSlide = parseInt(currentSlide) + 1;
            $("#control-" + nextSlide).click();

        }
    });
    $("#arrow-control-right a").focus(function () {
        $(this).addClass("focus");
    });
    $("#arrow-control-right a").blur(function () {
        $(this).removeClass("focus");
    });

    $("#history-controls a:first").click();
}


/*
Function: initTracking

Initializes additional Google Analytics.

*/
var initTracking = function () {
    //external links
    $("a[href^='http:']").not("[href*='http://dewittross.com']").click(function (e) {
        _gaq.push(["_trackEvent", "ExternalLink", "Link", $(this).attr('href')]);
    });

    //PDFs
    $("a[href$='.pdf']").click(function (e) {
        _gaq.push(["_trackEvent", "PDF", "Download", $(this).attr('href')]);
    });

    //attorney finder
    initAjaxTracking();

    //vcard
    $('.VCard a').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "VCard-OurPeople", $(this).attr("href")]);
    });

    $('.IdCard a.button').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "VCard-Bio", $(this).attr("href")]);
    });

    //print bio
    $('#printBioLink').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "Print-Bio", $(this).attr("href")]);
    });

    //email bio
    $('#btnShareBioSubmit').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "Email-Bio", $('#emailShareLink').attr("href")]);
    });

}


var initAjaxTracking = function () {
    //attorney finder
    $('#alphaFinder ol li a').unbind();
    $('#alphaFinder ol li a').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "AttorneyFinderAlpha", $(this).text()]);
    });

    $('#expertiseFinder input').unbind();
    $('#expertiseFinder input').click(function (e) {
        _gaq.push(["_trackEvent", "Click", "AttorneyFinderExpertise", $('#expertiseFinder select option:selected').text()]);
    });
}

/*
Function: initVideoPlayer

Initializes Video Player.

Parameters:
none
*/
var initVideoPlayer = function () {

    $('a[href*=".flv"]').each(function (index) {

        // Set width and height of anchor that launches flowplayer, which determines player dimension
        var vHeight = $("img", this).height();
        var vWidth = $("img", this).width();

       //console.log("height: " + vHeight);
         //console.log("width: " + vWidth);

        if ($(this)) {

            var playerID = $(this).attr('id');
            //var trackerID = $(this).attr('tracker');

         //        console.log("playerId: " + playerID);
            //console.log("trackerId: " + trackerID);
            if (playerID != null) {
                $f(playerID, {

                    src: '/App_Themes/Default/flash/flowplayer.commercial-3.2.7.swf',
                    width: vWidth,
                    height: vHeight,
                    wmode: 'opaque',
                    version: [9, 115],
                    onFail: function () {
                        document.getElementById("info").innerHTML =
                    			"You need the latest Flash version to see MP4 movies. " +
                    			"Your version is " + this.getVersion()
                    		;
                    }
                }, {
                    key: '#$48000e479a7e5b4e230',
                    clip: {
                        autoBuffering: true,
                        accelerated: true,
                        bufferLength: 2,
						scaling: 'fit',
                        eventCategory: 'video',
                        onBegin: function () {
                            //console.log(playerID);
                            this.setVolume(100);
                        }
                    },
                    plugins: {
                        controls: {
                            url: '/App_Themes/Default/flash/flowplayer.controls-3.2.5.swf',
                            all: false,
                            play: true,
                            mute: true,
                            fullscreen: true,
                            scrubber: true,
                            time: true,
                            volume: true
                        },
                        gatracker: {
                            url: '/App_Themes/Default/flash/flowplayer.analytics-3.2.2.swf',
                            //debug: true,
                            events: {
                                all: true
                            },
                            trackingMode: 'Bridge',
                            accountId: 'UA-12131238-1'
                        }
                    }
                }).ipad();
            }
        };
    });

}
