﻿/// <reference path="jquery-1.6.1.min.js" />

function stripFotoName(src) {
    var words = new Array();
    words = src.split('/');
    src = words[words.length - 1];
    return src;
}
    
$(document).ready(function () {
    var banners = $(".mainlink a span.files").parent(); 
    var exists = new Array();
    
    if (banners.length > 0) {
        banners.each(function (index) {
            this.files = $(this).find("span.files span.file img").sort(sortRandom);
            this.counter = 0;
        });
        var timer = setInterval(rotateTimer, 6000);
    }
    
    function rotateTimer() {
        //exists = [];
        banners.each(function (index) {
            this.counter = rotate(this);
        });
    }
    
    function sortRandom(){
        return 0.5 - Math.random();
    }
    
    
    function rotate(banner) {
        var files = banner.files;
        var counter = banner.counter;
        var newImg, oldImg, newImgSrc, oldSrc;
        var whileCounter = 0;
        
        while (oldSrc == newImgSrc && whileCounter < 5){
            newImg = $(files[counter++]);
            newImgSrc = $(newImg).attr("src");
            newImgSrc = stripFotoName(newImgSrc);
            oldImg = $(banner).children(".background");
            oldSrc = oldImg.attr("src");
            oldSrc = stripFotoName(oldSrc);
            
            if (counter > files.length - 1) {
                    counter = 0;
            }
            whileCounter++;
        }

        if (oldSrc != newImgSrc){
            crossfade(oldImg, newImg);
            if (banners.length == 4){
                $(banner).attr('href','/vacatures/' + newImgSrc.split('.')[0]);
            }
        }
        return counter;
    }
    
    function crossfade(oldImg, newImg) {
        var $newImgCopy = $(newImg).clone();
        $($newImgCopy).attr("id", oldImg.attr("id"))
            .attr("width", oldImg.attr("width"))
            .attr("height", oldImg.attr("height"))
            .attr("alt", oldImg.attr("alt"))
            .css('z-index', '9')
            .appendTo($(oldImg).parent()).each(function () {
                oldImg.fadeOut(2000, function () {
                    $(this).remove();
                    $($newImgCopy).css('z-index', '10');
                })
            });
    }
});
