/* Gallery (fade-on-click, auto-fade) */
jQuery.fn.gallFade = function (_options) {
    // defaults options	
    var _options = jQuery.extend({
        duration: 700,
        autoSlide: 5000
    }, _options);

    return this.each(function () {
        var _hold = $(this);
        var _btnPrev = _hold.find('li.link-prev > a');
        var _btnNext = _hold.find('li.link-next > a');
        var _speed = _options.duration;
        var _timer = _options.autoSlide;
        var _wrap = _hold.find('ul');
        var _el = _hold.find('ul > li');
        var _count = _el.index(_el.filter(':last')) - 2;
        var _w = _el.outerWidth();
        var _wrapHolderW = Math.ceil(_wrap.parent().width() / _w);
        var _active = 0;
        function scrollEl() {
            _wrap.eq(0).animate({
                left: -(_w * _active) + "px"
            }, { queue: false, duration: _speed });
        }
        _btnNext.click(function () {
            if (_time) clearTimeout(_time);
            if (_active < _count - 1) {
                _active++;
                scrollEl()
                _btnPrev.addClass('active');
                _btnNext.addClass('active');
            }
            else {
                if (_active < _count) {
                    _active++;
                    scrollEl()
                    _btnPrev.addClass('active');
                    _btnNext.removeClass('active');
                }
            }
            timeGo()
            return false;
        })
        _btnPrev.click(function () {
            if (_time) clearTimeout(_time);
            if (_active > 1) {
                _active--;
                scrollEl()
                _btnPrev.addClass('active');
                _btnNext.addClass('active');
            }
            else {
                if (_active > 0) {
                    _active--;
                    scrollEl()
                    _btnPrev.removeClass('active');
                    _btnNext.addClass('active');
                }
            }
            timeGo()
            return false;
        })

        _timesrun = 0;
        function timeGo() {
            _time = setInterval(function () {

                if (_active < _count - 1) {
                    _active++;
                    scrollEl();
                    _btnPrev.addClass('active');
                    _btnNext.addClass('active');
                    if (_active == 0) _btnPrev.removeClass('active');
                    if (_timesrun == 1) clearInterval(_time);
                }
                else {
                    if (_active < _count) {
                        _active++;
                        scrollEl();
                        _btnPrev.addClass('active');
                        _btnNext.removeClass('active');
                        _active = -1;
                        _timesrun++;
                    }
                }
            }, _timer);
        }
        timeGo();
    });
}
$(document).ready(function () {
    // set up the home page gallery
    $('div.gallery-fade').gallFade({
        duration: 700,
        autoSlide: 15000
    });

    // navigation effect
    speed = 500;
    $('#nav li').hover(
	    function () {
	        if ($(this).hasClass('active')) return; // don't do animation for active item

	        text = $(this).find('.text');
	        text.animate({ "marginTop": "-=105px" }, speed);

	        // move the number off to the left
	        number = $(this).find('.number');
	        number.animate({ "marginLeft": "-=100px" }, speed);
	    },
	    function () {
	        if ($(this).hasClass('active')) return; // don't do animation for active item

	        text = $(this).find('.text');
	        text.animate({ "marginTop": "+=105px" }, speed);

	        // move the number off to the left
	        number = $(this).find('.number');
	        number.animate({ "marginLeft": "+=100px" }, speed);

	        text.removeAttr("style");
	        number.removeAttr("style");
	    }
	);

    $.preloadImages("../images/bg-content-dark.png", "../images/process-on.png", "../images/structure-on.png", "../images/points-on.png");

    // set up fades for top graphics
        TopGraphicFadeEffect('#content-webelieve', '#labels-we-believe', 'slow'); // we believe page
        TopGraphicFadeEffect('#content-process', '#labels-process', 'slow'); // process page
        TopGraphicFadeEffect('#content-structure', '#labels-structure', 'slow'); // structure page
        TopGraphicFadeEffect('#content-points', '#labels-points', 'slow'); // points of difference page
   
    // more links on the Meet the Team page
    $('a.more').click(
		function () {
		    col = $(this).parents('.col');
		    DoFlip(col, false);
		    return false;
		}
	);

    $('a.less').click(
		function () {
		    col = $(this).parents('.col');
		    DoFlip(col, true);
		    return false;
		}
	);

    // Flip all link
    $('#flipall').toggle(
		function () {
		    $('.cardinfo').each(
				function (idx) {
				    DoFlip($(this), false);
				}
			)
		    return false;
		},
		function () {
		    $('.cardinfo').each(
				function (idx) {
				    DoFlip($(this), true);
				}
			)
		    return false;
		});

    // contact us form validation
    $("#contactFrm").validate({
        rules: {
            email: { required: true, email: true }
        }
    });

    $("#basecampform").validate({
        rules: {
            username: { required: true, email: false },
            password: { required: true, email: false }
        }
    });

    $("#contactFrm").submit(
		    function () {
		        if ($(this).valid()) {
		            $.post('/contact/process.aspx', { email: $('[name=email]').val(), message: $('[name=message]').val() },
		        function (data) {
		            if (data == "\"success\"") {
		                // replace form with confirmation div
		                $('#contact').hide('slow');
		                $('#contact_confirm').show('slow');
		            }
		            else {
		                return false;
		            }
		        });
		            return false;
		        }
		    });

    // flip for Meet the team page
    setTimeout('InitialFlip()', 5000);

});

jQuery.preloadImages = function () {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
        $('#content-webelieve').attr('preloadURL', arguments[0]);
    }


}

function InitialFlip() {
    // random flip on meet the team
    if ($('#flipall').html()) {
        $('.cardinfo').each(
				function (idx) {
				    DoFlip($(this), true);
				}
			)
    }
}

function TopGraphicFadeEffect(divID, imgID, fadeSpeed) {
    $(divID).hover(
        function () {
            if (CanDoFadeEffect()) {
                $(imgID).css('display', 'block');
            }
            else {
                $(imgID).fadeIn(fadeSpeed);
            }
        }
        ,
        function () {
            if (CanDoFadeEffect()) {
                $(imgID).css('display', 'none');
            }
            else {
                $(imgID).fadeOut(fadeSpeed);
            }
        }
    );
    }

    function CanDoFadeEffect() {
        return $.browser.msie && $.browser.version.substr(0, 1) <= 8 && $.browser.version.substr(0, 1) > 6;
    }

function DelayedFlip(idx, delay, arr) {
    card = $('.cardinfo:eq(' + arr[idx] + ')');
    setTimeout(DoFlip, delay, card, true);

    if (idx < arr.length) DelayedFlip(idx + 1, delay, arr);
}

function buildArray(numOfItems, maxNum) {
    digits = new Array();
    randomDigits = new Array();

    // build array with each of possible digits
    for (idx = 0; idx < numOfItems; idx++) {
        digits[digits.length] = idx;
    }

    while (digits.length != 0) {
        // get random number
        var rIdx = getRand(digits.length);
        if (digits.length > 1) {
            randomDigits[randomDigits.length] = digits[rIdx];
        }
        else {
            randomDigits[randomDigits.length] = digits[0];
        }

        // remove the item just selected from the digits array
        digits.splice(rIdx, 1);
    }

    return randomDigits;
}

function getRand(maxNum) {
    return (Math.ceil(Math.random() * 100)) % maxNum;
}
function DoFlip(card, showNext) {
    //if (!card) return; 
		// capture the card's current content in a hidden div so it will be there when we flip back
        tmp = '<div class="tmp">' + card.html() + '</div>';
		
		// get content and card direction
		if (showNext) {
			content = card.next().html();
			// capture the html for the other side of the card
			card.next().append(tmp);
			direction = 'lr';
		}
		else {
			content = card.next().find('.tmp').html();
			direction = 'rl';
		}

		// clean up tmp div
		card.next().remove('.tmp');
		
		// call flip code, onEnd sets up click events for the content on the flipped card
		card.flip({
				direction:direction,
				color:'#ffffff',
				content: content,
				speed: 150,
				onEnd: function() {
					if (showNext) { // re-bind link to click event
						card.find('a.more').click(
							function(){
								DoFlip($(this).parents('.col'), false);			
								return false;
							});
					}
					else {// re-bind link to click event
						card.find('a.less').click(
							function(){
								DoFlip($(this).parents('.col'), true);			
								return false;
						});
					}
				}
		});		
		
}
