var featuredcontentglider =
{
    csszindex: 100,
    ajaxloadingmsg: '<b>Fetching Content. Please wait...</b>',
    glide: function (config, showpage, isprev) {
        var selected = parseInt(showpage)
        if (selected >= config.$contentdivs.length) { //if no content exists at this index position
            alert("No content exists at page " + (selected + 1) + "! Loading 1st page instead.")
            selected = 0
        }
        var $target = config.$contentdivs.eq(selected)

        var count = config.$contentdivs.length;
        for (var i = 0; i < count; i++) {
            var $temp = config.$contentdivs.eq(i)

            if (i != selected) {
                $temp.fadeOut(700);
                var offSrc = config.$toc.eq(i).find('img').attr('offsrc');
                config.$toc.eq(i).find('img').attr('src', offSrc);
            }
            else {
                var relSrc = config.$toc.eq(i).find('img').attr('rel');
                config.$toc.eq(i).find('img').attr('src', config.$toc.eq(i).find('img').attr('activesrc'));

                if (i == 0) {
                    $('.feature_text_heading').html('Welcome to Touchlab');
                    $('.feature_text_body').html('Touchlab, a division of Media24 specialising in applications and publishing for touch devices.');
                    $('.feature_text_link').attr('href', 'http://www.facebook.com/thetouchlab');
                }
                else if (i == 1) {
                    $('.feature_text_heading').html('ABC van Diere');
                    $('.feature_text_body').html('This Afrikaans language app, brought to you by Baba & Kleuter magazine, will teach your toddler or pre-schooler the alphabet through fun interactions with South African animals.');
                    $('.feature_text_link').attr('href', 'http://itunes.apple.com/za/app/abc-van-diere/id457557736?mt=8');
                }
                else if (i == 2) {
                    $('.feature_text_heading').html('CoverMag');
                    $('.feature_text_body').html('Have you ever wanted to be a cover girl or guy!? Cover App gives you the opportunity to feature on the cover of South Africas biggest magazines – YOU, Huisgenoot and DRUM.');
                    $('.feature_text_link').attr('href', 'http://itunes.apple.com/za/app/covermag/id450772632?mt=8');
                }
                else if (i == 3) {
                    $('.feature_text_heading').html('Die Burger');
                    $('.feature_text_body').html('Die Burger is now available on iPad! Get the latest local and international news, sports, editorial comment, photo galleries, cartoons, weekend entertainment, weather forecasts...');
                    $('.feature_text_link').attr('href', 'http://itunes.apple.com/za/app/die-burger/id452212431?mt=8');
                }
                else if (i == 4) {
                    $('.feature_text_heading').html('PhotoSync');
                    $('.feature_text_body').html('Tagged Photos Sync for Facebook allows you to easily select and download photos you have been tagged in on Facebook. Download all the photos your friends uploaded to Facebook of you!');
                    $('.feature_text_link').attr('href', 'photosync.html');
                }
                else if (i == 5) {
                    $('.feature_text_heading').html('GO! Travel');
                    $('.feature_text_body').html('The go! South Africa travel app is a product of Touchlab, in collaboration with go! travel magazine, Eat Out restaurant guide and SA Venues travel website.');
                    $('.feature_text_link').attr('href', 'gotravelsa/index.html');
                }
            }
        }

        if (config.$togglerdiv.attr('lastselected') == null || parseInt(config.$togglerdiv.attr('lastselected')) != selected) {
            var $selectedlink = config.$toc.eq(selected)
            config.$next.attr('loadpage', (selected < config.$contentdivs.length - 1) ? selected + 1 + 'pg' : 0 + 'pg')
            config.$prev.attr('loadpage', (selected == 0) ? config.$contentdivs.length - 1 + 'pg' : selected - 1 + 'pg')
            var startpoint = (isprev == "previous") ? -config.startpoint : config.startpoint
            $target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it's just out of view before animating it
            var endpoint = (config.leftortop == "left") ? { left: 0} : { top: 0} //animate it into view
            $target.animate(endpoint, config.speed)

            config.$toc.css({ 'border': '2px solid #b9baba' })
            $selectedlink.css({ 'border': '2px solid #29C2F0' })

            config.$togglerdiv.attr('lastselected', selected + 'pg')

            $target.show();
            //$old.fadeOut(700);
        }
    },

    getremotecontent: function (config) {
        config.$glider.html(this.ajaxloadingmsg)
        $.ajax({
            url: config.remotecontent,
            error: function (ajaxrequest) {
                config.$glider.html('Error fetching content.<br />Server Response: ' + ajaxrequest.responseText)
            },
            success: function (content) {
                config.$glider.html(content)
                featuredcontentglider.setuptoggler(config)
            }
        })
    },

    aligncontents: function (config) {
        config.$contentdivs = $("#" + config.gliderid + " ." + config.contentclass)
        config.$contentdivs.css(config.leftortop, config.startpoint).css({ height: config.$glider.height(), visibility: 'visible' }) //position content divs so they're out of view:
    },

    setuptoggler: function (config) {
        this.aligncontents(config)
        config.$togglerdiv.hide()
        config.$toc.each(function (index) {
            $(this).attr('pagenumber', index + 'pg')
            if (index > (config.$contentdivs.length - 1))
                $(this).css({ display: 'none' }) //hide redundant "toc" links
        })
        var $nextandprev = $(".next, .prev")
        $nextandprev.click(function (event) { //Assign click behavior to 'next' and 'prev' links
            featuredcontentglider.glide(config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
            event.preventDefault() //cancel default link action
        })
        config.$toc.click(function (event) { //Assign click behavior to 'toc' links
            featuredcontentglider.glide(config, this.getAttribute('pagenumber'))
            event.preventDefault()
            clearInterval(window[config.togglerid + "timer"]);
        })
        config.$togglerdiv.fadeIn(1000, function () {
            featuredcontentglider.glide(config, config.selected)
            if (config.autorotate == true) { //auto rotate contents?
                config.stepcount = 0 //set steps taken
                config.totalsteps = config.$contentdivs.length * config.autorotateconfig[1] //Total steps limit: num of contents x num of user specified cycles)
                featuredcontentglider.autorotate(config)
            }
        })
        config.$togglerdiv.click(function () {
            featuredcontentglider.cancelautorotate(config.togglerid)
        })
    },

    autorotate: function (config) {

        var rotatespeed = config.speed + config.autorotateconfig[0]
        window[config.togglerid + "timer"] = setInterval(function () {
            if (config.totalsteps > 0 && config.stepcount >= config.totalsteps) {
                clearInterval(window[config.togglerid + "timer"])

            }
            else {
                config.$next.click()
                config.stepcount++
            }
        }, rotatespeed)
    },

    cancelautorotate: function (togglerid) {
        //if (window[togglerid + "timer"])
        //clearInterval(window[togglerid + "timer"])
    },

    getCookie: function (Name) {
        var re = new RegExp(Name + "=[^;]+", "i") //construct RE to search for target name/value pair
        if (document.cookie.match(re)) //if cookie found
            return document.cookie.match(re)[0].split("=")[1] //return its value
        return null
    },

    setCookie: function (name, value) {
        document.cookie = name + "=" + value
    },

    init: function (config) {
        $(document).ready(function () {
            config.$glider = $("#" + config.gliderid)
            config.$togglerdiv = $("#" + config.togglerid)
            config.$toc = config.$togglerdiv.find('.feature_thumbs')
            config.$next = $('.next')
            config.$prev = $('.prev')
            config.$prev.attr('buttontype', 'previous')
            var selected = (config.persiststate) ? featuredcontentglider.getCookie(config.gliderid) : config.selected
            config.selected = (isNaN(parseInt(selected))) ? config.selected : selected //test for cookie value containing null (1st page load) or "undefined" string	
            config.leftortop = (/up/i.test(config.direction)) ? "top" : "left" //set which CSS property to manipulate based on "direction"
            config.heightorwidth = (/up/i.test(config.direction)) ? config.$glider.height() : config.$glider.width() //Get glider height or width based on "direction"
            config.startpoint = (/^(left|up)/i.test(config.direction)) ? -config.heightorwidth : config.heightorwidth //set initial position of contents based on "direction"
            if (typeof config.remotecontent != "undefined" && config.remotecontent.length > 0)
                featuredcontentglider.getremotecontent(config)
            else
                featuredcontentglider.setuptoggler(config)
            $(window).bind('unload', function () { //clean up and persist
                config.$togglerdiv.unbind('click')
                config.$toc.unbind('click')
                config.$next.unbind('click')
                config.$prev.unbind('click')
                if (config.persiststate)
                    featuredcontentglider.setCookie(config.gliderid, config.$togglerdiv.attr('lastselected'))
                config = null

            })
        })
    }
}
