var $j = jQuery.noConflict();

var navtime;

$j(document).ready(function () {

    //clear texbox values when cursor in
    var inputs = $j("input[type='text']");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].onfocus = function () {
            if ($j(this).attr("alt") && this.value.indexOf($j(this).attr("alt")) == 0) { this.value = ''; }
        };
        inputs[i].onblur = function () {
            if (this.value == '') { this.value = $j(this).attr("alt"); }
        };
    }

    if ($j('.pp-maindrop').length) {

        var $ppdrop = $j('.pp-maindrop');

        //{ speed: 10, delay: 100 },

        $j('.b-navigation .nav__link').bind("hover", function() { OnNavLinkHover(this); });

        $j('.b-navigation .nav__link').bind({ mouseleave: OnNavLinkMouseLeave });

        $ppdrop.bind({
            mouseenter: function () {
                clearTimeout(navtime);
            },
            mouseleave: function () {
                navtime = setTimeout(hidenav, 400);
            }
        });
        $j('.b-navigation li.mysituation').bind({
            mouseover: function () {
                clearTimeout(navtime);
            },
            mouseout: function () {
                navtime = setTimeout(hidenav, 400);
            }
        });

    };


    if ($j('.b-faqlist').length) {
        $j('.b-faqlist h3 a').click(function () {
            $j('.active-li').toggleClass('active-li');
            $j(this).parent().parent().toggleClass('active-li')
            return false;
        })
    }

    if ($j("div[id*='contactForm']").length) {
        processValidation();
        $j('div[id*="contactForm"] input[type|="radio"]').change(function (event) {
            processRadioButtonChange(event);
        });
        $j.each($j('div[id*="contactForm"] input[type|="radio"]'), function (i, val) {
            rb = $j('div[id*="contactForm"] input[type|="radio"]').eq(i);
            if (rb[0].checked) {
                rb.prev().click();
            }
        });

    }
    if ($j("div[id*='registrationForm']").length) {
        processValidation();
        $j('div[id*="registrationForm"] input[type|="radio"]').change(function (event) {
            processRadioButtonChange(event);
        });
        $j.each($j('div[id*="registrationForm"] input[type|="radio"]'), function (i, val) {
            rb = $j('div[id*="registrationForm"] input[type|="radio"]').eq(i);
            if (rb[0].checked) {
                rb.prev().click();
            }
        });
    }
    if ($j("div[id*='newsletterForm']").length) {
        processValidation();
        $j('div[id*="newsletterForm"] input[type|="radio"]').change(function (event) {
            processRadioButtonChange(event);
        });
        $j("div[id*='newsletterForm']").css('top', '102px');
        $j("div[id*='newsletterForm']").hide();
        $j.each($j('div[id*="newsletterForm"] input[type|="radio"]'), function (i, val) {
            rb = $j('div[id*="newsletterForm"] input[type|="radio"]').eq(i);
            if (rb[0].checked) {
                rb.prev().click();
            }
        });
    }

    $j('.pp-lightbox .close').live('click', function () {
        if ($j(this).attr('class').indexOf('videoClose') != -1) {
            $f("*").each(function () {
                this.stop();
            });
        }
        $j('.overlay, .pp-lightbox').hide();
        return false;
    });

    // Language selector

    $j('.languageSelector').click(function () {
        $j('.overlay, #languageSelector').show();
        $j('html, body').animate({ scrollTop: 0 }, 'slow ');
        return false;
    });


    $j('#languageSelector .languages_holder a').click(function () {
        var rel = $j(this).attr('rel');
        $j.cookie('location', null);
        if (rel.length != 0)
            $j.cookie('location', rel, { expires: 365, path: '/' });
        else
            $j.cookie('location', '/', { expires: 365, path: '/' });
    });



    // Issuu documents links
    $j(".issuuLink").click(function () {

        var documentID = $j(this).attr("rel");
        var box = $j('.issuuPreview');
        if (!documentID || !box) {
            return;
        }
        box.empty();

        var container = document.createElement('div');
        container.setAttribute('id', 'issuuDocContainer');
        box.append(container);

        var attributes = { id: 'issuuViewer' };
        var params = { allowfullscreen: 'true', menu: 'false' };
        var flashvars = {
            jsAPIClientDomain: 'www.yourdomain.dk',
            mode: 'embed',
            layout: 'http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml',
            showFlipBtn: 'false',
            documentId: documentID,
            docName: 'agent2issue4',
            loadingInfoText: 'AGENT2%20Issue%204%20July%2FAugust',
            et: '1251461518896',
            er: '26'
        };
        swfobject.embedSWF("http://static.issuu.com/webembed/viewers/style1/v1/IssuuViewer.swf", "issuuDocContainer", "770", "500", "9.0.0", "swfobject/expressInstall.swf", flashvars, params, attributes);

        $j('.overlay, #issuuViewer').show();
        $j('html, body').animate({ scrollTop: 0 }, 'slow ');
    });

    //Video initialization
    InitVideo();

    $j('.snippet:not(.b-smlprm) + .snippet:not(.b-smlprm)').addClass('bordered');
    $j('.b-faqsection div:last-child').css('margin-right', '0');
    var maxHeight = 0;
    $j(".snippet").each(function (i) {
        if ($j(this).height() > maxHeight) {
            maxHeight = $j(this).height();
        }
    });
    if (maxHeight) {
        $j(".snippet:not(.b-smlprm)").height(maxHeight);
    }

    //features to comare
    $j('.b-ftcompare>li').mouseover(
					function () {
					    if (!$j('.compare_overlay').length) {
					        $j('.b-main-page').append('<div class="compare_overlay"></div>');
					        $j('.compare_overlay').width($j('body').width() - 2);
					        $j('.compare_overlay').height($j('.b-main-page').height());
					        $j('.compare_overlay').css('left', -($j('body').width() - $j('.b-main-page').width()) / 2);
					    }
					    $j('.b-ftcompare>li').removeClass('tempOp');
					    $j(this).siblings().removeClass('ftcompare');
					    $j(this).addClass('ftcompare');
					}
				);

    $j('.compare_overlay').live('mouseover', function () {
        $j('.b-ftcompare>li').addClass('tempOp');
        $j('.b-ftcompare>li').removeClass('ftcompare');
        $j('.compare_overlay').remove();
    });


});

function showLanguagePopup() {
    $j('.overlay, #languageSelector').show();
    $j('html, body').animate({ scrollTop: 0 }, 'slow ');
}


function hidenav() {

    if (typeof ClickTaleExec == 'function')
        ClickTaleExec("hidenav()");

    $j('.b-navigation .nav__link').removeClass('drop-nav');
    $j('.b-navigation .drop-mysituation').removeClass('drop-mysituation');
    $j('.pp-maindrop').removeClass('pp-maindrop-active');
}

// newsletter form
function showNewsletterForm(emailInputId) {
    if (emailInputId) {
        emailInput = $j("input[id*='" + emailInputId + "']");
        alt = emailInput.attr("alt");
        val = emailInput.val();
        if (alt != val) {
            $j("input[id*='txtEmail']").val(val);
        }
    }
    $j('.overlay, #newsletterForm').show();
    $j('html, body').animate({ scrollTop: 0 }, 'slow ');
    return false;
}

function hideNewsletterForm(clearFields) {
    $j('.overlay, #newsletterForm').hide();
    if (clearFields) {
        inputs = $j('#newsletterForm input');
        for (var i = 0; i < inputs.length; i++) {
            switch (inputs[i].type) {
                case 'text':
                    inputs[i].value = '';
                    break;
                case 'radio':
                case 'checkbox':
                    inputs[i].checked = false;
                    $j(inputs[i]).prev().removeClass('jqTransformChecked');
                    break;
                /*
                case 'radio':
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                break;
                case 'checkbox':
                if (inputs[i].id.indexOf('chbxReceiveNews') != -1) {
                inputs[i].checked = true;
                $j(inputs[i]).prev().addClass('jqTransformChecked');
                } else {
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                }
                break;
                */ 
            }
        }
        selects = $j('#newsletterForm select');
        for (i = 0; i < selects.length; i++) {
            if (selects[i].selectedIndex > 0) {
                selects[i].selectedIndex = 0;
                var parent = $j(selects[i]).parent();
                $j('ul>li>a[index|="0"]', parent).click();
            }
        }
        $j('#newsletterForm div[id*="pnlChildBirthDate"]').hide();
        divs = $j('#newsletterForm .ips.ips-error');
        for (i = 0; i < divs.length; i++) {
            $j(divs[i]).removeClass('ips-error');
        }
        $j('#newsletterForm .b-error-msg').css('display', 'none');
    }
    return false;
}

// send a friend form
function showSendAFriendForm() {
    $j('.overlay, #sendAFriendForm').show();
    $j('html, body').animate({ scrollTop: 0 }, 'slow ');
    return false;
}

function hideSendAFriendForm(clearFields) {
    $j('.overlay, #sendAFriendForm').hide();
    if (clearFields) {
        inputs = $j('#sendAFriendForm input');
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].value = '';
        }
        textareas = $j('#sendAFriendForm textarea');
        for (i = 0; i < textareas.length; i++) {
            textareas[i].value = '';
        }
        divs = $j('#sendAFriendForm .ips.ips-error');
        for (i = 0; i < divs.length; i++) {
            $j(divs[i]).removeClass('ips-error');
        }
        $j('#sendAFriendForm .b-error-msg').css('display', 'none');
    }
    return false;
}

// contact form
function processValidation() {
    if ($j("input[id*='hdfDueDateValidate']").val() == 'false') {
        setDivVisibility('pnlDueDate', false);
    }
    if ($j("input[id*='hdfOtherProductValidate']").val() == 'false') {
        setDivVisibility('pnlOtherProduct', false);
    }
    if ($j("input[id*='hdfPurchaseLocationValidate']").val() == 'false') {
        setDivVisibility('pnlPurchaseLocation', false);
    }
    if ($j("input[id*='hdfPurchaseDateValidate']").val() == 'false') {
        setDivVisibility('pnlPurchaseDate', false);
    }
    if ($j("input[id*='hdfProductValidate']").val() == 'false') {
        setDivVisibility('pnlProduct', false);
    }
}

function processRadioButtonChange(event) {
    if (!event.target.checked) {
        if (event.target.id.indexOf('rbProductRelated') > 0) {
            setDivVisibility('pnlProduct', 'hdfProductValidate', false);
            setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', false);
            setDivVisibility('pnlPurchaseLocation', 'hdfPurchaseLocationValidate', false);
            setDivVisibility('pnlPurchaseDate', 'hdfPurchaseDateValidate', false);
        } else if (event.target.id.indexOf('rbNotProductRelated') > 0) {
            setDivVisibility('pnlProduct', 'hdfProductValidate', true);
            selectProduct = $j("select[id*='ddlProduct']")[0];
            if (selectProduct.options.length == selectProduct.selectedIndex + 1) {
                setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', true);
            } else {
                setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', false);
            }
            setDivVisibility('pnlPurchaseLocation', 'hdfPurchaseLocationValidate', true);
            setDivVisibility('pnlPurchaseDate', 'hdfPurchaseDateValidate', true);
        } else if (event.target.id.indexOf('rbYes') > 0) {
            setDivVisibility('pnlDueDate', 'hdfDueDateValidate', false);
        } else if (event.target.id.indexOf('rbNo') > 0) {
            setDivVisibility('pnlDueDate', 'hdfDueDateValidate', true);
        } else if (event.target.id.indexOf('rbnYes') > 0) {
            setDivVisibility('pnlnDueDate', 'hdfnDueDateValidate', false);
        } else if (event.target.id.indexOf('rbnNo') > 0) {
            setDivVisibility('pnlnDueDate', 'hdfnDueDateValidate', true);
        }
    }
}

function handle_selectSubjectChange() {
    select = $j("select[id*='ddlSubject']")[0];
    relatedSubjects = $j("input[id*='hdfProductRelatedSubjects']").val();
    if (relatedSubjects.indexOf(select.selectedIndex + '|') < 0 && select.selectedIndex > 0) {
        setDivVisibility('pnlProduct', 'hdfProductValidate', false);
        setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', false);
        setDivVisibility('pnlPurchaseLocation', 'hdfPurchaseLocationValidate', false);
        setDivVisibility('pnlPurchaseDate', 'hdfPurchaseDateValidate', false);
    } else {
        setDivVisibility('pnlProduct', 'hdfProductValidate', true);
        selectProduct = $j("select[id*='ddlProduct']")[0];
        if (selectProduct.options.length == selectProduct.selectedIndex + 1) {
            setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', true);
        } else {
            setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', false);
        }
        setDivVisibility('pnlPurchaseLocation', 'hdfPurchaseLocationValidate', true);
        setDivVisibility('pnlPurchaseDate', 'hdfPurchaseDateValidate', true);
    }
}

function handle_selectProductChange() {
    select = $j("select[id*='ddlProduct']")[0];
    if (select.options.length == select.selectedIndex + 1) {
        setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', true);
    } else {
        setDivVisibility('pnlOtherProduct', 'hdfOtherProductValidate', false);
    }
}

function setDivVisibility(divId, hdfId, visible, useFullId) {
    if (!useFullId) {
        div = $j("div[id*='" + divId + "']");
        $j("input[id*='" + hdfId + "']").val(visible);
        if (visible) {
            div.show();
        } else {
            div.hide();
        }
    } else {
        div = $j("#" + divId);
        $j("#" + hdfId).val(visible);
        if (visible) {
            div.show();
        } else {
            div.hide();
        }
    }
}

function cancelContactForm() {
    inputs = $j('#contactForm input');
    for (var i = 0; i < inputs.length; i++) {
        switch (inputs[i].type) {
            case 'text':
                inputs[i].value = '';
                break;
            case 'radio':
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                break;
            case 'checkbox':
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                break;
        }
    }
    textareas = $j('#contactForm textarea');
    for (i = 0; i < textareas.length; i++) {
        textareas[i].value = '';
    }
    selects = $j('#contactForm select');
    for (i = 0; i < selects.length; i++) {
        if (selects[i].selectedIndex > 0) {
            selects[i].selectedIndex = 0;
            var parent = $j(selects[i]).parent();
            $j('ul>li>a[index|="0"]', parent).click();
        }
    }
    $j('#contactForm div[id*="pnlChildBirthDate"]').hide();
    divs = $j('#contactForm .ips.ips-error');
    for (i = 0; i < divs.length; i++) {
        $j(divs[i]).removeClass('ips-error');
    }
    $j('#contactForm .b-error-msg').css('display', 'none');
    return false;
}

function cancelRegistrationForm() {
    inputs = $j('#registrationForm input');
    for (var i = 0; i < inputs.length; i++) {
        switch (inputs[i].type) {
            case 'text':
                inputs[i].value = '';
                break;
            case 'radio':
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                break;
            case 'checkbox':
                inputs[i].checked = false;
                $j(inputs[i]).prev().removeClass('jqTransformChecked');
                break;
        }
    }
    textareas = $j('#registrationForm textarea');
    for (i = 0; i < textareas.length; i++) {
        textareas[i].value = '';
    }
    selects = $j('#registrationForm select');
    for (i = 0; i < selects.length; i++) {
        if (selects[i].selectedIndex > 0) {
            selects[i].selectedIndex = 0;
            var parent = $j(selects[i]).parent();
            $j('ul>li>a[index|="0"]', parent).click();
        }
    }
    $j('#registrationForm div[id*="pnlChildBirthDate"]').hide();
    divs = $j('#registrationForm .ips.ips-error');
    for (i = 0; i < divs.length; i++) {
        $j(divs[i]).removeClass('ips-error');
    }
    $j('#registrationForm .b-error-msg').css('display', 'none');
    return false;
}

function cancelReportErrorForm() {
    inputs = $j('#reportErrorForm input');
    for (var i = 0; i < inputs.length; i++) {
        switch (inputs[i].type) {
            case 'text':
                inputs[i].value = '';
                break;
        }
    }
    textareas = $j('#reportErrorForm textarea');
    for (i = 0; i < textareas.length; i++) {
        textareas[i].value = '';
    }
    divs = $j('#reportErrorForm .ips.ips-error');
    for (i = 0; i < divs.length; i++) {
        $j(divs[i]).removeClass('ips-error');
    }
    $j('#reportErrorForm .b-error-msg').css('display', 'none');
    return false;
}

// image gallery
function showGallery(storageId, startIndex, startMessage, stopMessage) {
    var $curr = startIndex ? startIndex : 0;
    $j('.overlay').show();
    $j('body').append('<div class="pp-lightbox pp-photogallery" id="pp-photogallery" style="visibility: hidden;"><i class="pp-cr ppc-tl"></i><i class="pp-cr ppc-tr"></i><i class="pp-cr ppc-bl"></i><i class="pp-cr ppc-br"></i></div>');
    $j('#pp-photogallery').prepend('<div class="pp-lightbox-i" id="pp-lightbox-i"></div>');
    $j('#pp-lightbox-i').append('<a class="close" href="#"></a><h2 id="imagetitle">Image Gallery</h2><div class="ad-gallery" id="gallery"></div>');
    $j('#gallery').append('<div class="ad-image-wrapper"></div><div class="ss_decor"></div><div class="ad-controls"></div><div class="ad-nav"><div class="ad-thumbs"></div></div>');
    $j('.ad-thumbs').append($j('#' + storageId).clone());
    var galleries = $j('.ad-gallery').adGallery({
        loader_image: '/include/DorelBase/i/cntrl_loader.gif',
        thumb_opacity: 0.5,
        start_at_index: $curr,
        width: 888,
        height: 479,
        effect: 'fade',
        slideshow: {
            start_label: startMessage ? startMessage : 'view slideshow',
            stop_label: stopMessage ? stopMessage : 'stop slideshow',
            autostart: false,
            countdown_prefix: '',
            countdown_sufix: '',
            speed: 2000,
            onStart: function () {
                $j('.ad-slideshow-stop').fadeIn(100);
                $j('.ad-slideshow-start').fadeOut(100);
            },
            onStop: function () {
                $j('.ad-slideshow-stop').fadeOut(100);
                $j('.ad-slideshow-start').fadeIn(100);
            }
        },
        callbacks: {
            afterImageVisible: function () {
                if (this.images[this.current_index].desc) {
                    $j('#imagetitle').text(this.images[this.current_index].desc);
                }
                else {
                    $j('#imagetitle').text("Image " + (this.current_index + 1));
                }
            }
        }
    });
    $j('html, body').animate({ scrollTop: 0 }, 'slow ');
    $j('#pp-photogallery').css('visibility', 'visible');
    $j('.close').click(OnMenuClose);
    return false;
}

function ShowVideo(element, url, width) {

    $f(element, "/include/dorelbase/f/flowplayer.commercial-3.2.6.swf", {
        wmode: 'opaque',
        key: flowPlayerKey,
        clip: {
            url: url,
            autoPlay: false,
            autoBuffering: true,
            onStart: function (clip) {
                if (width) {
                    var wrap = jQuery(this.getParent());
                    wrap.css({ width: width, height: clip.metaData.height * width / clip.metaData.width });
                }
            }
        },
        plugins: {
            controls: {
                // location of the controlbar plugin
                url: '/include/dorelbase/f/flowplayer.controls-3.2.4.swf'
            }
        }
    }).ipad();
}

function ShowVideoPopup(url, title) {
    $j(".pp-videotitle").html(title);
    $j('.overlay, #videoViewer').show();
    $j('html, body').animate({ scrollTop: 0 }, 'slow ');
    ShowVideo($j("#videoViewer .pp-lightbox-i div").get(0), url, 770);
    return false;
}

function InitVideo() {
    // Player links
    $j(".vidPlayer").each(function () {
        ShowVideo(this, $j(this).attr("href"));
    });

    // video links
    $j(".vidLink").each(function () {
        var url = $j(this).attr("href");
        $j(this).attr("href", "#");
        $j(this).click(function () {
            ShowVideoPopup(url, $j(this).html());
        });
    });

    // video links with image inside
    $j(".vidImageLink").each(function () {
        var url = $j(this).attr("href");
        $j(this).attr("href", "#");
        $j(this).click(function () {
            ShowVideoPopup(url, "&nbsp;");
        });
    });

    //video popup close button
    $j('#videoViewer .videoClose').live('click', function () {
        $j('.overlay, .pp-lightbox').hide();
        //$f($("#videoViewer .pp-lightbox-i div")).stop();
        $f("*").each(function () {
            this.stop();
        });

        $j("#videoViewer .pp-lightbox-i div").html("");
        return false;
    });
}
//search
function submitenter(myfield, e, btnId) {
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;
    } else {
        return true;
    }
    if (keycode == 13) {
        window.location.href = $j('#btnSearch').attr('href');
        return false;
    } else {
        return true;
    }
}

function OnNavLinkHover(caller) {

    if (typeof ClickTaleExec == "function") 
    {
		var callerID = caller.id;
		if (callerID) {
		    ClickTaleExec("OnNavLinkHover(document.getElementById('" + callerID + "'));");
		}
	}

    var $ppdrop = $j('.pp-maindrop');

    var $t = $j(caller);
    clearTimeout(navtime);
    $j('.tab', $ppdrop).removeClass('active-tab');
    $j('.b-navigation .nav__link').removeClass('drop-nav');
    if ($t.parents('li').hasClass('mysituation')) {
        $ppdrop.removeClass('pp-maindrop-active');
        $t.parents('li').addClass('drop-mysituation')
    }
    else {
        $j('.b-navigation .drop-mysituation').removeClass('drop-mysituation');
        var $rel = $t.attr('rel');

        if (typeof ClickTaleExec == 'function')
            ClickTaleTag($rel);

        $t.addClass('drop-nav');
        $ppdrop.addClass('pp-maindrop-active');
        $j('.' + $rel, $ppdrop).addClass('active-tab');
    }
}

function OnNavLinkMouseLeave() {

    if (typeof ClickTaleExec == 'function')
        ClickTaleExec("OnNavLinkMouseLeave()");

    var $t = $j(this);
    if (!$t.parents('li').hasClass('mysituation')) {
        navtime = setTimeout(hidenav, 400)
    }
}

function OnMenuClose() {

    if (typeof ClickTaleExec == 'function')
        ClickTaleExec("OnMenuClose()");

    $j('#pp-photogallery').empty();
    $j('.overlay').hide();
    $j('.ad-preloads').remove();
    $j('#pp-photogallery').remove();

    return false;
}

