var browserWidth = $(window).width();
var animationComplete = false;
var slideWidth = 919;
var slideCount = 0;

var _ShowAdTextPanels = false;
var _ShowAgentTextPanels = false;

/***********************************
RESOURCE PRELOADING PLUGIN
***********************************/
$.fn.preload = function () {
    this.each(function () {
        $('<img/>')[0].src = this;
    });
}

/***********************************
Grab an image's width after adding image
***********************************/
function loadImg(url, func) {
    var img = new Image();
    img.css({
        "opacity": "1",
        "position": "normal",
        "visibility": "visible"
    });
    img.onload = func;
    img.src = url;
    return img;
}

/***********************************
MAIN DOCUMENT LOADING
***********************************/
$(window).load(function () {

    var numberOfSlides = 0;

    //Load the slides from XML file
    $.ajax({
        type: "GET",
        url: "/Slider/slider.xml",
        dataType: "xml",
        success: InitializeAnimation,
        error: function (request, status, error) {
            alert('Error in script:' + error);
        }
    });

    /***********************************/
    function InitializeAnimation(xml) {

        //Load options to variables
        _ShowAdTextPanels = ($(xml).find('ShowAdTextPanels').text().toUpperCase() == 'TRUE') ? true : false;
        _ShowAgentTextPanels = ($(xml).find('ShowAgentTextPanels').text().toUpperCase() == 'TRUE') ? true : false;

        //Create the Slider inside the master control.
        $('#slideshow').append('<div id="slidesContainer"></div>');

        // Remove scrollbar in JS; Show the control
        //-----------------------------------------------
        $('#slidesContainer')
        .css({
            'overflow': 'hidden',
            'display': 'block'
        });
		$('#slidesContainer').append('<ul id="mycarousel" class="jcarousel-skin-tango"></ul>');
        var slideCnt = 0;
        var newSlide = '';
		
		$(xml).find('Banner').each(function () {
			slideCnt++;
			newSlide = '';
			newSlide += '<li>';
			newSlide += '<div class="slide" id="slide_' + slideCnt + '">';
			newSlide += '<div class="adbanner">';
			newSlide += '<img width="685px" height="302px" id="imgbanner_' + slideCnt + '" src="' + $(this).find("Image").text() + '" alt="banner ' + slideCnt + '" />';
			newSlide += '<span id="span_' + slideCnt + '" style="color:'+$(this).find("Statement").attr("color")+';"><strong>' + $(this).find("Statement").text() + '</strong><br />';
			newSlide += '<img src="' + $(this).find("StatementIcon").text() + '" alt="" /></span></div>';
			newSlide += '<div class="agentbanner">';
			newSlide += '<a href="' + $(this).find("AgentLinkURL").text() + '">';
			newSlide += '<img width="234px" height="302px" src="' + $(this).find("AgentImage").text() + '" alt="agent ' + slideCnt + '" /></a>';
			newSlide += '<span id="agentspan_' + slideCnt + '" style="color:'+$(this).find("Agent").attr("color")+';"><strong>' + $(this).find("Agent").text() + '</strong><br />';
			newSlide += '<strong style="color:'+$(this).find("AgentCompany").attr("color")+';">' + $(this).find("AgentCompany").text() + '</strong> </span></div></div>';
			newSlide += '</li>';
			$("#mycarousel").append(newSlide);
		});
		
		slideCount = slideCnt;
		
		//Make us a gray scroller inside the scroller container
        var gryIdx = 0;
        $('#scrollercontainer').append('<ul id="grayscroller"></ul>');
        $(xml).find('GrayItem').each(function () {
			$('#grayscroller').append('<li><img width="'+$(this).attr('width')+'" height="'+$(this).attr('height')+'" alt="grayitm_' + (gryIdx + 1) + '" src="' + $(this).text() + '"/></li>');
            gryIdx++;
        });
        $('#grayscroller').css({ 'width': slideWidth*slideCount });
  
		$('#scrollercontainer').append('<ul id="grayscrollerinitial"></ul>');
		for (i=0; i<2; i++)
		{
			$(xml).find('GrayItem').each(function () {
				$('#grayscrollerinitial').append('<li><img width="'+$(this).attr('width')+'" height="'+$(this).attr('height')+'" alt="grayitm_' + (gryIdx + 1) + '" src="' + $(this).text() + '"/></li>');
				gryIdx++;
			});
		}
        $('#grayscrollerinitial').css({ 'width': (slideWidth*slideCount)*2 });
		$("#grayscrollerinitial").css({ 'margin-left': (-1*(slideWidth*slideCount)) });

        //Show effect on the agent banner when mouse is hovered over it.
        //-------------------------------------------------
        $(".agentbanner")
        .hover(
            function () { $(".agentbanner").animate({ 'opacity': 1 }, { duration: 100, queue: false }) },
            function () { $(".agentbanner").animate({ 'opacity': 0.9 }, { duration: 100, queue: false }) })
        .click(
            function () { //Make a blinking effect when agent image is clicked.
                $(".agentbanner")
                .animate({ 'opacity': 0.9 }, { duration: 100, queue: true })
                .animate({ 'opacity': 1 }, { duration: 100, queue: true })
                .animate({ 'opacity': 0.9 }, { duration: 100, queue: true })
                .animate({ 'opacity': 1 }, { duration: 100, queue: true })
                .animate({ 'opacity': 0.9 }, { duration: 100, queue: true })
                .animate({ 'opacity': 1 }, { duration: 100, queue: true });
            });

        //Start animation sequence
        //-------------------------------------------
        //Prepare banner and agent image containers for animation
        $(".adbanner").css({ 'opacity': 0, 'marginLeft': 685 / 2, 'width': 5, 'zIndex': 1 });
        $(".agentbanner").css({ 'opacity': 0, 'width': 0, 'zIndex': 0 });
        
        animationComplete = false;
		var randomnumber=Math.floor(Math.random()*slideCount);
		$('#grayscroller').jcarousel({wrap: 'circular', scroll: 3, start: (((randomnumber+1)*3)-2), animation: "slow", initCallback: modelCarousel_initCallback});
		$("#grayscroller").hide();
		
		$('#mycarousel').jcarousel({wrap: 'circular', animation: "slow", start: randomnumber+1, scroll: 1});
		$('.jcarousel-prev, .jcarousel-next').hide();
		
		$("#grayscrollerinitial").animate({ marginLeft: ((((randomnumber)*919)*-1)+randomnumber*28)},{
			duration: 7500,
			complete: function () { 
			$(".adbanner").animate(
			{ opacity: "1", marginLeft: "0px", width: "685px" },
			{ queue: false,
				duration: 800,
				complete: function () {
					$(".agentbanner").animate(
					{ opacity: .90, width: "234px" },
					{ queue: false,
						duration: 1500,
						complete: function () {
							
							if (_ShowAdTextPanels) {
								$("#span_1").animate({ 'bottom': 0 }, { queue: false, duration: 800 });
							}
							if (_ShowAgentTextPanels) {
								$("#agentspan_1").animate({ 'bottom': 0 }, { queue: false, duration: 1000 });
							}
							
							$("#grayscrollerinitial").hide();
							$("#grayscroller").show();
							$('.jcarousel-prev, .jcarousel-next').fadeIn("slow");
							$('#slidesContainer .jcarousel-prev').click(function() {
							  grayCarousel.prev();
							});
							$(".adbanner span").css("left", "auto");
							$(".agentbanner span").css("left", "auto");
							
							$('#slidesContainer .jcarousel-next').click(function() {
							  grayCarousel.next();
							});
							animationComplete = true;
						}
					});
				}
			});
		}});
    }
});  // ( JQuery Main ) 

var grayCarousel = null;
function modelCarousel_initCallback(carousel) {
grayCarousel = carousel;
};

