﻿var curr = 0;
var slides;
var total = 0;
var timer = null;
var cont;
var w = 950;
var fixed = false;
var first = true;
$(function() {
    cont = $('#homepageFMAHolder .imageArea');
    slides = cont.children('.slide');
    total = slides.length;

    initSlides();

//    if (isIE6()) {
//        moveSearchDrawer();
//    }
});

function initSlides()
{
    cont.width((total+1) * w);
    //clone the second slide, since we'll be removing the first slide after the first time
    $(slides[1]).clone().addClass('cloned').insertAfter(cont.children('.slide:last'));

    $('#homepageFMAHolder .linkArea a').each(function(i){
        $(this).bind('click',function(){
            clearInterval(timer);
            linktoSlide(i);
        });
    });

    
    if($(slides[0]).find('.overlay').length > 0)
    {
        setTimeout(function(){indicateCurrent(curr);$(slides[0]).find('.overlay').animate({left:40},800);},2500);
    }
    
    timer = setInterval(cycleSlides,8000);
}

function cycleSlides()
{
    curr++;
    if (first) {
        removeIntro();
    }
    if(curr == total)
        curr = 0;
    
    gotoSlide(curr);
}

function linktoSlide(idx)
{
    if(!fixed)
        idx++;
    gotoSlide(idx, true);
}

function removeIntro() {
    if (!fixed) {
        cont.children('.slide:first').remove();
        total--;
        fixed = true;
    }
}

function gotoSlide(idx, linked)
{
    curr = idx;
    if(curr == 0 && (typeof(linked) == 'undefined' || linked == false))
    {
        indicateCurrent(idx);
        cont.stop(true).animate({marginLeft:(-total)*w},700,function(){
            cont.css('marginLeft','0px');
        });
    }
    else
    {
        var indicated = fixed ? idx : idx-1;
        indicateCurrent(indicated);
        //indicateCurrent(idx);
        cont.stop(true).animate({marginLeft:w*(-curr)},700);
    }
}

function indicateCurrent(idx)
{
    $('#homepageFMAHolder .linkArea a span.indicator').fadeOut(600);
    var currchild = $('#homepageFMAHolder .linkArea').children('a')[idx];
    $(currchild).children('span.indicator').fadeIn(600);
}

function moveSearchDrawer() {
    var tdrawer = $('#searchDrawer');
    tdrawer.width('950px');
    tdrawer.css('margin', '0 auto');
    $('body').append(tdrawer);

    $(window).resize(centerSearchDrawer);
    centerSearchDrawer();
}

function centerSearchDrawer() {
    var w = $(window).width();
    $('#searchDrawer').css('left', (w / 2) - (950 / 2));
}
