/* -- optional home dir set -- */

if (homedir == undefined)
{
    var homedir = '';
}

/* --- standard and gui functions --- */

function SaveSerial()
{
	if ($('SerialCode'))
    {
    	$('SerialCode').value = $F('serial');
    }
}
function setFocus(id)
{
    try 
    {
        $(id).focus();
        return 1;
    }
    catch (e)
    {
        return 0;
    }
}

function trim(value) 
{
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}

function getKeyCode(e) 
{
    if( !e ) 
    {
        if( window.event ) 
        {
            e = window.event;
        } 
        else 
        {
            return;
        }
    }
    if( typeof( e.which ) == 'number' ) 
    {
        e = e.which;
    } 
    else if( typeof( e.keyCode ) == 'number'  ) 
    {
        e = e.keyCode;
    } 
    else if( typeof( e.charCode ) == 'number'  ) 
    {
        e = e.charCode;
    }
    else 
    {
        return;
    }
    return e;
}

function initEnv()
{
   $('activateText').innerHTML  = text('eActivate');
   $('stornoText').innerHTML  = text('eStorno');
   $('execute').innerHTML   = '<span id="button_txt">' + text('eConfirmActivate') + "</span>";
   $('cancel').innerHTML    = '<span id="button_txt">' + text('eNewSerial') + "</span>";
   $('newSerial').innerHTML = text('eNewNewSerial');
   setFocus('serial');
   $('serial').onkeydown = catchEnter;
   $('activate').disabled=true;
   $('storno').disabled=true; 
}

function text(id)
{
    if ($(id).innerHTML)
    {
        return $(id).innerHTML;
    }
    
    return null;
}

function show(id)
{
    document.write(text(id));
}

function checkSerial(serial)
{
    serial.value = trim(serial.value);
    if (serial.value.length == 0 || serial.value.match(/^[0-9]{13}$/) == null)
    {
        setFocus('serial');
        changeSerialDesc(text('eSerialSyntax'), 'ccError');
        hideError();
        return false;
    }
    
    resetSerialInputDesc();
    return true;
}

function chkEAN13(nr)
{ 
    var nrr = nr;
    var i = 0;
    var o = 0;
    var mod = 0;
    var result = 0;
    var nr = new Array;
    var sum = 0;
    
    for(i=0 , sum=0 , o=0 ; i < (nrr.length - 1) ; i++)
    {
        if(Math.ceil(i/2) * 2 == i)
        {
            o = nrr.substring(i,(i+1)) * 1;
        }
        else
        {
            o = nrr.substring(i,(i+1)) * 3;
        }
        sum = sum + o;
    }
    
    mod = sum % 10;
    
    if(mod == 0)
    {
        result = mod;    
    }
    else
    {
        result = 10 - mod;
    }
       
    if(result == nrr.substring(12,13))
    {
        return true;
    }
    else
    {
        return false;
    } 
}

function getSerial(productid, serial, amount, currency)
{
    if (!checkSerial(serial))
    {
        return false;
    }
    
    $('productid').value = productid;

    getDetails(productid, serial.value, amount, currency);
    return true;
}

function changeSerialDesc(text, style)
{
    $('infoSerialEnter').innerHTML = text;
    $('infoSerialEnter').className = style;
}

function hideDetails()
{
    $('dDetails').style.display = 'none';
    $('container_confirm_serial').style.display = 'none';
    $('container_new_serial').style.display = 'none';
}

function hideSerial()
{
    $('dSerial').style.display = 'none'; 
}

function hideConfirm()
{
    $('dConfirm').style.display = 'none';
}

function showDetails()
{
    $('dDetails').style.display = 'block';
    $('container_confirm_serial').style.display = 'block';
    $('container_new_serial').style.display = 'block';
}

function resetSerialInputDesc()
{
    changeSerialDesc(text('eEnterSerial'), 'ccSerialInputText');
}

function showSerial()
{
    $('serial').value = '';
    $('dSerial').style.display = 'block'; 
    setFocus('serial');
}

function showConfirm()
{
    $('dConfirm').style.display = 'block';
}

function viewConfirm(serial, ean, product, price)
{
    hideSerial();
    showDetails(); 
    showConfirm();
    setDetails(serial, ean, product, price);
}

function viewSerial()
{
    hideWait();
    hideSuccess();
    hideError();
    hideDetails();
    hideConfirm();
    hideStornoElements();
    showSerial();
}

function viewNewSerial()
{
    hideWait();
    hideSuccess();
    hideError();
    hideDetails();
    hideStornoElements();
    showSerial();
}

function hideStornoElements()
{
    $('dStorno').style.display                  = 'none';
    $('container_confirm_storno').style.display = 'none';
    $('storno').disabled                        = true;     /* storno-button auf inaktiv setzen */
    $('activate').disabled                      = true;     /* storno-button auf inaktiv setzen */
    $('found_serial_line').style.display        = 'block';  /* wo-finde-ich-seriennummer block */
    $('serial_status_line').style.display       = 'none';   /* seriennummern-status-zeile */
    $('serial_error_line').style.display        = 'none';   /* fehlerhafte seriennummer + passwort vergessen */
    $('Final').style.display         = 'none';   /* finaler button bei storno */
    $('headline_activation_storno').innerHTML   = text('_HEADLINE_ACTIVATION');          
}

function showWait()
{
    hideError();
    hideSuccess();
    $('dWait').style.display = 'block';
}

function hideWait()
{
    $('dWait').style.display = 'none';
}

function catchEnter(e)
{ 
    if (getKeyCode(e) == 13)
    { 
        $('activate').click();
    } 
}

function setDetails(serial, ean, product, price)
{
    $('infoSerial').innerHTML  = serial;
    $('infoEAN').innerHTML     = ean;
    $('infoProduct').innerHTML = product.substr(0, 40);
    $('infoPrice').innerHTML   = price;
}

function hideError()
{
    $('dServerError').innerHTML = '';
    $('dServerError').style.display = 'none';
}

function hideSuccess()
{
    $('dServerSuccess').innerHTML = '';
    $('dServerSuccess').style.display = 'none';
}

function serverError(msg)
{
    hideConfirm();
    $('dServerError').innerHTML = msg;
    $('dServerError').style.display = 'inline';
}

function serverSuccess(msg)
{
    hideConfirm();
    $('dServerSuccess').innerHTML = msg;
    $('dServerSuccess').style.display = 'inline';
}

function showNewSerial()
{
    $('dNewSerial').style.display = 'block';
}

function hideNewSerial()
{
    $('dNewSerial').style.display = 'none';
}

/* --- Ajax functions --- */

function getDetails(productid, serial, amount, currency)
{
    showWait();
    var timeout = 15;
    var args  = 'action=1';
        args += '&prodid='+productid;
        args += '&serial='+serial;
        args += '&serviceid=3';
        args += '&version=4.2';
        args += '&amount='+amount;
        args += '&curr='+currency;
        
    $('productid').value = productid;

    var myAjax = new Ajax.Request( homedir+'activate-contentcard.php',
                                   {
                                        method: 'post',
                                        parameters: args,
                                        onSuccess: handleDetailResponse,
                                        asynchronous: true
                                    }
                                  );

    new AjaxTimeouter(myAjax, timeout, handleDetailTimeout.bind(handleDetailTimeout) );
}

function handleDetailResponse(myAjax)
{
    var dom = myAjax.responseXML;
    if (dom.getElementsByTagName('ErrorMessage').length || dom.getElementsByTagName('ERROR').length)
    {
        hideWait();
        hideDetails();

        var Code = dom.getElementsByTagName('CODE')[0].childNodes[0].nodeValue;

        fetchCodeMessage(Code);

        if (getCodeMessage().length > 0)
        {
            serverError(Code+': '+getCodeMessage());
        }
        else if (dom.getElementsByTagName('TEXT')[0].childNodes[0].nodeValue.length > 0)
        {
            serverError(Code+': '+dom.getElementsByTagName('TEXT')[0].childNodes[0].nodeValue);
        }
        else
        {
            serverError(Code+': '+text('eError'));
        }
    }
    else
    {
        hideWait();
        var price = String(parseInt(dom.getElementsByTagName('AMOUNT')[0].childNodes[0].nodeValue, 10)/100).replace(/\./g, ',');

        viewConfirm($F('serial'),
                    dom.getElementsByTagName('EANCODE')[0].childNodes[0].nodeValue, 
                    dom.getElementsByTagName('DESCRIPTION')[0].childNodes[0].nodeValue,
                    price+' '+dom.getElementsByTagName('CURRENCY')[0].childNodes[0].nodeValue);
                    
        $('dTan').innerHTML = dom.getElementsByTagName('TAN')[0].childNodes[0].nodeValue;
    }
}

function handleDetailTimeout()
{
    hideWait();
    serverError(text('eTimeout'));
}

function activateSerial(productid, serial, amount, currency, tan)
{
    showWait();
    var timeout = 15;
    var args  = 'action=2';
        args += '&prodid='+productid;
        args += '&serial='+serial;
        args += '&serviceid=3';
        args += '&version=4.2';
        args += '&amount='+amount;
        args += '&curr='+currency;
        args += '&tan='+tan;

    $('productid').value = productid;
        
    var ajax = new Ajax.Request( homedir+'activate-contentcard.php',
                                   {
                                        method: 'post',
                                        parameters: args,
                                        onSuccess: handleActivateResponse,
                                        asynchronous: true
                                    }
                                  );

    new AjaxTimeouter(ajax, timeout, handleDetailTimeout.bind(handleActivateTimeout) );
}

function handleActivateTimeout()
{
    hideWait();
    serverError(text('eTimeout'));
}

function handleActivateResponse(myAjax)
{
    var dom = myAjax.responseXML;

    if (dom.getElementsByTagName('ErrorMessage').length > 0 || dom.getElementsByTagName('PIN').length == 0)
    {
        hideWait();
        showNewSerial();

        var Code = dom.getElementsByTagName('CODE')[0].childNodes[0].nodeValue;
        fetchCodeMessage(Code);

        if (getCodeMessage().length > 0)
        {
            serverError(Code+': '+getCodeMessage());
        }
        else if (dom.getElementsByTagName('TEXT')[0].childNodes[0].nodeValue.length > 0)
        {
            serverError(Code+': '+dom.getElementsByTagName('TEXT')[0].childNodes[0].nodeValue);
        }
        else
        {
            serverError(Code+': '+text('eError'));
        }
        $('Final').style.display = 'block';
        $('freischaltprintbutton').style.display = 'none';
        $('stornoprintbutton').style.display = 'none';
        $('stornoprintcustomerbutton').style.display = 'none';
        $('stornoprintcancelbutton').style.display = 'inline';
    }
    else
    {
        var pin = dom.getElementsByTagName('PIN')[0].childNodes[0].nodeValue;
        $('tan').value = pin;
        
        hideWait();
        //showNewSerial();
        $('Final').style.display = 'block';
        $('freischaltprintbutton').style.display = 'block';
        $('stornoprintbutton').style.display = 'none';
        $('stornoprintcustomerbutton').style.display = 'none';
        $('stornoprintcancelbutton').style.display = 'inline';
        
        serverSuccess(text('eSuccess'));
    }
}

var CodeMessage;

function getCodeMessage()
{
    return CodeMessage;
}

function setCodeMessage(msg)
{
    CodeMessage = msg;
}

function handleGetCodeResponse(myAjax)
{
    setCodeMessage(myAjax.responseText);
}


function handleGetCodeTimeout()
{
    serverError(text('eTimeout'));
}

function fetchCodeMessage(code)
{
    var timeout = 15;
    var args  = 'code='+code;

    var ajax = new Ajax.Request( homedir+'getContentCardMessage.php',
                                   {
                                        method: 'post',
                                        parameters: args,
                                        onSuccess: handleGetCodeResponse,
                                        asynchronous: false
                                    }
                                  );

    new AjaxTimeouter(ajax, timeout, handleGetCodeTimeout.bind(handleGetCodeTimeout) );
}
