var SAPCareerRegion = window.SAPCareerRegion || {};

var listScroll_itemList = [];
function AssignListScrollVar(scroll_list) {
    listScroll_itemList = scroll_list;
}

(function($) {

    var listItemCarousel = null;
    var currentIndex = 0;
    var firstLoad = true;
    var currentPageName;

    SAPCareerRegion.Carousel = (function() {
        var _this = this;
        var _order;
        var _id;
        var _heroScroll1_itemList = [];
        var carouselfirst = {

            heroScroll_initCallback: function(carousel) {
                $('#mycarousel-next').click(function() {
                    carousel.next();
                    return false;
                });

                $('#mycarousel-prev').click(function() {
                    carousel.prev();
                    return false;
                });
            },
            heroScroll_getItemHTML: function(item) {
                return '<img src="' + item.image + '" alt="' + item.title + '" />';
            },
            heroScroll_itemVisibleInCallback: function(carousel, item, i, state, evt) {
                // The index() method calculates the index from a
                // given index who is out of the actual item range.
                var idx = carousel.index(i, _heroScroll1_itemList.length);
                carousel.add(i, _this.heroScroll_getItemHTML(_heroScroll1_itemList[idx - 1]));
                $('#caption1').html(_heroScroll1_itemList[idx - 1].title + '</a>');
                //if($('.jcarousel-container-horizontal')){ $('.carouseldemo > .jcarousel-skin-tango > .jcarousel-container-horizontal > .overlayPanel').remove(); }
                //$('.carouseldemo > .jcarousel-skin-tango > .jcarousel-container-horizontal').append('<div class="overlayPanel">' + heroScroll_itemList[idx - 1].title + '</div>');
                if (_heroScroll1_itemList.length <= 1) {
                    $('#mycarousel-next').hide();
                    $('#mycarousel-prev').hide();
                } else {
                    $('#mycarousel-next').show();
                    $('#mycarousel-prev').show();
                }
            },
            heroScroll_itemVisibleOutCallback: function(carousel, item, i, state, evt) {
                carousel.remove(i);
            },
            heroScroll_reloadCallback: function(carousel) {
                carousel.reset();
            },
            init: function(id) {
                _this = this;
                jQuery(id).jcarousel({
                    scroll: 1,
                    visible: 1,
                    animation: 300,
                    wrap: "circular",
                    initCallback: _this.heroScroll_initCallback,
                    buttonNextHTML: null,
                    buttonPrevHTML: null,
                    itemVisibleInCallback: { onBeforeAnimation: _this.heroScroll_itemVisibleInCallback },
                    itemVisibleOutCallback: { onAfterAnimation: _this.heroScroll_itemVisibleOutCallback },
                    reloadCallback: _this.heroScroll_reloadCallback

                });
            }
        };
        return { //public members
            init: function() {

                if ($('#topWideCarousel').length > 0) { carouselfirst.init('#topWideCarousel'); }

            },
            AssignVar: function(scroll_list) {
                _heroScroll1_itemList = scroll_list;
            }
        }
    })();

    function getIndexFromName(collection, name) {
        var index = 0;
        for (var key in collection) {
            if (collection[key].name != null && name != null && (collection[key].name.toLowerCase() == name.toLowerCase())) {
                index = parseInt(key);
            }
        }
        currentIndex = index;
        return index;
    }



    function listCarouselReset() {

        $('#listCarousel > li > a').removeClass('active');
        $('.link1').addClass('active');
        currentIndex = 1;
        if (contentHeroCarousel != null) {
            contentHeroCarousel.reset();
        }

        if (listItemCarousel != null) {
            listItemCarousel.reset();
        }
        $('.contentRightCol').find('.content').html(listScroll_itemList[0].title);

    }


    function listCarouselRemoveEmptyRows() {

        $('#listCarousel > li').each(function(index) {

            if ($(this).text() == '') {
                $(this).hide();
            }
        });
    }

    function listCarouselFilteredSize() {
        var res = 0;

        for (i = 0; i < listScroll_itemList.length; i++) {
            if (listScroll_itemList[i].title != '') {
                res++;
            }
        }

        return res;
    }

    function listItemClick(index) {
        //alert(index);

        if (index > listScroll_itemList.length - 1) { index = 0; }
        if (index < 0) { index = listScroll_itemList.length - 1; }

        $('.contentRightCol').find('.content').html(listScroll_itemList[index].content);

        //contentHeroCarousel.scroll(index);
        $('#listCarousel > li > a').removeClass('active');
        $('.link' + index).addClass('active');


        if (listItemCarousel != null) {
            listItemCarousel.scroll(index + 1);
        }

        if ($('.category').length > 0) {
            $('.category').click(
			function() {
			    $(this).toggleClass('expanded');
			}
		);
        }

        /*
        $('.officesList a').click(
        function(){
			       
        alert($('#listCarousel li:eq('+ index +') a').text());
        //window.tracker.track("Local Office Click", {'region': $('#listCarousel li:eq('+ itemIndex +') a').text(), 'country':$(this).text() });
        window.tracker.track("Local Office Click", {'country':$(this).text(),'region': 'test' });
        }
        );
        */
        currentIndex = index;

        //if Local page
        if (currentPageName.toLowerCase() != 'sapoffices' && currentPageName.toLowerCase() != 'findyourjob') {
            makeAjaxCall(index);
        } else {
            updateOfficesList(index);
        }
        /*
        if(index == 1){
        listItemCarousel.scroll(1);
        }
        else if(index%(7-currentScroll) ==0){
        listItemCarousel.scroll(index-1);
        currentScroll++;
        }*/
    }


    function populateNoScrollList() {
        /* When the profile list are static without carousel scroller, generate the link text with list on load */

        //var profileLinks = $('#listCarousel');

        $.each(listScroll_itemList, function(key, value) {
            var index = key;
            var display = '';
            if (this.title == '') {
                display = 'style="display:none;"';
            }

            var ele = $('<li ' + display + '><a class="link' + index + '" href="#/' + this.name + '">' + this.title + '</a></li>'); // name
            $('#listCarousel').append(ele);
            //$('#listCarousel').append('<li><a onClick="listItemClick(' +index+ ')" class="link' + index +'" href="javascript:void(0)">' + this.title + '</a></li>');
        });

        $('.link' + currentIndex).addClass('active');
        $('.contentRightCol').find('.content').html(listScroll_itemList[currentIndex].content);
    }



    /* list Scroll */

    function listItemLoadCallbackFunction(carousel, state) {
        listItemCarousel = carousel;
        for (var i = carousel.first; i <= carousel.last; i++) {
            // Check if the item already exists
            if (carousel.has(i)) {
                continue;
            }

            if (i > listScroll_itemList.length) {
                break;
            }

            carousel.add(i, listScroll_getItemHTML(listScroll_itemList[i - 1], i));
        }
        //carousel.setup();
    };

    function listScroll_getItemHTML(item, index) {
        var ele = $('<a href="#/' + item.name + '"  class="link' + (index - 1) + '">' + item.title + '</a>');
        return ele;
    };


    $(document).ready(function() {

        SAPCareerRegion.Carousel.init();


        //if (listScroll_itemList.length > 6) {
        var listSize = listCarouselFilteredSize();
        if (listSize > 6) {
            jQuery('#listCarousel').jcarousel({
                vertical: true,
                visible: 6,
                scroll: 5,
                size: listSize,
                itemLoadCallback: { onBeforeAnimation: listItemLoadCallbackFunction }
            });

        }

        if (listItemCarousel == null) {
            populateNoScrollList();
        }

        var sPath = window.location.pathname;
        //var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
        var sPage = sPath.substring(sPath.lastIndexOf('/') + 1, sPath.lastIndexOf('.aspx'));
        currentPageName = sPage;

        //if Local page
        if (currentPageName.toLowerCase() != 'sapoffices' && currentPageName.toLowerCase() != 'findyourjob') {
            makeAjaxCall(currentIndex);
        }

        localOfficeTracking();

        listCarouselRemoveEmptyRows();


    });

    function makeAjaxCall(itemIndex) {
        //alert('making ajax call');
        var itemId = listScroll_itemList[itemIndex].id;

        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: "/webservices/view.svc/offices/" + currentPageName + "/" + itemId,
            dataType: "json",
            data: "{}",
            timeout: 1000000,
            success: function(response) {

                var json = JSON.stringify(response);
                var inst2 = JSON.parse(json);


                $('.contentRightCol').find('.content').html(inst2.Title + inst2.Body);
                //$('.contentRightCol').find('.content').html('<table class="event"><tr class="header"><td width="20%">EVENT TYPE</td><td width="37%">UNIVERSITY</td><td width="20%">DATE & TIME</td><td>LOCATION</td></tr><tr class="yellow"><td>Conference</td><td>National Association of Colleges and Employers (NACE)</td><td>June 1-4, 2010<br/>TIME TDB</td><td>Indianapolis, IN</td></tr><tr class="grey"><td>Conference</td><td>National Association of Colleges and Employers (NACE)</td><td>June 6-9, 2010 TIME TBD</td><td>Halifax, NS</td></tr><tr class="yellow"><td>Career Fair</td><td>National Association of Colleges and Employers (NACE)</td><td>June 6-9, 2010 TIME TBD</td><td>Halifax, NS</td></tr></table>');

                if ($('.category').length > 0) {
                    $('.category').click(
			        function() {
			            $(this).toggleClass('expanded');
			        }
		        );
                }




            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //if (XMLHttpRequest.responseText)          
                //alert(XMLHttpRequest.responseText);
                //else
                //$('.contentRightCol').find('.content').html(XMLHttpRequest.responseText + textStatus);
                //alert(textStatus + errorThrown);
            }
        });
    }


    function updateOfficesList(idx) {
        var trackIndex = idx;
        if (idx != 0) {
            idx = idx - 1;

            $('table.officesList tr.region:eq(' + idx + ')').css('display', 'block');
            $('table.officesList tr.region').not(':eq(' + idx + ')').css('display', 'none');

            window.tracker.track("Office List Click", { 'region': $('#listCarousel li:eq(' + trackIndex + ') a').text() });

        } else if (idx == 0) {
            $('table.officesList tr.region').css('display', 'block');
            window.tracker.track("Office List Click", { 'region': $('#listCarousel li:eq(0) a').text() });
        }


    }

    function hashChangedItem(event) {
        console.log(event);
        var hashValue = event.value.substring(1);

        var index = getIndexFromName(listScroll_itemList, hashValue);

        listItemClick(index);
    }



    SWFAddress.addEventListener(SWFAddressEvent.CHANGE, hashChangedItem);

    function localOfficeTracking() {
        $('.officesList a').click(function() {
            var regionName = $.trim($(this).parent().parent().parent().parent().parent().find(':first-child h3').text());
            window.tracker.track("Local Office Click", { 'region': regionName, 'country': $(this).text() });
        });
    }

} (jQuery));
