/**
*
*  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=en&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,
            frameWidth: 500,
            frameHeight: 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){
    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_en/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)
{
    elID='#soft_reg_form';
    var trigger=false;
    $.ajax({
           async: false,
           url: '/cps/rde/xchg/eu_en/2887.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_en/?"+fileHref.substring(1,fileHref.length);
                }
                if (!$(elID).length) $('body').append("<div id='"+elID.substring(1,elID.length)+"' style='display:none;'></div>");
                formHtml=$("formHtml",xml).text();
                $(elID).append(formHtml);
                $.fn.fancybox.start(el,o);
                $("#fancy_div a.download").click(function(){ return soft_reg_send(fileHref);}).attr('href',fileHref);
                $("#fancy_div select").selectbox();
                $("#fancy_div form").bind('submit',function(){ return soft_reg_send(fileHref);});
                $('#fancy_close').unbind().click(function(){
                    $.fn.fancybox.close(); 
                    $(elID).empty();
                });
                $(document).unbind("keydown");
                $(document).keydown(function(event) {
                    if (event.keyCode == 27) {
                        $.fn.fancybox.close();
                        $(elID).empty();
                    }
                    if (event.keyCode == 13) {
                        if (soft_reg_send(fileHref)) window.open(fileHref);
                    }
                });
                
            }
        }
    });
    return trigger;
}


function soft_reg_send(fileHref)
{
    elID='#soft_reg_form';
    var params='';
    var valid=true;
    var trigger=false;
    $("#fancy_div input[@type='text'], #fancy_div input[@type='hidden'], #fancy_div 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_en/2887.xsl/softRegForm.xml'+params,
               type: 'GET',
               dataType: 'xml',
               timeout: 3000,
            error: function(xml){
                $.fn.fancybox.close();
                $(elID).empty();
                //window.open(fileHref);
                trigger=true;
            },
            success: function(xml){
                var status=$("status",xml).text();
                if (status==0) {
                    $.fn.fancybox.close();
                    $(elID).empty();
                    //window.open(fileHref);
                    trigger=true;
                }
                else {
                    formHtml=$("formHtml",xml).text();
                    $('#fancy_div').empty();
                    $('#fancy_div').append(formHtml);
                    $("#fancy_div select").selectbox();
                    $("#fancy_div a.download").click(function(){ return soft_reg_send(fileHref); }).attr('href',fileHref);
                    $("#fancy_div form").bind('submit',function(){ return soft_reg_send(fileHref); });
                }
            }
        });
        
    }
    return trigger;
    
}

function clearElement(element, focus, value)
{
    if(focus){
        if(element.value==value){
            element.value="";   
        }
    }
    else{
        if(element.value==""){
            element.value=value;
        }
    }
}


function showSoftReg(opts)
{
    opts.itemArray.push({url: "#soft_reg_form", title: "Please register"});
}

 
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_en/hs.xsl/bookmarks.html"+params);
}
