
// Copyright 2010 Convertium Pte Ltd. 
// All Rights Reserved.
// http://convertium.com

$(document).ready(function() {

    //Auto generate paging items
    var kidId = 1;
    $('.cpltransition_banners').children().each(function() {
        $(this).attr('id', 'banner-' + kidId);
        $('.cpltransition_paging').append('<a href="#" id="a' + kidId + '" rel="' + kidId + '">' + kidId + '</a>');
        kidId += 1;
    });

    //Init Configurations
    var transitioning = false;
    var currID = 1;
    var fadeInSpeed = 1000; 		// Fade In - miliseconds
    var fadeOutSpeed = 1000; 		// Fade Out - miliseconds
    var transitionSpeed = 4000; 	// Holding Time - miliseconds
    transitionSpeed = transitionSpeed + fadeInSpeed + fadeOutSpeed;

    //Set Default State of each portfolio piece
    $(".cpltransition_paging").show();
    $(".cpltransition_paging a:first").addClass("active");

    //Paging + Transition Function
    rotate = function() {

        var currentID = currID;
        var nextID = $active.attr("rel");
        currID = nextID;

        $(".cpltransition_paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //alert(currentID + " : " + nextID);

        //Transition Animation
        if (transitioning == false) {
            transitioning = true;
            $("#banner-" + currentID).fadeOut(fadeOutSpeed, function() {
            });
            $("#banner-" + nextID).fadeIn(fadeInSpeed, function() {
                transitioning = false;
            });
        }

    };

    //Rotation + Timing Event
    rotateSwitch = function() {

        play = setInterval(function() { //Set timer - this will repeat itself every 3 seconds
            $active = $('.cpltransition_paging a.active').next();
            if ($active.length === 0) { //If paging reaches the end...
                $active = $('.cpltransition_paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, transitionSpeed); //Timer speed 

    };

    rotateSwitch(); 	//Run function on launch
    $("#banner-" + currID).fadeIn(fadeInSpeed, function() { }); //Show first banner

    //On Hover
    $(".cpltransition_banners a").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation
    });

    //On Click
    $(".cpltransition_paging a").click(function() {
        if (transitioning == false) {
            $active = $(this); //Activate the clicked paging
            //Reset Timer
            clearInterval(play); //Stop the rotation
            rotate(); //Trigger rotation immediately
            rotateSwitch(); // Resume rotation
        }
        return false; //Prevent browser jump to link anchor
    });

});

