
var tipJump = 1;

var scrollTo = '';
var loc = window.location.href;
var urn_ = loc.split("?");
if (typeof urn_[1] != "undefined") {
    ar = urn_[1].split('&');
    for (var i = 0, len = ar.length; i < len; ++i) {
        var ent = ar[i];
        var ent_ = ent.split('=');
        if (ent_[0] == 'tips') {
            scrollTo = ent_[1];
        }
    }
    if (scrollTo != '') {
        tipJump = scrollTo;
    } else {
        tipJump = 1;
    }
}

function get_page() {
    var loco = window.location.href.replace(/\/$/g, "");
    var urno = loco.split("/");
    var numR = Number(urno.length) - 1;
    return urno[numR];
}

function show_all() {
    var loco = window.location.href;
    var urno = loco.split("#");
    if (urno.length > 1) {
        var numR = Number(urno.length) - 1;
        var reveal = urno[numR];
        if (reveal == 'showAll') {
            return true;
        }
        return false;
    }
    return false;
}

function showJuanBar() {
    $('.content', this).animate({ height: 80 }, 400);
    $('.contentCopy', this).animate({ height: 80 }, 200);
    $('.juanSheet').fadeOut(400);
    $('.juanSheet2').fadeIn(400);
}

function hideJuanBar() {
    $('.content', this).animate({ height: 31 }, 400);
    $('.contentCopy', this).animate({ height: 26 }, 400);
    $('.juanSheet2').fadeOut(400);
    $('.juanSheet').fadeIn(400);
}

var remove;
var hoverObject;
var worldofplenty = false;

try {
    function removeClass() {
        hoverObject.parent().parent().removeClass('hover');
        remove = null;
    }
} catch (err) { alert('function removeClass : ' + err.message); }

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();


$(document).ready(function () {

    try {

        $('.addTarget').attr('target', '_blank');

        //Styled selectbox
        if ($('.dropdown').length > 0) {
            $('.dropdown').selectbox({ maxLength: 40, debug: true });
        }

    } catch (err) { alert('select box error: ' + err.message); }

    try {
        //IE Fix for fading PNGs
        var i;
        for (i in document.images) {
            if (document.images[i].src) {
                var imgSrc = document.images[i].src;
                if (imgSrc.substr(imgSrc.length - 4) === '.png' || imgSrc.substr(imgSrc.length - 4) === '.PNG') {
                    document.images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + imgSrc + "')";
                }
            }
        }
    } catch (err) { alert('fading PNG fix : ' + err.message); }

    try {
        //Juan Bar Show and Hide
        $('.juanSheet2').css({ visibility: 'visible', display: 'none' });

        var juanBarConfig = {
            over: showJuanBar,
            timeout: 500,
            out: hideJuanBar
        };

        $('#juanBar').hoverIntent(juanBarConfig);

        //END Juan Bar Show and Hid
    } catch (err) { alert('Juans bar : ' + err.message); }

    try {

        $('#topNav > ul[id!=lang_select] li:eq(1)').hover(function () {
            clearTimeout(remove);
            remove = setTimeout("removeClass()", 2000);
        });

        //IE6 fix for dropdown navigation
        $('#topNav > ul[id!=lang_select] li').hover(function () {
            $(this).addClass('hover');
        }, function () {
            if ($(this).find('ul').length == 0) {
                $(this).removeClass('hover');
            } else if (remove == null) {
                $(this).removeClass('hover');
            }
        });

        $('#topNav > ul[id!=lang_select] li ul li').hover(function () {
            clearTimeout(remove);
            $(this).parent().parent().addClass('hover');
        }, function () {
            hoverObject = $(this);
            remove = setTimeout("removeClass()", 1000);
        });

    } catch (err) { alert('navigation js : ' + err.message); }

    try {

        //Faq Accorian
        $('#faqAccordion .answer').css('display', 'none');

        $('#faqAccordion .question').click(function () {
            if (!$(this).hasClass('currentOpen')) {
                $('#faqAccordion .question').removeClass('currentOpen');
                $('#faqAccordion .question').find('.active').removeClass('active');
                $(this).addClass('currentOpen');
                $('#faqAccordion .answer').each(function () {
                    if ($(this).css('display') != 'none') {
                        $(this).slideToggle('fast');
                    }
                });
                $(this).next().slideToggle('fast');
                $(this).children('.arrow').toggleClass('active');
            } else {
                $('#faqAccordion .question').removeClass('currentOpen');
                $('#faqAccordion .question').find('.active').removeClass('active');
                if ($(this).css('display') != 'none') {
                    $(this).next().slideToggle('fast');
                }
            }
        });

        // Uses show comments accordian
        $('#usesAccordion .answer').css('display', 'none');

        $('#usesAccordion .question').click(function () {
            $(this).next().slideToggle('fast');
            $(this).children('.arrow').toggleClass('active')
        });
    } catch (err) { alert('FAQ accordian : ' + err.message); }

    try {

        //Homepage carousel
        // LS
        // The below functions unbind and re initialises the carousel for Chrome bug. 

        var firstRun = true;
        var cur = 1;
        var carouselPaging = $('#carouselPaging').html();

        function init_carousel() {
            //$('#carouselPaging').html(carouselPaging);
            $('#homepageCarousel #carouselSlides').cycle({
                fx: 'scrollHorz',
                timeout: 5000,
                prev: '#prevButton',
                next: '#nextButton',
                easing: '',
                startingSlide: ( firstRun === true ? 0 : cur ),
                slideResize: 0,
                speed: 2000,
                pager: '#carouselPaging ul',
                pagerAnchorBuilder: function (idx, slide) {
                    return '#carouselPaging ul li:eq(' + idx + ') a';
                },
                before: function (curr, next, opts) {
                    if (cur == opts.slideCount) {
                        cur = 1;
                    } else {
                        cur++;
                    }
                },
                after: function () {
                    firstRun = false;
                }
            });
        }

        if ($('#homepageCarousel #carouselSlides').length > 0) {
            $(window).resize(function () {
                delay(function () {
                    $('#homepageCarousel #carouselSlides').cycle('destroy');
                    cur = cur - 1;
                    init_carousel();
                }, 500);
            });
        }

        init_carousel();

    } catch (err) { alert('Homepage carousel : ' + err.message); }


    try {

        //Uses carousel
        $('#usesCarousel #usesFrames').cycle({
            fx: 'custom',
            cleartypeNoBg: true,
            timeout: 0,
            speed: 500,
            sync: 0,
            cssBefore: {
                left: 50,
                opacity: 0,
                display: 'block',
                zIndex: '0'
            },
            animIn: {
                left: 0,
                opacity: 1,
                zIndex: '11'
            },
            animOut: {
                left: -50,
                opacity: 0,
                zIndex: '0'
            },
            pager: '#usesCarousel ul.controls',
            pagerAnchorBuilder: function (idx, slide) {
                return '#usesCarousel ul.controls li:eq(' + idx + ') a';
            }
        });

    } catch (err) { alert('Uses Carousel : ' + err.message); }

    try {

        //Top 10 carousel
        $('#top10Carousel #carouselSlides').cycle({
            fx: 'fade',
            timeout: 0,
            slideResize: 0,
            startingSlide: tipJump - 1,
            pager: '#top10Carousel ul.controls',
            pagerAnchorBuilder: function (idx, slide) {
                return '#top10Carousel ul.controls li:eq(' + idx + ') a';
            }
        });

    } catch (err) { alert('Top 10 Carousel : ' + err.message); }

    /*if (window.location.href.search(/\?/g) != "-1" && window.location.href.search(/tips/g) != '-1') {
    if (tipJump !== false) {

    $('.tips' + tipJump).trigger('click');
    }
    }*/

    try {

        //Footer text boxes
        $('.youtube').cycle({
            speed: 'fast',
            timeout: 0,
            cleartypeNoBg: true,
            next: '.youtube_leftButton',
            prev: '.youtube_rightButton'
        });

        if ($('#juanBarInner div.twitter p').length > 1) {
            $('.twitter').cycle({
                speed: 'fast',
                timeout: 0,
                cleartypeNoBg: true,
                next: '.twitter_leftButton',
                prev: '.twitter_rightButton'
            });
        } else {
            $('.twitter_leftButton, .twitter_rightButton').live('click', function () {
                return false;
            });
        }

        $('.facebook').cycle({
            speed: 'fast',
            timeout: 0,
            cleartypeNoBg: true,
            next: '.facebook_leftButton',
            prev: '.facebook_rightButton'
        });

    } catch (err) { alert('footer text boxes : ' + err.message); }

    try {

        // uses page - show more comments button
        $('.showMoreComments').live('click', function () {
            if ($('#usesAccordion .showCommentsAnswerTrigger').css('display') == 'block') {
                $(':first', $(this)).html('show more comments');
            } else {
                $(this).hide();
            }
            $('#usesAccordion .showCommentsQuestionTrigger').trigger('click');
            $('#juanBarInner').css({ 'position': 'absolute', 'top': '0' });
            $('#juanBarInner').attr('style', '');
            return false;
        });

        // uses page - add your own comment
        $('.showCommentForm').live('click', function () {
            if ($('#usesAccordion .showFormAnswerTrigger').css('display') == 'block') {
                $(':first', $(this)).html('Add your own comment');
            } else {
                $("#showMoreCommentsWrapper").css({ 'position': 'absolute', 'left': '315px', 'top': '-80px' });
                $(this).hide();
            }
            $('#usesAccordion .showFormQuestionTrigger').trigger('click');
            return false;
        });
        // uses page - show more comments button

        $('.showMoreTips').live('click', function () {
            if ($('#usesAccordion .showMoreTipsTrigger2').css('display') == 'block') {
                $(':first', $(this)).html('View more tips');
            } else {
                $(this).css('display', 'none');
            }
            $('#usesAccordion .showMoreTipsTrigger1').trigger('click');
            return false;
        });

    } catch (err) { alert('Uses button triggers : ' + err.message); }

    //Range carousel

    /*
    $('#plentyRangeIcons ul li').click(function () {

    $('#plentyRangeIcons ul li, #plentyRangePackshot img').removeClass('currentImage');

    var activeImage = '.' + $(this).attr('class');

    $('#plentyRangeIcons ul li' + activeImage).addClass('currentImage');
    $('#plentyRangePackshot img' + activeImage).addClass('currentImage');
    });*/

    try {

        $('#plentyRangePackshot').cycle({
            timeout: 0,
            speed: 700,
            cleartypeNoBg: true,
            cleartype: true,
            pager: '#plentyRangeIcons ul',
            pagerAnchorBuilder: function (idx, slide) {
                return '#plentyRangeIcons ul li:eq(' + idx + ') a';
            }
        });

    } catch (err) { alert('Plenty range pack shot : ' + err.message); }

    // below jumps to screen related to 'uses' links in carasol
    //try {

    //} catch (err) { alert('Uses Carousel Jumper : ' + err.message); }

    try {

        // makes sure the body is exactly 20px larger than the text
        /*
        $('.sga a, .sga input').each(function () {
        var ob = $(this);
        var newWidth = ob.width() + 20;
        ob.parents('ul:eq(0)').children(':first').find('.sga_body').css('width', newWidth + 'px');
        });
        */

        // extendable arrow, should be sound to use png fix for ie6 without grey backgroud
        $('.sga_body').each(function () {
            $(this).attr('ref', $(this).width());
        });

        $('.sga a, .sga input').hover(function () {
            var body = $(this).parents('ul:eq(0)').find('.sga_body');
            var origWidth = body.attr('ref');
            body.stop().animate(
                {
                    width: Number(Number(origWidth) + 20) + 'px'
                }, {
                    duration: 200
                });
        }, function () {
            var body = $(this).parents('ul:eq(0)').find('.sga_body');
            var origWidth = body.attr('ref');
            body.stop().animate(
                {
                    width: origWidth + 'px'
                }, {
                    duration: 200
                });
        });


    } catch (err) { }

    var page = get_page();
    switch (page) {
        case 'ContactUs':
            $('.footerLeft li:eq(0) a').addClass('fNselected');
            break;
        case 'AboutUs':
            $('.footerLeft li:eq(1) a').addClass('fNselected');
            break;
        case 'FAQs':
            $('.footerLeft li:eq(2) a').addClass('fNselected');
            break;
        case 'Privacypolicy':
            $('.footerLeft li:eq(3) a').addClass('fNselected');
            break;

    }

    if (show_all() === true) {
        $('#sga15 li a').trigger('click');
        $('html, body').animate({
            scrollTop: $(document).height()
        }, 1500);
    }

});

function arrows() {
    var width = $(this).width();
    var remain = Number((width - 1600) / 2);
    if (width > 1600) {
        $('#nextButton, .starburst').css({ 'right': remain + 'px' });
        $('#prevButton').css({ 'left': remain + 'px' });
    } else {
        $('#nextButton, #prevButton, .starburst').removeAttr('style');
    }
}

$(window).resize(function () {
    arrows();
});
$(document).ready(function () {
    arrows();
    var fbiframe = '<iframe title="facebook" src="http://www.facebook.com/plugins/like.php?href=' + encodeURI(loc) + '&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;font=arial&amp;colorscheme=light" style="border: medium none; overflow: hidden; width: 46px; margin-right:30px; height: 21px;" frameborder="0" scrolling="no"></iframe>';
    $('#facebookIframe').replaceWith(fbiframe);
    var juansFBcontent = '<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fjuansheet&amp;width=292&amp;colorscheme=light&amp;show_faces=true&amp;stream=true&amp;header=false&amp;height=556" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:556px;"></iframe>';
    $('#juansFBcontent').replaceWith(juansFBcontent);
    $('#faqAccordion .question').each(function (i) {
        $(this).addClass('question' + Number(i + 1));
    });

});


function OnKeyDownControl(elementName) {
    var key = event.which || event.keyCode;
    if (key != '8' && key != '46' && key != '37' && key != '38' && key != '39' && key != '40') {
        if ($("#" + elementName).val().length > 1500) {
            CancelEvent(event);
        }
    }
}

function CancelEvent(pE) {
    if (!pE)
        if (window.event)
            pE = window.event;
        else
            return;
    if (pE.cancelBubble != null)
        pE.cancelBubble = true;
    if (pE.stopPropagation)
        pE.stopPropagation();
    if (pE.preventDefault)
        pE.preventDefault();
    if (window.event)
        pE.returnValue = false;
    if (pE.cancel != null)
        pE.cancel = true;
}


