﻿var lastPage = 2;
var curPage = 2;
var count = 0;
var amtToRotate = 0;
var rotationAmt = 0;
var slideWidth = 1239;
var lastSlideX = 0;
var angleOffset = 0;
var maxMove = 0;
var fromNav = false;
var timer;
var timeoutAmt = 200;
var homeSlider;

$(document).ready(homepageInit);

isHomePage = true;

function homepageInit() {
    //initHomepageFlash();
    //initHomepageFeature();
    //initBlogs();
    initNewsletterSignup();
}

function setupSlider() {
    count = $('.royalSlidesContainer li.royalSlide').length;
    lastSlideX = (count) * slideWidth;
    // Set total width to contain slides and duplicates (for looping)
    $('.royalSlidesContainer').width((count + 4) * slideWidth);
    if (noTouchControls)
        $('.royalSlidesContainer').css('left', -(slideWidth * 2));
    maxMove = ((count + 1) * slideWidth);
    amtToRotate = 360 / count;
    rotationAmt = (amtToRotate / 2) + 9;

    $('.royalSlider').click(onTouch);

    if (!isIpadTest) {
        // For looping: Duplicate first two and last two items and add to the end and beginning of the slider, respectively
        var firstSlide = $('.royalSlidesContainer li:eq(0)').clone();
        var secondSlide = $('.royalSlidesContainer li:eq(1)').clone();
        var lastSlide = $('.royalSlidesContainer li:eq(' + (count - 1) + ')').clone();
        var secondToLastSlide = $('.royalSlidesContainer li:eq(' + (count - 2) + ')').clone();

        $(lastSlide).insertBefore('.royalSlidesContainer li:first');
        $(secondToLastSlide).insertBefore('.royalSlidesContainer li:first');
        $(firstSlide).insertAfter('.royalSlidesContainer li:last');
        $(secondSlide).insertAfter('.royalSlidesContainer li:last');
    }
}

// When clicked or touched, stop the auto slideshow
function onTouch() {
    homeSlider.stopSlideshow();
}

function sliderCheck() {
    if (isIpadTest)
        return;
    var currentSlide = homeSlider.currentSlideId;
    // Copy of last slide, snap to end
    if (currentSlide == 1) {
        $('.royalControlNavCenterer a').eq(count + 1).addClass('current');
        var moveTo = "" + -slideWidth * (count + 1) + "px";
        $('.royalSlidesContainer').css('left', moveTo);
        homeSlider.currentSlideId = count + 1;
    }
    // Actual last slide
    else if (currentSlide == count + 2) {
        $('.royalControlNavCenterer a').eq(2).addClass('current');
        var moveTo = "" + (-slideWidth * 2) + "px";
        $('.royalSlidesContainer').css('left', moveTo);
        homeSlider.currentSlideId = 2;
    }

}

function sliderStart() {
    // Hide unused nav buttons
    if (!isIpadTest) {
        $('.royalControlNavCenterer a:eq(0)').hide();
        $('.royalControlNavCenterer a:eq(1)').hide();
        $('.royalControlNavCenterer a').eq(count + 3).hide();
        $('.royalControlNavCenterer a').eq(count + 2).hide();
        $('.royalControlNavCenterer a:eq(2)').addClass('current');
    }
}

function initHomepageFeature() {
    setupSlider();

    if (!isIpadTest) {
        $('#myGallery1').hover(
			function () {
			    $('#myGallery1 a.arrow').fadeIn(300);
			},
			function () {
			    $('#myGallery1 a.arrow').fadeOut(300);
			}
		);
    }

    /*
    function loaded() {
    myScroll = new iScroll('wrapper', {
    snap: 'li',
    useTransition: false, // improves iPad readability/performance?
    momentum: false,
    hScrollbar: false,
    vScrollbar: false,
    onScrollEnd: function () {
    // We've just stopped, and we're on the first or last slide
    // Let the slider snap to a new location, then re-enable it
    curPage = this.currPageX;
    if (curPage == (count + 2)) {
    // At the last slide, snap to it's duplicate at the start
    //console.log('snap to start');
    this.x = -(slideWidth * 2);
    this.curPageX = 2;
    this.scrollToPage(2, 0, snapSpeed);
    lastPage = curPage;
    }
    else if (curPage == 1) {
    // At the first slide, snap to it's duplicate at the end
    //console.log('snap to end');
    this.x = -maxMove;
    this.curPageX = (count);
    this.scrollToPage(count + 1, 0, snapSpeed);
    lastPage = curPage;
    }
    else {
    rotateNav();
    lastPage = curPage;
    }
    if (preventNextScroll) {
    //this.disable();
    //setTimeout(function () { myScroll.enable(); }, 600);
    //console.log('scrolling re-enabled');
    preventNextScroll = false;
    }
    },
    onTouchEnd: function () {
    var forwardMove = false;
    if (this.currPageX > lastPage)
    forwardMove = true;

    // Need to stop carousel from going past the first and last slides without refreshing position
    // Just released touch, and on, or headed to, first slide
    if ((!forwardMove && lastPage == 3) || (forwardMove && lastPage == (count + 1))) {
    preventNextScroll = true;
    }
    // Just released touch, and on, or headed to, last slide
    else if ((forwardMove && lastPage == count) || (!forwardMove && lastPage == 2)) {
    preventNextScroll = true;
    }
    if (preventNextScroll) {
    //console.log('prevented');
    }
    //console.log('reset parallax touch end');
    //var t = setTimeout(resetParallax, 1000);
    resetParallax();
    },
    onBeforeScrollStart: function () {
    if (preventNextScroll) {
    //console.log('prevented');
    $(this).click(function () {
    // Prevents further action 
    // TODO: 
    // Might need to add something here?
    });
    }
    },
    onScrollMove: function () {
    rotateNav();
    updateParallax();
    }
    });
    };
    // Activate touch controls for home slideshow
    if (!noTouchControls) { 
    $(document).ready(function () {
    loaded(); 
    // Start the slider at page 2
    setTimeout(function () { myScroll.scrollToPage(2, 0, snapSpeed); }, 500); 
    })
    }

    $('#homeSlideContainer #prev').click(function () {
    scrollSlider(curPage - 1);
    });

    $('#homeSlideContainer #next').click(function () {
    scrollSlider(curPage + 1);
    });

    $('#selector').rotate(rotationAmt);
    */

}

/*
function resetParallax() {
var frontImages = $('#scroller li.featured img');
//console.log(frontImages.length);
$(frontImages).each(function(){
$(this).animate({ marginLeft: 0 });
});
//$(frontImages).css('marginLeft', 0);
}

function updateParallax() {
//var frontImg = ($('#scroller li.featured').eq(curPage)).find('img');
var frontImg = $('#scroller li.featured').find('img');
var moveAmt = (myScroll.x + (curPage * slideWidth)) / 3;
$(frontImg).css('marginLeft', moveAmt);
}

function scrollSlider(page, boolFromNav) {
// Was the click from the nav ring?
fromNav = boolFromNav;

if (!noTouchControls) {
// Reset page number when looping
if (page > count + 2) {
snapToStart = true;
page = 2;
}
else if (page < 1) {
snapToEnd = true;
page = count + 1;
}
myScroll.scrollToPage(page, 0, snapSpeed);
}
// Scrolling function when touch is disabled
else {
// Reset page number when looping
if (page > count + 1) {
snapToStart = true;
page = 2;
}
else if (page < 2) {
snapToEnd = true;
page = count + 1;
}
// Page 2 is the actual start page, not a duplicate
if (snapToStart) {
// Reset to the start
var callback = function () { $('#scroller').css('marginLeft', -(slideWidth * 2)); curPage = page; };
scrollToPageIE(curPage + 1, callback);
snapToStart = false;
return;
}
// Page Count+1 is the actual last slide, not a duplicate
else if (snapToEnd) {
// Reset to the end
var callback = function () { $('#scroller').css('marginLeft', -maxMove); curPage = page; };
scrollToPageIE(curPage - 1, callback);
snapToEnd = false;
return;
}
scrollToPageIE(page);
}
}

function scrollToPageIE(page,callback) {
var pageDif = page - curPage;
curPage += pageDif;
$('#scroller').animate({
marginLeft: '-=' + (slideWidth * pageDif)
}, 450, callback);

rotateNav();
lastPage = curPage;
}

function setupSlider() {
count = $('#homeSlideContainer li.featured').length;
lastSlideX = (count) * slideWidth;
// Set total width to contain slides and duplicates (for looping)
$('#scroller').width((count + 4) * slideWidth);
if(noTouchControls)
$('#scroller').css('marginLeft', -(slideWidth * 2));
maxMove = ((count+1) * slideWidth);
amtToRotate = 360 / count;
rotationAmt = (amtToRotate / 2) + 9;

// For looping: Duplicate first two and last two items and add to the end and beginning of the slider, respectively
var firstSlide = $('#homeSlideContainer ul:eq(0)').clone();
var secondSlide = $('#homeSlideContainer ul:eq(1)').clone();
var lastSlide = $('#homeSlideContainer ul:eq(' + (count-1) + ')').clone();
var secondToLastSlide = $('#homeSlideContainer ul:eq(' + (count-2) + ')').clone();

$(lastSlide).insertBefore('#homeSlideContainer ul:first');
$(secondToLastSlide).insertBefore('#homeSlideContainer ul:first');
$(firstSlide).insertAfter('#homeSlideContainer ul:last');
$(secondSlide).insertAfter('#homeSlideContainer ul:last');
}

var lastRot = 0;

function rotateNav() {
var pageDif = (curPage - lastPage);

if (!fromNav && noTouchControls) {
// Need to account for edge cases
if (pageDif < -count)
pageDif = -1;
else if (pageDif > count)
pageDif = 1;
else if (pageDif > 1)
pageDif = -1;
else if (pageDif < -1)
pageDif = 1;
}
// Reset the tags
fromNav = false;
rotationAmt += (pageDif * amtToRotate);

// Move the nav circle for touch controls
if (!noTouchControls) {
var xValue = -parseInt(myScroll.x) - (slideWidth * 2);
lastRot = rotationAmt;
// When the nav is circling back to the start, prevent it from spinning back the opposite way
if (pageDif < -(count - 2))
angleOffset += 360;
else if (pageDif > (count - 2))
angleOffset -= 360;
rotationAmt = -(((lastSlideX - xValue) / lastSlideX) * 360) + 43 + angleOffset; // 43 is the starting angle of the first nav spot
}

$('#selector').rotate({
animateTo: rotationAmt
});
}
*/



/*
function initHomepageFlash() {
var params = {};
params.wmode = "transparent";

var flashVars = {};
flashVars.File = "Resources/Xml/HomepageFlashSpots.xml";

swfobject.embedSWF("Resources/Swf/APWebsite2009_HomepageFlash.swf", "homepageFlashDiv", "980", "512", "9.0.0", flashExpressInstallPath, flashVars, params);
}
*/

function initBlogs() {
    var flashvars = {};
    flashvars.BlogHtml = $("#blogDataDiv").html();
    jQuery.each(jQuery.browser, function (i, val) {
        if (val && i == "msie") {
            flashvars.BlogHtml = escape(ieInnerHTML($("#blogDataDiv").html()));
        }
    });

    swfobject.embedSWF("Resources/Swf/HomepageBlogPreview.swf", "blogDataDiv", "480", "200", "9.0.0", flashExpressInstallPath, flashvars);
}

function ieInnerHTML(innerHtml) {
    var z = innerHtml.match(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g);
    if (z) {
        for (var i = 0; i < z.length; i++) {
            var y, zSaved = z[i];
            z[i] = z[i].replace(/(<?\w+)|(<\/?\w+)\s/, function (a) { return a.toLowerCase(); });
            y = z[i].match(/\=\w+[?\s+|?>]/g);
            if (y) {
                for (var j = 0; j < y.length; j++) {
                    z[i] = z[i].replace(y[j], y[j].replace(/\=(\w+)([?\s+|?>])/g, '="$1"$2'));
                }
            }
            innerHtml = innerHtml.replace(zSaved, z[i]);
        }
    }
    return innerHtml;
}

function initNewsletterSignup() {
    $("input[name='NewsLetterEmail']").keypress(inputKeyPress);
    $("input[name='NewsLetterEmail']").blur(newsletterBlur);
}

function inputKeyPress(e) {
    if (e.which == 13) {
        newsletterSignup();
        return false;
    }
    else {
        return true;
    }

}

function newsletterBlur() {
    if ($("input[name='NewsLetterEmail']").val() == "") {
        $("input[name='NewsLetterEmail']").val("Enter Your E-mail Address");
    }
}

var NewsLetterEmail = "";
function newsletterSignup() {
    NewsLetterEmail = $("input[name='NewsLetterEmail']").val();
    if (NewsLetterEmail != null && NewsLetterEmail != "" && NewsLetterEmail != "Enter Your E-mail Address" && isValidEmail(NewsLetterEmail)) {
        AtomicPlaypen.AjaxAPI.AtomicPlaypenAjax.NewsletterSignup(NewsLetterEmail, NewsletterSignup_Callback);
    }
    else {
        //alert('Please enter your e-mail address and try again.');
    }
}

function NewsletterSignup_Callback(res) {
    if (res.error) {
        showNewsletterFailMsg();
    }
    else {
        showNewsletterSuccessMsg();
        $.cookie('NewsLetterEmail', NewsLetterEmail);
    }
}

function showNewsletterSuccessMsg() {
    showNewsletterMsg($(".newsletterSuccess").html());
}

function showNewsletterFailMsg() {
    showNewsletterMsg($(".newsletterFail").html());
}

function showNewsletterMsg(msg) {
    $(".newsLetterForm").slideUp(400, function () { $(this).html(msg).slideDown(); });
}

