// To fetch Data from Sharepoint List
var _itv;

function GetSPListData()
{
    var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                <soapenv:Body> \
                     <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        <listName>ImageCarousel</listName> \
                        <query><Query><OrderBy><FieldRef Name='LinkTitle'/></OrderBy><Where><Eq><FieldRef Name='TargetPage'/><Value Type='Text'>HomePage</Value></Eq></Where></Query></query> \
                        <viewFields> \
                            <ViewFields> \
                               <FieldRef Name='Large_x0020_Image' /> \
							   <FieldRef Name='More_x0020_Link' /> \
							   <FieldRef Name='video_x0020_link' /> \
							   <FieldRef Name='Video_x0020_Description' /> \
                           </ViewFields> \
                        </viewFields> \
                    </GetListItems> \
                </soapenv:Body> \
            </soapenv:Envelope>";
    $.ajax(
    {
        url: "../_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });
}

function processResult(xData, status)
{
    var count_video = 1;
    var image_count = 0;
    $(xData.responseXML).find("[nodeName=z:row]").each(function ()
    {
        if ($(this).attr("ows_Large_x0020_Image") != undefined)
        {
            var link = $(this).attr("ows_More_x0020_Link");
            var link_array = link.split(", ");
            var liHtml = "<li id=\"image" + image_count++ + "\"><div style=\"float:left;\"><a href=\"" + link_array[0] +
            			 "\">" + $(this).attr("ows_Large_x0020_Image") + 
            			 "</a></div><div style=\"position:absolute;width:940px;margin: 225px 0 0 280px;\"><div style=\"float:right;\"><div class=\"learnmoreLink\"><a href=\"" + link_array[0] + 
            			 "\">Learn More</a></div><div class=\"watchvideoLink\" id=\"videoID" + count_video + "\"></div></div></div></li>";
            $("#novelis_scroller").append(liHtml);
            var video_link = $(this).attr("ows_video_x0020_link");
            if (video_link != undefined)
            {
                var tempID = "#videoID" + count_video;
                var contentID = "#jwbox_content" + count_video;
                var video_link_array = video_link.split("\"");
                var videodescription = $(this).attr("ows_Video_x0020_Description");
                var video = "'" + video_link_array[1] + "','" + videodescription + "','" + contentID + "'";
                var reg = /\s+/g;
                var video_final = video.replace(reg, "%20");
                var videoData = "<div id='watchvideo' class='jwbox'><a href='#' onclick=\"javascript:createPlayerHome(" + video_final + 
                				");return false;\">Watch Video</a><div class='jwbox_hidden closeButton'><div class='jwbox_content' id='jwbox_content" + count_video + 
                				"'></div></div></div>";
                if ($(tempID).is(':empty'))
                {
                    $(tempID).append(videoData);
                    count_video = count_video + 1;
                }
            }
        }
    });
    process();
    functionBindClick();
}


//For Carousel
function process()
{
    var specificslide;
    var slideCounter = 0;
    // Set currently selected
    var object = $('#novelis_scroller');
    // Sets up slide size
    var slides = object.find('li');
    var currentslide = 0;
    var noOfSlides = slides.length;
    var hreftag;
    var indicators = $('ul#novelis_indicators');
    var activeIndicator;
    var currentLi;
    jQuery.fn.imageScroller = function (params)
    {
        var p = params || {
            next: "buttonNext",
            prev: "buttonPrev",
            frame: "viewerFrame",
            width: 100,
            child: "a",
            auto: true
        };
        var _btnNext = $("#" + p.next);
        var _btnPrev = $("#" + p.prev);
        var _imgFrame = $("#" + p.frame);
        var _width = p.width;
        var _child = p.child;
        var _auto = p.auto;
        var turnLeft = function ()
        {
            _btnNext.unbind("click", turnLeft);
            $(".active").removeClass();
            if (_auto) autoStop();
            _imgFrame.animate(
            {
                marginLeft: -_width
            }, 'slow', '', function ()
            {
                _imgFrame.find(_child + ":first").appendTo(_imgFrame);
                _imgFrame.css("marginLeft", 0);
                currentLi = _imgFrame.find(_child + ":first").attr("id");
                if (currentLi !== undefined)
                {
                    currentLi = currentLi.replace("image", "");
                }
                activeIndicator = $('ul#novelis_indicators').find('li:eq(' + currentLi + ')');
                activeIndicator.addClass('active');
                _btnNext.bind("click", turnLeft);
                if (_auto) autoPlay();
            });
            return false;
        };
        jQuery.fn.imageScroller.getSpecificImage = function ()
        {
            if (_auto) autoStop();
            currentLi = _imgFrame.find(_child + ":first").attr("id");
            if (currentLi !== undefined)
            {
                currentLi = currentLi.replace("image", "");
            }
            if (currentLi != hreftag)
            {
                if (currentLi < hreftag)
                {
                    $(".active").removeClass();
                    _imgFrame.animate(
                    {
                        marginLeft: -_width * (hreftag - currentLi)
                    }, 'slow', '', function ()
                    {
                        for (var i = 0; i < parseInt(hreftag - currentLi); i++)
                        {
                            _imgFrame.find(_child + ":first").appendTo(_imgFrame);
                        }
                        _imgFrame.css("marginLeft", 0);
                    });
                    activeIndicator = $('ul#novelis_indicators').find('li:eq(' + hreftag + ')');
                    activeIndicator.addClass('active');
                }
                else if (currentLi > hreftag)
                {
                    if (currentLi - (noOfSlides - 1) == hreftag)
                    {
                        $(".active").removeClass();
                        _imgFrame.animate(
                        {
                            marginLeft: -_width
                        }, 'slow', '', function ()
                        {
                            _imgFrame.find(_child + ":first").appendTo(_imgFrame);
                            _imgFrame.css("marginLeft", 0);
                        });
                        activeIndicator = $('ul#novelis_indicators').find('li:eq(' + hreftag + ')');
                        activeIndicator.addClass('active');
                    }
                    else
                    {
                        $(".active").removeClass();
                        for (var i = 0; i < parseInt(currentLi - hreftag); i++)
                        {
                            _imgFrame.find(_child + ":last").clone().show().prependTo(_imgFrame);
                            _imgFrame.css("marginLeft", -_width * (currentLi - hreftag));
                            _imgFrame.find(_child + ":last").remove();
                        }
                        _imgFrame.animate(
                        {
                            marginLeft: 0
                        }, 'slow', '', function ()
                        {
                        });
                        activeIndicator = $('ul#novelis_indicators').find('li:eq(' + hreftag + ')');
                        activeIndicator.addClass('active');
                    }
                }
                else
                {
                    $(".active").removeClass();
                    _imgFrame.animate(
                    {
                        marginLeft: -_width
                    }, 'slow', '', function ()
                    {
                        _imgFrame.find(_child + ":first").appendTo(_imgFrame);
                        _imgFrame.css("marginLeft", 0);
                    });
                    activeIndicator = $('ul#novelis_indicators').find('li:eq(' + hreftag + ')');
                    activeIndicator.addClass('active');
                }
            }
            else
            {
                $(".active").removeClass();
                activeIndicator = $('ul#novelis_indicators').find('li:eq(' + hreftag + ')');
                activeIndicator.addClass('active');
            }
            if (_auto) autoPlay();
        }
        var turnRight = function ()
        {
            _btnPrev.unbind("click", turnRight);
            if (_auto) autoStop();
            $(".active").removeClass();
            _imgFrame.find(_child + ":last").clone().show().prependTo(_imgFrame);
            _imgFrame.css("marginLeft", -_width);
            _imgFrame.animate(
            {
                marginLeft: 0
            }, 'slow', '', function ()
            {
                _imgFrame.find(_child + ":last").remove();
                currentLi = _imgFrame.find(_child + ":first").attr("id");
                if (currentLi !== undefined)
                {
                    currentLi = currentLi.replace("image", "");
                }
                activeIndicator = $('ul#novelis_indicators').find('li:eq(' + currentLi + ')');
                activeIndicator.addClass('active');
                _btnPrev.bind("click", turnRight);
                if (_auto) autoPlay();
            });
            return false;
        };
        _btnNext.css("cursor", "hand").click(turnLeft);
        _btnPrev.css("cursor", "hand").click(turnRight);
        var autoPlay = function ()
        {
            _itv = window.setInterval(turnLeft, 8000);
        };
        var autoStop = function ()
        {
            window.clearInterval(_itv);
        };
        jQuery.fn.imageScroller.carouselAutoPlay = function ()
        {
			autoPlay ();
        }
        
        if (_auto) autoPlay();
    };
    // If there's slides, continue
    if (slides.length > 0)
    {
        // If the developer wants default indicators
        for (var i = 0; i < slides.length; i++)
        {
            $('ul#novelis_indicators').append('<li><a href="#' + i + '"></a></li>');
        }
    }
    // Indicator Functionality
    var defautindicator = $('ul#novelis_indicators').find('li:eq(0)');
    defautindicator.addClass('active');
    var the_indicators = $('ul#novelis_indicators').find('li a');
    // Thanks to Tomas Nikl for the below fix
    the_indicators.click(function ()
    {
        hreftag = $(this).attr('href');
        hreftag = hreftag.substring(hreftag.search('#') + 1, hreftag.length);
        specificslide = hreftag;
        $("#novelis_clip").imageScroller.getSpecificImage();
        return false;
    });
    $("#novelis_clip").imageScroller(
    {
        next: "carousel_next",
        prev: "carousel_prev",
        frame: "novelis_scroller",
        width: 1600,
        child: "li",
        auto: true
    });
}

//For Light Box
function functionBindClick()
{
    $(document).ready(function ()
    {
        $("body").append('<div id="jwbox_background">&nbsp;</div>');
        if ($(".jwbox"))
        {
            $(".jwbox").live("click", function ()
            {
                $.jwbox.toggle(this);
                return false;
            });
            $("#jwbox_background").live("click", function ()
            {
                $.jwbox.toggle(this);
                $("#novelis_clip").imageScroller.carouselAutoPlay();
                return false;
            });
            $(".jwbox_content").live("click", function ()
            {
                $.jwbox.toggle(this);
                return false;
            });
            $(window).resize(function ()
            {
                $.jwbox.center();
            });
            $(".closeButton").live("click", function ()
            {
            	$("#novelis_clip").imageScroller.carouselAutoPlay();
			});
        }
    });
    jQuery.fn.center = function ()
    {
        this.css("position", "fixed");
        this.css("top", ($(window).height() - this.outerHeight()) / 2 + "px");
        this.css("left", ($(window).width() - this.outerWidth()) / 2 + "px");
        return this;
    }
    jQuery.jwbox =
    {
        lightbox: null,
        player: null,
        toggle: function (context)
        {
            if (!$.jwbox.lightbox)
            {
                $.jwbox.lightbox = $(".jwbox_hidden", context);
                $.jwbox.center();
                $("#jwbox_background").fadeIn("fast");
                $.jwbox.lightbox.css("display", "block")
                $.jwbox.center();
                $("#jwbox_background").fadeTo(0, 0.8);
                $("object", context).each(function ()
                {
                    $.jwbox.player = document.getElementById(this.id);
                });
            }
            else if ((context.className == 'jwbox_content'))
            {
            }
            else
            {
                try
                {
                    $.jwbox.player.sendEvent("STOP");
                    $.jwbox.player = null;
                }
                catch (err)
                {
                }
                $.jwbox.lightbox.css("display", "none");
                $.jwbox.lightbox = null;
                $("#jwbox_background").fadeOut("fast");
            }
        },
        center: function ()
        {
            if ($.jwbox.lightbox)
            {
                $.jwbox.lightbox.center();
            }
        }
    }
    $(document).keyup(function (event)
    {
        if (event.keyCode == 27 && $.jwbox.lightbox)
        {
            $.jwbox.toggle($("#jwbox_background"));
        }
    });
}

//Dynamically Taking the video
function createPlayerHome(video_link, video_description, contentID)
{
    window.clearInterval(_itv);
    if ($("#player1"))
    {
        $("#player1").remove();
        $("#videoDesc").remove();
    }
    if($("#videoPlaceholder"))
    {
    	$("#videoPlaceholder").remove();
    }
    if ($(contentID))
    {
        var videoContainerHTML = "<div id=\"videoPlaceholder\">Hello, you either don't have Flash Player or an old version of Macromedia's Flash Player.<p><a href=\"#\" onclick=\"javascript:window.open('http://get.adobe.com/flashplayer');\">Get the latest Flash player.</a></p></div>";
        $(contentID).append(videoContainerHTML);
        var flashvars =
        {
            file: video_link,
            image: "../JWPlayer/JWPlayer/novelis_logo.gif"
        }
        var params =
        {
            allowfullscreen: "true",
            allowscriptaccess: "always",
            wmode: "window"
        }
        var attributes =
        {
            id: "player1",
            name: "player1"
        }
        swfobject.embedSWF("../JWPlayer/JWPlayer/player.swf", "videoPlaceholder", "320", "196", "9.0.115", false, flashvars, params, attributes);
        var video_description = video_description.replace(/%20+/g, " ");
        var videoDescHTML = "<div id=\"videoDesc\">" + video_description + "</div>";
        $(contentID).append(videoDescHTML);
    }
}
//Execution Start from here after document is ready
$(document).ready(function ()
{
    GetSPListData();
});


