var popup = $('#popup'); //create a reusable variable for Pop up
var pod_frame = $('.pod-frame');
var podLoaded;
var vidFlag = false; //video breadcrumb status

var medianWidth; //Central Menu Width (Median Width)
var dist;

var $containerWidth;
var $bodyWidth;
var $median;
var $dragger;
var $draggerWidth;
var $draggerContainerWidth;
var $podHolderWidth;

var podToAnimate;
var medianOffset;
var animSpeed;
var animSpeedFast;
var rightVal;
var leftVal;
var scrollLimitModifier;

// click timer variables
var clickTimer;
var mouseUp;
var incrementing;

//scroll
var scrollAmount;

$(function() {
    initHelpBar();
    country_dropdown();
    resetTextbox();
    if ($.browser.msie) {	//Set text shadow for menu & footer
        $('.menu li a').textShadow();
        $('.footer ul li a, .footer ul li:first').textShadow({ x: 1, y: 1, radius: 1, color: "#33700F" });
        $('.footer ul li a').css({ 'text-decoration': 'none', 'border-bottom': '1px solid #fff' });

        if (parseInt($.browser.version) == 7) { //if IE 7, 
            $('.menu li a').textShadow({ x: 1, y: 10, radius: 1, color: "#33700F" }); //fix shadow alignment issues
            $('.pod-container').css('background-position', ($(window).width() - 967) / 2 + ' 0'); //align bg
        }
    }

    /*Menu Pulsate STARTS Here - Except for IE - PNG Gradient Issue*/
    var pulsateImages = $(".scroll-left img, .scroll-right img");
    if ($.browser.msie) { //if IE, do not show pulsate
        pulsateImages.hide();
    }
    else {
        for (var i = 0; i < 4; i += 1) {
            pulsateImages.animate({
                opacity: 1
            }, 750).animate({
                opacity: 0
            }, 750);
        }
    }
    /*Menu Pulsate ENDS Here*/

    /* initialize global variables */
    medianWidth = $('.center-menu-holder').width(); //Central Menu Width (Median Width)
    dist = medianWidth / 2;

    $containerWidth = $('.pod-holder').length * $('.pod-holder').width();
    $bodyWidth = $('.pod-container').width();
    $median = $bodyWidth / 2;
    $dragger = $('.dragger');
    $draggerWidth = $dragger.width();
    $draggerContainerWidth = $('.dragger_container').width();
    $podHolderWidth = $('.pod-holder').width();

    podToAnimate = Math.ceil($('.pod-container').find('.pod-holder').size() / 2);
    medianOffset = $('.center-menu-holder').offset().left;
    animSpeed = 12;
    animSpeedFast = 45;
    scrollLimitModifier = 2 * Math.ceil(($bodyWidth - $podHolderWidth) / ($podHolderWidth * 2));

    mouseUp = true;
    incrementing = false;

    $('.pod-frame').width($containerWidth); //Setting exact width for pod frame
    //alert(Math.abs($containerWidth / 2 - $median));
    if ($containerWidth > $bodyWidth)
        $('.pod-frame').css('left', -Math.abs($containerWidth / 2 - $median) + 'px'); //Center Align the pod frame

    $(window).resize(function() { //Fix the alignment of pods when window is resized
        if ($containerWidth > $bodyWidth)
            $('.pod-frame').css('left', -Math.abs($containerWidth / 2 - $('.pod-container').width() / 2)); //Center Align the pod frame
    });

    nearestPod(); //Find the POD nearest to center menu and apply parting of PODs
    partingPod(rightVal, leftVal, 2000); //Initialize onload parting PODs

    $('.scroll-left, .scroll-right').click(function(e) { //Prevent Click event for the Scroll buttons
        e.preventDefault();
    });

    $('.scroll-left').mousedown(function() {		//When Left arrow is clicked
        mouseUp = false;
        setStartMillisecondTimer('right');
    }).mouseup(function() {		//When Left arrow click is released
        if (!incrementing)
            stopScroll();
        mouseUp = true;
    });

    $('.scroll-right').mousedown(function() {	//When Right arrow is clicked
        mouseUp = false;
        setStartMillisecondTimer('left');
    }).mouseup(function() {		//When Right arrow click is released
        if (!incrementing)
            stopScroll();
        mouseUp = true;
    });

    /*Dragger STARTS Here*/
    var draggerX = (($draggerContainerWidth - $draggerWidth) / 2) - 13; //Subtract margin-left of dragger
    //alert(draggerX);
    $dragger.css('left', draggerX + 'px');
    $dragger.draggable({ //initializw the bottome slider drag
        axis: "x",
        containment: "parent",
        drag: function(event, ui) {
            ScrollX();
        },
        stop: function(event, ui) {
            stopScroll();
        }
    });

    $dragger.mousedown(function() {
        partingPod(0, 0, 200); //Merge the central gap before animating
    });
    $dragger.mouseup(function() {
        stopScroll(); //Merge the central gap before animating
    });

    //scroll
    scrollAmount = ($containerWidth - $bodyWidth) / ($draggerContainerWidth - $draggerWidth - 26);
    /*Dragger ENDS Here*/

});

function nearestPod() {	//Find the POD nearest to the Median to apply the margin
    var podFrameLeft = parseFloat($('.pod-frame').css('left').replace('px', ''));
    var firstPodMarginLeft = parseFloat($('.pod-holder:eq(0)').css('marginLeft').replace('px', ''));
    $('.pod-frame').stop(true).css({ 'left': (podFrameLeft + firstPodMarginLeft) + 'px' });
    $('.pod-holder:eq(0)').stop(true).css({ 'marginLeft': '0px' });

    $('.pod-holder').each(function(i) {
        if ($(this).offset().left + ($podHolderWidth / 2) > medianOffset + (medianWidth / 2)) {	//if left position of the pod is more than center of Median
            podToAnimate = i; //the index of POD in the middle to be moved
            var podMarginLeft = parseFloat($('.pod-holder:eq(' + podToAnimate + ')').css('marginLeft').replace('px', ''));
            leftVal = (medianOffset - $podHolderWidth) - $(this).prev().offset().left;
            rightVal = medianWidth - ($(this).offset().left - medianOffset) - leftVal + podMarginLeft;
            return false; //Once the closest POD is found, stop the function
        }
    });
    $('.pod-frame').width($('.pod-frame').width() + rightVal + leftVal); //Add the increased margin width for the POD frame to  hold last POD
}

function partingPod(a, b, time, callback) {	//Function to part the PODs (Middle Pod margin, first pod margin, time)
    $('.pod-holder:eq(' + podToAnimate + ')').stop(true).animate({ //Middle Pod
        marginLeft: a + 'px'
    }, time, 'linear', callback);
    $('.pod-holder:eq(0)').stop(true).animate({ //First Pod
        marginLeft: b + 'px'
    }, time, 'linear');
}

// start the timer
function setStartMillisecondTimer(dir) {
    clickTimer = setTimeout(function() { checkTimerDuration(dir) }, 300);
}

// check to see after a short duration if the mouseup has been triggered
function checkTimerDuration(dir) {
    clearTimeout(clickTimer);

    if (!incrementing) {
        if (mouseUp) {
            incrementPods(dir);
        }
        else {
            movePods(dir);
        }
    }
}

function closeGap(dir, time, callback) {
    nearestPod();
    var firstMargin = $('.pod-holder:eq(0)').css('marginLeft').replace('px', '');

    if (dir == 'right')
        firstMargin += 220;

    partingPod(0, firstMargin, time, function() {


        var podFrameLeft = parseFloat($('.pod-frame').css('left').replace('px', ''));
        var firstPodMarginLeft = parseFloat($('.pod-holder:eq(0)').css('marginLeft').replace('px', ''));
        $('.pod-frame').stop(true).css({ 'left': (podFrameLeft + firstPodMarginLeft) + 'px' });
        $('.pod-holder:eq(0)').stop(true).css({ 'marginLeft': 0 });

        callback();
    });
}

function incrementPods(dir) {
    incrementing = true;
    var increment = true;
    var animateValue = $podHolderWidth - (medianWidth / 2);
    var btnsScrollTo = ($draggerContainerWidth - $draggerWidth - 26) / ($('.pod-holder').length - scrollLimitModifier);

    var closeGapSpeed = parseFloat($('.pod-holder:eq(' + podToAnimate + ')').css('marginLeft').replace('px', '')) * (100 / animSpeedFast);
    var podFrameSpeed = animateValue * (100 / animSpeedFast);
    var scrollSpeed = closeGapSpeed + podFrameSpeed;

    if (dir == 'left') {
        increment = parseFloat($dragger.css('left')) + $draggerWidth + btnsScrollTo <= $draggerContainerWidth;
        animateValue = '-=' + animateValue;
        btnsScrollTo = '+=' + btnsScrollTo;
    }
    else {
        increment = parseFloat($dragger.css('left')) - btnsScrollTo >= 0;
        animateValue = '+=' + animateValue;
        btnsScrollTo = '-=' + btnsScrollTo;
    }

    if (increment) {
        closeGap(dir, closeGapSpeed, function() {
            $('.pod-frame').stop(true).animate({ 'left': animateValue }, podFrameSpeed, 'linear', function() {
                incrementing = false;
                setTimeout('stopScroll()', 0);
            });
        });
        $dragger.stop(true, true).animate({ 'left': btnsScrollTo }, scrollSpeed, 'linear');
    }
    else {
        incrementing = false;
    }
};

function movePods(dir) {		//Function to SLide the entire POD set
    var animateValue = 0; //if right, set the values to 0
    var btnsScrollTo = 0;

    if (dir == 'left') {
        animateValue = -Math.abs($containerWidth - $bodyWidth);
        btnsScrollTo = $draggerContainerWidth - $draggerWidth - 26;
    }

    var scrollSpeed = Math.abs($dragger.position().left - btnsScrollTo) * (100 / animSpeed);

    if (scrollSpeed > 0) {
        var closeGapSpeed = parseFloat($('.pod-holder:eq(' + podToAnimate + ')').css('marginLeft').replace('px', '')) * (100 / animSpeed);
        closeGap(dir, closeGapSpeed, function() {
            $('.pod-frame').stop(true).animate({ 'left': animateValue }, scrollSpeed - closeGapSpeed, 'linear');
        });
        $dragger.stop(true).animate({ 'left': btnsScrollTo }, scrollSpeed, 'linear');
    }
};

function stopScroll() { 	//Stop the sliding of PODs
    $('.pod-holder:eq(' + podToAnimate + ')').stop(true);
    $('.pod-holder:eq(0)').stop(true);
    $('.pod-frame').stop(true);
    $dragger.stop(true);

    nearestPod(); //After the PODs are stopped, find the central POD for parting
    partingPod(rightVal, leftVal, 2000); //initialize the parting animation
    $dragger.css('left', (podToAnimate - (scrollLimitModifier / 2)) * ($draggerContainerWidth - $draggerWidth - 26) / ($('.pod-holder').length - scrollLimitModifier));
}

function ScrollX() {
    var draggerX = $dragger.position().left;
    var targX = -draggerX * scrollAmount;
    var thePos = $('.pod-frame').position().left - targX;
    $('.pod-frame').stop(true).animate({ left: "-=" + thePos }, 500); //move the pods
}

/*--------------------- HOMEPAGE POD - POP UP RELATED ACTIVITIES-------------------------*/

$(function() {
    $(".popup_content").css('height', '0');
    var currentPod_x = 0;
    var currentPod_y = 0;
    var podHeight = 0;
    var podWidth = 0;
    var popupHeight = 426; //Set the height when popup is open
    var popup_x = ($(window).width() - $('#popup').width()) / 2;
    //var popup_y = ($(window).height() - popupHeight) / 2;
    $(window).resize(function() { //Align the popup when window is resized
        popup_x = ($(window).width() - $('#popup').width()) / 2;
        //popup_y = ($(window).height() - popupHeight) / 2;
        $('#popup').css({ 'left': popup_x });
    });
    $('.pod, .pod-large, .menu li a, .buy-now, .help, .footer-menu li a').not('.menu li:first a').click(function(e) { //avoid pupup when home link is clicked
        var $this = $(this);

        if ($this.attr('target') == '_blank') {
            return;
        }
        e.preventDefault(); //Prevent default linking to the href 

        popupHeight = 426;
        if ($this.hasClass('ht_305')) { /*Set the smaller PopUp Height for product pages only*/
            popupHeight = 305;
        }
        else if ($this.hasClass('help')) {
            popupHeight = 328;
        }
        //popup_y = ($(window).height() - popupHeight) / 2;

        $('#overlay, #popup').css('display', 'none'); // hide the pop-up
        $('.content-holder').fadeTo('fast', 0).html(""); // clear the div

        /*Calculation related to the POD dimension,position etc and assigning it to the popup div*/
        currentPod_x = $this.offset().left;
        currentPod_y = $this.offset().top;
        podHeight = $this.height();
        podWidth = $this.width();

        var fetch_url = $(this).attr("href"); //href value of the link clicked 
        getPodPage(fetch_url); //function to be called when a page is visited directly

        $('#overlay').fadeTo("fast", 0.5); //open the background veil
        $('#popup').css({ 'width': podWidth, 'height': podHeight, 'left': currentPod_x, 'top': currentPod_y }); //Initial height&width = POD height&width & offset of last popup clicked

        $('#popup').animate({	//Open the popup from the location of the clicked POD
            opacity: 'show',
            left: popup_x,
            top: 90,
            width: 572,
            height: popupHeight  //322
        }, 400, false, function() {
            $('.home-div, .product-video-container').parents('#popup').addClass('color-panel');
            afterPopupOpen();
            vidFlag = false;
        });
        $(".popup_content").css({ height: popupHeight - 22 }); //Increase the height of the content dynamically

        $('.popup_close a, #overlay').click(function() {
            $('#popup').animate({ //Close the Popup to the last pod
                opacity: 'hide',
                left: currentPod_x,
                top: currentPod_y,
                width: podWidth,
                height: podHeight
            }, 400, function() {
                $('#overlay').fadeOut('fast'); //Hide gray bg when animation is complete
                $('.home-div, .product-video-container').parents('#popup').removeClass('color-panel');
                $('.popup_content').html('<div class="loader">Loading...</div>'); //Erase the previously loaded content
            });
        });

    }); //End of pod click function
});  //End of main function

function afterPopupOpen() {
    //popupLoaded = true;
    if (podLoaded == false) {
        $('.popup_content').html('<div class="loader">Loading...</div>'); /*Code when pop up is open*/
    }
    //podLoadComplete();

}
/*------------------------------------------------------------------------------------------------------*/

function podLoadComplete() {
    $(".popup_content").html('<div class="content-holder">' + htmlData + '</div>');
    initialize();
}

/*function podLoadComplete() { 
$(".popup_content").html('<div class="content-holder">' + htmlData + '</div>'); 
if ($.browser.msie) {
var newdata = $(".content-holder form").contents();
if(newdata) { 
$(".content-holder form").replaceWith(newdata); 
}
}
initialize(); 
}*/

function handelerror(jqXHR, textStatus, errorThrown) {
    var errorMsg = "<div class='errorMsgHolder'>The page you are trying to reach is not available right now. Please try again later.</div>";
    htmlData = errorMsg;
    podLoadComplete();
}

function getPodPage(fetch_url) {
    if (!fetch_url) {
        return;
    }

    $.ajax({
        url: fetch_url,
        cache: false,
        dataType: "html",
        type: "POST",
        data: ({ pod: 'true' }),
        error: handelerror,
        success: function(data, textStatus, jqXHR) {
            $('.content-holder').fadeTo('fast', 1);
            htmlData = data;
            podLoaded = true;
            $('#popup').removeClass('color-panel');
            podLoadComplete();
        }
    });
}

function initHelpBar() {
    if ($('.help-bar').length > 0) {
        // Trying if($('.help-bar')) will always return true since jQuery will return it as an object.
        //So we need to check the length of the object returned. If more than 0 then the element exists.
        var helpBarReq = $.cookie("helpBar");
        if (helpBarReq != 'false') {
            $('.help-bar').fadeIn();
        }
        $('.help-bar .close, .btn-startexploring').live('click', function() {
            $('.help-bar').slideUp(); //Close the default Help Bar
            $.cookie("helpBar", "false", { expires: 31, path: '/' });
        });
    }
}

function country_dropdown() {
    $('a').bind('mousedown', function() { //Allow css outline only on tab focus
        $(this).addClass('no_outline')
    }
		).bind('mouseup', function() {
		    $(this).removeClass('no_outline')
		});

    $('.country li a').live('click', function(e) {	//When Country Selector is Clicked
        if ($(this).parent().hasClass('active')) {
            e.preventDefault(); //prevent linking for the current locale
        }
        $('div.country').toggleClass('country_open').find('li:last').addClass('last-child'); //Toggle Dropdown open state & identify last li tag to set bg
        $(this).addClass('no_outline').parent().addClass('active').siblings().toggle().removeClass('active'); //Remove outline & show options
    });
    $('.country li:last a').hover(function() {
        $(this).closest('ul').toggleClass('bottom-bg'); //set bottom curve bg since last-child option is not cross browser CSS
    });
    $(document).bind('mousedown', function(e) { //Close the dropdown if clicked anywer else in the body
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass('country')) {
            $('.country').removeClass('country_open').find('li:not(.active)').hide();
        }
    });
}

function resetTextbox() {
    $("input[type=text]").not($('.search-bar-holder input[type=text]')).each(function() {
        this.value = $(this).attr('title'); //Reset the default value as in the title
        this.defaultValue = this.value;
        $(this).click(function() {
            if (this.value == this.defaultValue) {
                $(this).val("");
            }
            return false;
        });
        $(this).blur(function() {
            if (this.value == "") {
                $(this).val(this.defaultValue);
            }
        });
    });
}
