﻿String.prototype.endsWith = function (str) { return (this.match(str + "$") == str); };
function showMonthlyWinner(month) {
    try {
        if (month == undefined)
            month = winner.Default;
        var conf = winnerConfigDE;

        $(".title .winPrev").hide();
        $(".title .winNext").hide();
        $(".title .winHeader").html(conf.TextHeader.replace('<month>', conf.MonthName[winner.Month[month] - 1]));
        $(".title .winName").html('');
        for (var i = 0; i < winner.Name[month].length; i++) {
            $(".title .winName").append(winner.Name[month][i] + '<br /><br />');
        }
        $(".title .WinnerInfo a").attr('href', winner.Link[month]);
        //$(".title .winName").html(winner.Name[month]);
        //$(".title .winCity").html(conf.TextCity.replace('<city>', winner.City[month]));

        if (month != 0) {
            $(".title .winPrev").html(conf.TextButton.replace('<month>', conf.MonthName[winner.Month[month - 1] - 1]));
            $(".title .winPrev").unbind('click', function () { return false; });
            $(".title .winPrev").bind('click', function () { showMonthlyWinner(month - 1); });
            $(".title .winPrev").show();
        }
        if (month < winner.Name.length - 1) {
            $(".title .winNext").html(conf.TextButton.replace('<month>', conf.MonthName[winner.Month[month + 1] - 1]));
            $(".title .winNext").unbind('click', function () { return false; });
            $(".title .winNext").bind('click', function () { showMonthlyWinner(month + 1); });
            $(".title .winNext").show();
        }
    } catch (ex) {
        return;
    }
}
function getSiteURL() {
    var b = "kleenex.at";
    if (window.location.href.indexOf(".testdev.") > -1)
        return "http://www.testdev." + b;
    if (window.location.href.indexOf(".dev.") > -1)
        return "http://www.dev." + b;
    if (window.location.href.indexOf(".testqa.") > -1)
        return "http://www.testqa." + b;
    if (window.location.href.indexOf(".qa.") > -1)
        return "http://www.qa." + b;
    return "http://www." + b;
}
function showInfoDialog(title, message, width) {
    if (width == undefined)
        width = 300;
    $("#infoDialog p").html(message);
    $("#infoDialog").dialog("option", "width", width);
    $("#infoDialog").dialog("option", "title", title);
    $("#infoDialog").dialog("open");
}
function showErrorDialog(title, message, width) {
    if (width == undefined)
        width = 300;
    $("#errorDialog div").append(message);
    $("#errorDialog").dialog("option", "title", title);
    $("#errorDialog").dialog("open");
}
function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return 'de'; //default_;
    else
        return qs[1];
}

function acceptcharonly(e) {
    var key;
    var keychar;

    if (window.event) // For IE
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    if ((("<>").indexOf(keychar) > -1))
        return false;

    return true;
}

function RemoveOtherTab(openTab) {



    if (openTab == "right_tab_preise") {
        //$('.right_tab_partner').animate({ right: '-471px' }, 300).removeClass('open');
        $('.right_tab_gewinner').animate({ right: '-392px' }, 300).removeClass('open');
        //swapButton('.partner_content', "_on");
        swapButton('.gewinner_content', "_on");
    } else if (openTab == "right_tab_gewinner") {
        //$('.right_tab_partner').animate({ right: '-471px' }, 300).removeClass('open');
        $('.right_tab_preise').animate({ right: '-796px' }, 300).removeClass('open');
        //swapButton('.partner_content', "_on");
        swapButton('.preise_content', "_on");
    } else {
        //$('.right_tab_partner').animate({ right: '-471px' }, 300).removeClass('open');
        $('.right_tab_preise').animate({ right: '-796px' }, 300).removeClass('open');
        $('.right_tab_gewinner').animate({ right: '-392px' }, 300).removeClass('open');
        //swapButton('.partner_content', "_on");
        swapButton('.preise_content', "_on");
        swapButton('.gewinner_content', "_on");
    }

}



function showTerm(termLang) {
    var URL = 'TermCond_' + termLang + '.htm';
    window.open(URL, '_blank', 'width=540, height=560, location=no, menubar=no, resizable=no, scrollbars=no, toolbar=no');
    return false;
}
function validateInputForm() {
    $(".requireField").html('&nbsp;');
    var intRegex = /^\d+$/;
    var isValidInput = true;
    var inputElement = $(".campaignForm :text");
    var isAcceptTerm = document.getElementById(chkAcceptID).checked;
    $(inputElement).each(function () {

        var nextElement = $(this).next();
        if ($(nextElement) != null) {
            if (jQuery.trim($(this).attr('value')) == '') {
                isValidInput = false;
                $(nextElement).html('*');
            }
            if ($(this).attr('id') == txtZipID) {
                var zip = jQuery.trim($(this).attr('value'));
                if(!intRegex.test(zip) || zip.length != 4){
                    isValidInput = false;
                    $(nextElement).html('*');
                }
            }
        }
    });
    if (isAcceptTerm == false) {
        isValidInput = false;
        $(".acceptTerm").html('*');
    }
    return isValidInput;
}
function showCompleteStage() {
    $("#left_tab .colLHead, #left_tab .colLBody, #imgList").hide();
    $("#left_tab #noseCompleted").show();
    if (lang == "de") {
        $("#txtLTabHeadCompleteDE").show();
        $("#txtLTabBodyCompleteDE").show();
    } else {
        $("#txtLTabHeadCompleteFR").show();
        $("#txtLTabBodyCompleteFR").show();
    }
}
function switchLBtnTab() {
    var $btnElement = $('#left_tab .tab_button');
    var $temp = $btnElement.css('background-image');
    if ($temp.indexOf("newbalsam/btn_tabLeft.png") != -1) {
        $btnElement.css('background-image', 'url(/images/newbalsam/btn_tabLeft2.png)');
    } else if ($temp.indexOf("newbalsam/btn_tabLeft2.png") != -1) {
        $btnElement.css('background-image', 'url(/images/newbalsam/btn_tabLeft.png)');
    } 
}
function showLeftTab() {
    if (step == undefined) {
        step = 1;
    }
    var $tabElement = $('#left_tab .tab_mcontent');

    if (step == 1) {
        $('#left_tab').css('width', 560);
        $tabElement.animate(
            { width: 480 }
        );
    } else if (step == 2) {
        $("#content_r").show();
        $('#left_tab').css('width', 960);
        $tabElement.animate(
            { width: 879 }
        );
    }

}
function hideLeftTab(closeHalf) {
    $("#content_r").hide();
    if (closeHalf == undefined)
        closeHalf = false;

    var $tabElement = $('#left_tab .tab_mcontent');

    if (closeHalf == true) {
        $tabElement.animate(
            { width: 480 },
            500, function () {
                $('#left_tab').css('width', 560);
            }
        );
    } else {
        $tabElement.animate(
            { width: 0 },
            500, function () {
                $('#left_tab').css('width', 74);
            }
        );
    }
}
function swapButton(btn, param2) {
    var temp = $(btn).css('background-image');
    var tmpPath = "";

    if (param2 == undefined) {
        if (temp.indexOf("_on") != -1) {
            tmpPath = temp.replace("_on", "_off");
        } else {
            tmpPath = temp.replace("_off", "_on");
        }
    } else {
        //alert(param2);
        if (param2 == "_on") {
            tmpPath = temp.replace("_on", "_off");
        } else {
            tmpPath = temp.replace("_off", "_on");
        }
    }


    $(btn).css('background-image', tmpPath);

}


function moveZ(panel) {

    if (panel.indexOf("preise") > 0) {
        $(panel).css('z-index', 60);
        $('.right_tab_gewinner').css('z-index', 40);

    } else if (panel.indexOf("gewinner") > 0) {
        $(panel).css('z-index', 60);
        $('.right_tab_preise').css('z-index', 40);
    }

}

/// =================== Social ==================== ///
function BtnFacebookClick() {
    var url = "http://www.facebook.com/share.php?u=" + siteURL;
    newwindow = window.open(url, 'name', 'height=500,width=550');
    return false;
}
function BtnTwitterClick() {
    var url = "https://twitter.com/share";
    newwindow = window.open(url, 'name', 'height=500,width=550');
    return false;
}
/// ============================================== ///
$(document).ready(function () {

    $("#chkAcceptTerm").click(function () { validateInputForm(); });
    $(".btnMail").attr("href", "mailto:?subject=Kleenex(R) Balsam Fresh!&body=" + siteURL);
    $.datepicker.setDefaults({
        yearRange: '1900:2012',
        maxDate: new Date(),
        minDate: new Date(1900, 1, 1),
        changeMonth: true,
        changeYear: true,
        onSelect: function (dateText, inst) { validateInputForm(); }
    });
    if (lang == 'de') {
        $("#txtBirthday").datepicker($.datepicker.regional['de-CH']);
        $("#footerFBDE").show();
        $("#homeTermDE").show();
    } else {
        $("#txtBirthday").datepicker($.datepicker.regional['fr-CH']);
        $("#footerFBFR").show();
        $("#homeTermFR").show();
    }

    // ======== Hide TextBox and show DropDown if FR
    if (lang == 'fr') {
        $("#FRLandSelector").show();
        $("#reqCountry").hide();
        document.getElementById(txtCountryID).style.display = 'none';
        document.getElementById(txtCountryID).value = $("#FRLandSelector").val();
    }

    //$("#txtProductDE").click(function () { window.open("/default.aspx", "_blank"); });
    //$("#txtProductFR").click(function () { window.open("/ch/fr/index.aspx", "_blank"); });

    $('#left_tab .tab_button').click(function () {
        if ($('#left_tab .tab_mcontent').width() == 0) {
            showLeftTab();
        } else {
            hideLeftTab();
        }
        switchLBtnTab();
    });



    // User pick the board
    $(".imgBox").bind('click', function () {
        // Ajax logic when click image
        var ItemID = $(this);
        var email = document.getElementById(txtEmailID).value;
        var Postdata = "lang=" + lang + "&imgID=" + $(ItemID).attr('id') + "&email=" + email +"&userID=" + userID;


        $(".imgBox").unbind('click');
        xmlAsyncA("HomeAction.aspx?type=select", Postdata, function (req) {
            var resArr = req.responseText.split("|");
            if (resArr[0] == '1') {
                step = 2;
                showLeftTab();
                $(ItemID).html('');
                prizeID = resArr[1];
                $(ItemID).css('background-image', resArr[2]);
                $(".imgBox").css('cursor', 'default');
            } else {
                alert(resArr[1]);
                //showErrorDialog('Error!', resArr[1])
            }
        });
    });

    // Clear input form
    $(".frmBtnAbort").click(function () {
        $(".requireField").html('&nbsp;');
        var inputElement = $(".campaignForm :input");
        var firstElement = $(inputElement)[0];
        $(inputElement).each(function () {
            if ($(this).attr('id') == txtCountryID)
                return true;
            if ($(this).attr('type') == 'text')
                $(this).attr('value', '');
            else if ($(this).attr('type') == 'checkbox')
                $(this).attr('checked', false);
        });
        if (lang == 'fr')
            document.getElementById(txtCountryID).value = $("#FRLandSelector").val();
        $(firstElement).focus();
    });

    // User click NEXT
    $(".btnNext").click(function () {
        dcsMultiTrack('DCS.dcsuri', '/promo/campaign/', 'WT.ti', 'Campaign name');
        var email = document.getElementById(txtEmailID).value;
        var Postdata = "lang=" + lang + "&email=" + email;
        xmlAsyncA("HomeAction.aspx?type=next", Postdata, function (req) {
            var resArr = req.responseText.split("|");
            if (resArr[0] == '1') {
                userID = resArr[1];
                $("#emailLTab").hide();
                $(".imgBox").show();
            } else if (resArr[0] == '2') {
                showInfoDialog('Blocked Email!', resArr[1], 800);
            } else {
                alert(resArr[1]);
                //showErrorDialog('Error!', resArr[1])
            }
        });
    });
    // Submit form
    $(".frmBtnSend").click(function () {
        if (validateInputForm()) {
            dcsMultiTrack('DCS.dcsuri', '/promo/campaign/', 'WT.ti', 'Campaign name');
            var fname = document.getElementById(txtFirstNameID).value;
            var lname = document.getElementById(txtLastNameID).value;
            var address = document.getElementById(txtAddressID).value;
            var zip = document.getElementById(txtZipID).value;
            var city = document.getElementById(txtCityID).value;
            var country = document.getElementById(txtCountryID).value;
            var telephone = document.getElementById(txtTelephoneID).value;
            var email = document.getElementById(txtEmailID).value;
            var accept = document.getElementById(chkAcceptID).checked;
            var optinmail = document.getElementById(chkOptInEmailID).checked;
            var birthday = '';// document.getElementById(txtBirthdayID).value;

            var Postdata = "lang=" + lang + "&prize=" + prizeID + "&fname=" + fname + "&lname=" + lname +
                        "&address=" + address + "&zip=" + zip + "&city=" + city +
                        "&country=" + country + "&telephone=" + telephone + "&email=" + email +
                        "&optinmail=" + optinmail + "&userID=" + userID + "&birthday=" + birthday;
            xmlAsyncA("HomeAction.aspx?type=submit", Postdata, function (req) {
                var resArr = req.responseText.split("|");
                if (resArr[0] == '1') {
                    step = 1;
                    hideLeftTab(true);
                    showCompleteStage();
                } else {
                    alert(resArr[1]);
                    //showErrorDialog('Error!', resArr[1])
                }
            });
        } else {
            var txtAlert = "Please fill all required field.";
            //alert(txtAlert);
        }
    });

    // Auto validate form
    $(":input").blur(function () {
        validateInputForm();
    });


    //---------------------Right Tab--------------------------//


    $('.right_tab_preise').tabSlideOut({
        tabHandle: '.preise_content',                     //class of the element that will become your tab
        pathToTabImage: '/images/newBalsam/' + lang + '/kleenex_btPreise_off.png', //path to the image for the tab //Optionally can be set using css
        imageHeight: '140px',                     //height of tab image           //Optionally can be set using css
        imageWidth: '58px',                       //width of tab image            //Optionally can be set using css
        tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
        speed: 300,                               //speed of animation
        action: 'click',                          //options: 'click' or 'hover', action to trigger animation
        topPos: '179px',                          //position from the top/ use if tabLocation is left or right
        leftPos: '0px',                          //position from left/ use if tabLocation is bottom or top
        fixedPosition: false                      //options: true makes it stick(fixed position) on scroll
    });

    $('.preise_content').bind('click', function () {
        swapButton('.preise_content');
        moveZ('.right_tab_preise');
        hideLeftTab();
        RemoveOtherTab('right_tab_preise');
    });

    $('.right_tab_gewinner').tabSlideOut({
        tabHandle: '.gewinner_content',                     //class of the element that will become your tab
        pathToTabImage: '/images/newBalsam/' + lang + '/kleenex_btGewinner_off.png', //path to the image for the tab //Optionally can be set using css
        imageHeight: '147px',                     //height of tab image           //Optionally can be set using css
        imageWidth: '58px',                       //width of tab image            //Optionally can be set using css
        tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
        speed: 300,                               //speed of animation
        action: 'click',                          //options: 'click' or 'hover', action to trigger animation
        topPos: '316px',                          //position from the top/ use if tabLocation is left or right
        leftPos: '0px',                          //position from left/ use if tabLocation is bottom or top
        fixedPosition: false                      //options: true makes it stick(fixed position) on scroll
    });

    $('.gewinner_content').bind('click', function () {
        //alert(this.className);
        swapButton('.gewinner_content');
        moveZ('.right_tab_gewinner');
        hideLeftTab();
        RemoveOtherTab('right_tab_gewinner');
    });

    //---------------------Right Tab--------------------------//


    //============= DropDown Handler ===============//
    $("#FRLandSelector").change(function () {
        document.getElementById(txtCountryID).value = $(this).val();
    });
    //==============================================//

    // Validate key press
    $('[type="text"]').each(function () {
        $(this).keypress(function (e) {
            return acceptcharonly(e);
        });
    });
    $('[type="password"]').each(function () {
        $(this).keypress(function (e) {
            return acceptcharonly(e);
        });
    });

    // Show Monthly Winner
    showMonthlyWinner();

    // Startup Dialog
    $(".dialog-message").dialog({ modal: true, autoOpen: false, resizable: false, draggable: false });
    if (getQuerystring('d') == '0') {
        showErrorDialog('Error!!!', 'An error occur during the activation process.');
    } else if (getQuerystring('d') == '1') {
        if (lang == 'de')
            $("#successDE").dialog("open");
        else
            $("#successFR").dialog("open");
    } else if (getQuerystring('d') == '9')
        if (getQuerystring('lang') == 'de')
            showInfoDialog('Oop!!!', 'Ihr Gewinn ist von anderen getroffen worden.');
        else
            showInfoDialog('Oop!!!', 'Votre prix a été prise par d\'autres.');
});
