
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
var Url = {
    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
 
// Product Finder: Launches Flex-Application 
function openProductfinder(fallbackLink) {
    var appUrl = '/nsk_product_finder/index.swf?language=pl&project=eu';

    var flashVersion = swfobject.getFlashPlayerVersion();
    if (flashVersion.major >= 9)
    {
        var height = 543;
        try
        {
            if (window.innerWidth && window.innerHeight)
                height = window.innerHeight;
            else if (document.body.clientHeight && document.body.clientWidth)
                height = document.body.clientHeight;
            else if (document.documentElement.clientHeight && document.documentElement.clientWidth)
                height = document.documentElement.clientHeight;
        }
        catch(e)
        {}    

        if ($("#productfinder").length === 0)
        {
            $('body').append('<div id="productfinder"></div>');
            var flashvarsPF = {}; var paramsPF = { wmode: 'transparent', allowScriptAccess: 'always' }; var attributesPF = {};
            swfobject.embedSWF(appUrl, "productfinder", "100%", height, "6.0.0", false, flashvarsPF, paramsPF, attributesPF);
        }
        $('#productfinder').show();
    } else {

/* ****************************************************************************************************
 *
 * Homepage, Flash
 *
 */

    if ($("#NoFlashInfoBox").length === 0) {
        if (fallbackLink !== '') window.location.href = fallbackLink;
    } else {
        $('body').append('<a id="NoFlashInfoBoxLinHelper" style="display:block;" href="#NoFlashInfoBox">&nbsp;</a>');
        $("a#NoFlashInfoBoxLinHelper").fancybox({
            'zoomSpeedIn': 4,
            'zoomSpeedOut': 2,
            'width': 500,
            'height': 300
        });
        $("a#NoFlashInfoBoxLinHelper").click();        
    }

    }
}

// Product Finder: Hides the Product Finder DIV
function closeProductfinder() {
    $('#productfinder').hide();
}


// Customer Portal Login: Inits the clear function at form submission
function submitPortalLogin()
{
    window.setTimeout("clearPortalLogin()", 1000);
    return true;
}

// Customer Portal Login: Clears portal Login form after submission
function clearPortalLogin()
{
    document.portalLogin.txtUsername.value="";
    document.portalLogin.txtPassword.value="";
    nskPortalLogin.focus();
}


function getOrderParams(opts){
/* no longer needed due to jquery update
    var params='';
    var formID=$('body').data('formID');
    $('#'+formID+' input[type=hidden], #'+formID+' input[name=order-control][checked]').each(function(){
       params+="&"+$(this).attr('name')+'='+encodeURIComponent($(this).attr('value'));
    });
    params='?'+params.substring(1,params.length);
    opts.itemArray.push({url:'/cps/rde/xchg/eu_pl/hs.xsl/literature_order.html'+params});
*/
}

function selectAll(formID,checkboxName){
    $('#'+formID+' input[name='+checkboxName+']').attr('checked','checked');
}
function deselectAll(formID,checkboxName){
    $('#'+formID+' input[name='+checkboxName+']').removeAttr('checked');
}

function checkEMail(el){
    $('p.form_error_inline',el).remove();
    var re = /^((?:[a-z0-9\.\-\_\!\$\^\/#+=~&|]{0,63})(?:[^.])|\"[^\"]+\")@((?:(?:\w[\w\-]+\w|\w+)\.)+(?:[a-z]{2}|(?:aero|asia|biz|cat|com|coop|edu|eu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)))$/; 
    var inputEl=el.EMail;
    if (inputEl.value.match(re)){
        return true;
    }else{
        $(inputEl).parent().after('<p class="form_error_inline">'+$(inputEl).attr('title')+'</p>');
        return false;
    }
}

function checkLogin(el)
{
    var test=true;
    thisID=$(el).attr('id');
    formID='login'+thisID.substring(thisID.indexOf('_'),thisID.length);
    $('#'+formID+' p.form_error_inline').remove();
    $('#'+formID+' input[type=text], #'+formID+' input[type=password]').each(function(){
        if ($(this).val()==''){
            $(this).parent().after('<p class="form_error_inline">'+$(this).attr('title')+'</p>');
            test=false;
        }
    });
    return test;
}

function download_reg(el, o)
{
    var trigger=false;
    $.ajax({
           async: false,
           url: '/cps/rde/xchg/eu_pl/xml2xml.xsl/softRegForm.xml',
           type: 'GET',
           dataType: 'xml',
           timeout: 3000,
        error: function(xml){
            //window.open(el.href);
            trigger=true;
        },
        success: function(xml){
            var status=$("status",xml).text();
            if (status==0) {
                //window.open(el.href);
                trigger=true;
            }
            else {
                var fileHref="";
                fileHref=el.href;
                if (fileHref==null || !(fileHref.length>0)){
                    fileHref="";
                    $('input[name=download-control][checked]',$(el).parent().parent()).each(function(){
                        fileHref+="&download-control="+$(this).attr('value');
                    });
                    fileHref="/cps/rde/zip_order/eu_pl/?"+fileHref.substring(1,fileHref.length);
                }

                if (!$('#soft_reg_form').length) $('body').append('<div id="soft_reg_form" style="display:none;"></div>');
                formHtml = $("formHtml", xml).text();
                $('#soft_reg_form').append(formHtml);

                $(el).fancybox(
                {
                    'autoDimensions': false,
                    'width': 547,
                    'height': 455,
                    'centerOnScroll': true,
                    'speedIn' : 250,
                    'speedOut' : 250,
                    'overlayShow' : true,
                    'href': '#soft_reg_form',
                    'title': 'Zarejestruj się',
                    'hideOnOverlayClick': false,
                    'onStart':  function() {$('#soft_reg_form').css('display', 'block');},
                    'onCleanup': function() {$('#soft_reg_form').css('display', 'none');}
                });
                $(el).triggerHandler("click.fb");

                $("#fancybox-inner a.download")
                    .click(function()
                    {
                        return soft_reg_send(el, fileHref);
                    })
                    .attr('href', fileHref);
                $("#fancybox-inner select").selectbox();
                $("#fancybox-inner form").bind('submit',function()
                {
                    return soft_reg_send(el, fileHref);
                });
                $('#fancybox-close').unbind().click(function()
                {
                    $(el).unbind("click.fb");
                    $.fancybox.close();
                    $('#soft_reg_form').remove();
                });
                $(document).unbind("keydown");
                $(document).keydown(function(event)
                {
                    if (event.keyCode == 27)
                    {
                        $(el).unbind("click.fb");
                        $.fancybox.close();
                        $('#soft_reg_form').remove();
                    }
                    if (event.keyCode == 13)
                    {
                        if (soft_reg_send(el, fileHref)) window.open(fileHref);
                    }
                });
            }
        }
    });
    return trigger;
}

function soft_reg_send(el, fileHref)
{
    var params='';
    var valid=true;
    var trigger=false;
    $("#fancybox-inner input[type='text'], #fancybox-inner input[type='hidden'], #fancybox-inner select").each(function()
    {
        fName=$(this).attr('name');
        fValue=$(this).attr('value');
        if (fName=='EMail'){
            if (fValue.length>0) $('#emailError').hide();
            else {
                $('#emailError').show();
                valid=false;
            }
        }
        if (fName=='Surname'){
            if (fValue.length>0) $('#surnameError').hide();
            else {
                $('#surnameError').show();
                valid=false;
            }
        }
        if (fName=='Company'){
            if (fValue.length>0) $('#companyError').hide();
            else {
                $('#companyError').show();
                valid=false;
            }
        }
        if (fName=='Postcode'){
            if (fValue.length>0) $('#postcodeError').hide();
            else {
                $('#postcodeError').show();
                valid=false;
            }
        }
        if (fName=='Country'){
            if (fValue.length>0) $('#countryError').hide();
            else {
                $('#countryError').show();
                valid=false;
            }
        }
        if (fName=='Interest'){
            if (fValue.length>0) $('#interestError').hide();
            else {
                $('#interestError').show();
                valid=false;
            }
        }
        if (fName=='Business'){
            if (fValue.length>0) $('#businessError').hide();
            else {
                $('#businessError').show();
                valid=false;
            }
        }
        if ( fName.length > 0 ){
            params+='&'+fName+'='+fValue;
        }
    });
    if( $("#Newsletter").attr("checked") ){
      params+='&Newsletter='+$("#Newsletter").val();
    }

    params='?'+params.substring(1,params.length);
    
    if (valid){
        $.ajax({
               async: false,
               url: '/cps/rde/xchg/eu_pl/xml2xml.xsl/softRegForm.xml'+params,
               type: 'GET',
               dataType: 'xml',
               timeout: 3000,
            error: function(xml){
                $.fancybox.close();
                $('#soft_reg_form').remove();
                $(el).unbind("click.fb");
                //window.open(fileHref);
                trigger = true;
                },
            success: function(xml){
                var status = $("status", xml).text();
                if (status == 0)
                {
                    $.fancybox.close();
                    $('#soft_reg_form').remove();
                    $(el).unbind("click.fb");
                    //window.open(fileHref);
                    trigger = true;
                }
                else
                {
                    formHtml = $("formHtml", xml).text();
                    alert(formHtml);
                    $('#fancybox-inner').empty();
                    $('#fancybox-inner').append(formHtml);
                    $("#fancybox-inner select").selectbox();
                    $("#fancybox-inner a.download").click(function(){ return soft_reg_send(fileHref); }).attr('href',fileHref);
                    $("#fancybox-inner form").bind('submit',function(){ return soft_reg_send(fileHref); });
                }
            }
        });
    }
    return trigger;
    
}

function submitDSearch(opts)
{
/* no longer needed due to jquery update
    if ($("#dsearchform select[name=country]").val()=="" ){
        opts.itemArray.push({'url':"#dsearcherror"});
    }
    else {
        var params = "?country=" + $("#dsearchform select[name=country]").attr("value") + "&zipcode=" + $("#dsearchform input[name=zipcode]").attr("value") + "&type=" + $("#dsearchform select[name=type]").attr("value") + "&ziplabel=" + $("#dsearchform input[name=ziplabel]").attr("value");
        opts.itemArray.push({'url':$("#dsearchform").attr("action")+params});
    }
*/
}

function clearElement(element, focus, value)
{
    if(focus){
        if(element.value==value){
            element.value="";   
        }
    }
    else{
        if(element.value==""){
            element.value=value;
        }
    }
}


function showSoftReg(opts)
{
/* no longer needed due to jquery update
    opts.itemArray.push({url: "#soft_reg_form", title: "Zarejestruj się"});
*/
}

 
function selectDropdownOption(element, wert)
{
    for (var i=0; i<element.options.length; i++) 
    {
        if (element.options[i].value == wert) 
        {
            element.options[i].selected = true;        
        } else {
            element.options[i].selected = false;    
        }
    }
}

function checkForm(name,rules,inner)
{
    if (performCheck(name, rules, inner))
    {
        return true;
    } else {
        var field;
        $('.form_error_inline').each(function()
        {
            field=$(this).attr('id');
            field=field.substring(0,field.length - 5);
            if($('#'+field)!=null)
            {
                $('#'+field).focus();
                window.scrollBy(0,-40);
                return false;
            }
        });
    }
}

function bookmarking(thisForm){
    var params="";
    $("input",thisForm).each(function(){
        if ($(this).attr("type")=="hidden" || ($(this).attr("type")=="checkbox" && $(this).attr("checked")!="")){
        params+="&"+$(this).attr("name")+"="+Url.encode($(this).attr("value"));
        }
        if (params.length != 0) params="?"+params.substring(1, params.length);
    });
    $("#bookmark_container").load("/cps/rde/xchg/eu_pl/hs.xsl/bookmarks.html"+params);
}

function fixFancyHover(offsetX, offsetY)
{
    $('#fancybox-wrap,.fancybox-ie')
        .css('top', tempFancyPosition.top + offsetY + 'px').css('left', tempFancyPosition.left + offsetX + 'px');
}
 
$(document).ready(function(){

    $('.selectbox .selectbox-wrapper').click(function(){
    
        if($.browser.msie == true){

            $(this).css('display', 'block').css('background-color', 'red');    
        
        }    

    });

});

// Setting hover-effect top-websites
$(function() {
    $("#mainnavigation ul li.topsites:last-child").hover(
      function () {
        $(this).addClass("hover");
      },
      function () {
        $(this).removeClass("hover");
      }
    );    
});
