$(function () {

    //build menu
    jquerycssmenu.buildmenu("nav");

    // start animations and scrolling
    setInterval('slide("testimonials",1000)', 8000);
    setInterval('slide("partners",1000)', 5000);
    setTimeout('banner_screen()',500);
    side_testimonials();
    marquee();
    countries(1, 0, 0);

    // start lightbox for galleries
    // $('.gallery').fancybox();

    // start coverflip set class with number for multiple coverflips.
    var i=1;
    $('.flip').each(function() {
        $(this).addClass('flip'+i);
        $(this).parent().find('.scrollbar').addClass('scrollbar'+i);
        var start = $(this).attr('title') || '0';
        var total = $(this).find('LI').length;
        coverflip(i, start, total);
        i++;
        });

    $(".prevent_default").click(function(event) {
        event.preventDefault();
        });

    $('.collapsible').hide();
    $('.collapse_header').each(function(){
            $(this).bind('click', function(){
                var $c = $(this).next('.collapsible');
                $c.slideToggle("fast");
            });
        });

    });

var jquerycssmenu={
    //duration of fade in/ out animation, in milliseconds
    fadesettings: {overduration: 300, outduration: 150},
    buildmenu:function(menuid){
        jQuery(document).ready(function($){
            var $mainmenu=$("#"+menuid+">ul")
            var $headers=$mainmenu.find("ul").parent()
            $headers.each(function(i){
                var $curobj=$(this)
                var $subul=$(this).find('ul:eq(0)')
                this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
                this.istopheader=$curobj.parents("ul").length==1? true : false
                $subul.css({top:this.istopheader? this._dimensions.h-1+"px" : 0})
                $curobj.children("a:eq(0)").append(
                    '<div class="' + (this.istopheader ? "down_arrow" : "right_arrow") + '"></div>'
                )
                $curobj.hover(
                    function(e){
                        var $targetul=$(this).children("ul:eq(0)")
                        this._offsets={left:$(this).offset().left, top:$(this).offset().top}
                        var menuleft=this.istopheader? 0 : this._dimensions.w
                        menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
                        $targetul.css({left:menuleft-11+"px"}).fadeIn(jquerycssmenu.fadesettings.overduration)
                        },
                        function(e){
                            $(this).children("ul:eq(0)").fadeOut(jquerycssmenu.fadesettings.outduration)
                        }
                    )    //end hover
                }) //end $headers.each()
                $mainmenu.find("ul").css({display:'none', visibility:'visible'})
            }) //end document.ready
        }
    }

function coverflip(flip_num, start_shot, total_shots) {

    // Increments for scrollbar indicator
    var increments = 100/(total_shots-1);

    $('.flip'+flip_num).jcoverflip({
        current: start_shot || '0',
        beforeCss: function( el, container, offset ){
          return [
            $.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 260 - 135*offset + 20*offset )+'px', bottom: 30*(offset+1) +'px' }, { } ),
            $.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,125-20*offset*offset) + 'px' }, {} )
          ];
        },
        afterCss: function( el, container, offset ){
          return [
            $.jcoverflip.animationElement( el, { left: ( container.width( )/2 + 135 + 135*offset )+'px', bottom: 30*(offset+1) + 'px' }, { } ),
            $.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,125-20*offset*offset) + 'px' }, {} )
          ];
        },
        currentCss: function( el, container ){
          return [
            $.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 125 )+'px', bottom: 0 }, { } ),
            $.jcoverflip.animationElement( el.find( 'img' ), { width: '250px' }, { } )
          ];
        },
        change: function(event, ui){
          $('.scrollbar'+flip_num).slider('value', ui.to*increments);
        }
      });

    $('.scrollbar'+flip_num).slider({
        value: (100/(total_shots-1))*start_shot,
        stop: function(event, ui) {
            if(event.originalEvent) {
                var newVal = Math.round(ui.value/increments);
                $('.flip'+flip_num).jcoverflip( 'current', newVal );
                $('.scrollbar'+flip_num).slider('value', newVal*increments);
                }
            }
        });
    }

function banner_screen() {
    var $graphic = $('DIV#banner_graphic DIV.slide_in');

    if ($graphic.length) {
        $graphic.animate(
            { marginLeft    :   '0px' },
            {
              duration      :   1000,
              easing        :   'easeOutBounce',
              complete      :   function() {
                   start_screen();
                   main_points(0);
                   }
            });
        }
    }

function start_screen() {
    var $screen = $('DIV#screen');
    if (!$screen) return;

    $screen.show();

    $screen.animate({
        width:      '320px',
        left:       '71px'
        }, 500 ).animate({
            height:     '210px',
            top:        '74px'
            }, 300, function() {
                setInterval('slide("screen",600)', 5000);
                });
    }

function main_points(left_pos) {
    var $points = $('DIV#main_points');

    if ($points.length) {
        for (var i = 0; i < 3; i++ ){
        $points.find('DIV.point:eq('+i+')').animate({
                left    :   left_pos
                },{
                duration    :   600,
                easing      :   'easeOutCirc',
                complete    :   function() {
                    }
                });
            };

        if ($points.find('DIV.point').length > 3) {
            if (left_pos == 0) {
                setTimeout("main_points(500)",8000);
                }
            else {
                setTimeout("rearrange_points()",800);
                }
            }
        }
    }

function rearrange_points() {
    var $points     = $('DIV#main_points');
    var $old_points = $points.find('DIV.point:lt(3)');
    $old_points.remove().appendTo($points);
    main_points(0);
    }

function slide(target,speed){
    var $slides = $('DIV#'+target+' DIV.slides');
    if ($slides.find('DIV.slide').length < 2) return;
    var $current = $slides.find('DIV.slide:first');

    var $new = $slides.find('DIV.slide:last');
    $new.remove();
    $slides.prepend($new);
    $new.css({
        top:  "-" + $slides.height() + "px"
        });

    $current.animate({
            top:   $slides.height() + "px"
            },
        speed
        );

    $new.animate(
        {
            top:   0
            },
        speed
        );
    }

function marquee() {
    var $marquee = $('DIV.marquee');
    if (!$marquee.length) return;
    var $parent  = $marquee.parent();
    var parent_width = $parent.width();
    var width = $marquee.width();

    $marquee.animate({
        left:       '-'+width+'px'
        }, 50000, function(){
            marquee();
            });
    }

function side_testimonials() {

    var $scroll_elem = $('DIV#scrolling_testimonials DIV.contents');
    if (!$scroll_elem) return;

    var height      = $scroll_elem.height();
    $scroll_elem.height(height); //set height
    var duration = height * 80;

    var scrollUp = function(){ $scroll_elem.animate({
        top:        (-1 * height) + 'px'
        }, duration, 'linear', function(){
            $scroll_elem.css({
                paddingTop: $scroll_elem.css('paddingBottom'),
                top:        0
                });
            // When finished start again
            setTimeout(scrollUp, 3000);
            });
        }

    setTimeout(scrollUp, 3000);

    }

function countries(start_over, pos, delay) {

    var $countries = $('DIV#countries');

    if (start_over) {
        pos         = 0;
        delay       = 1800;
        }

    var $next = $countries.find('DIV.country:eq('+pos+')');

    colors = ['#ff6600','#666','#999','#cc0000','#0099cc','#339900'];
    var top;
    var left;

    if ($next.attr('title') != 'last') {
        top   = Math.floor(Math.random()*110+20);
        left  = Math.floor(Math.random()*130);
        var color = colors[Math.floor(Math.random()*colors.length)];
        var size  = Math.floor(Math.random()*20+12);

        $next.delay(delay/3).animate({
            opacity: 0
            }, 1000, function() {
                // reset element state
                $(this).css({
                    opacity:    1,
                    top:        200
                    });
                });
        if (delay > 100) {
            delay = delay/1.2;
            }
        pos++;
        setTimeout('countries(0,'+ pos + ',' + delay +')', delay);
        }
    else {
        top = 25;
        left = 0;
        $countries.find('DIV.country').not('DIV.last').removeAttr('style');
        // restart animation after delay
        $next.delay(15000).animate({
            top:        200
            }, 800 , function() {
                countries(1,0,0);
                }
            );
        }

    $next.css({
        top: top,
        left: left,
        color: color,
        fontSize: size
        });

    }

  
