var ajaxObjects = new Array();
var path = sShopAddr + 'ajax/ajax_response.php';
var imagePath = sShopAddr + 'shared/default/img/';
var bNewsletter = false;
var bOrder = false;

function formBasketPlusMinus(parentElement, sign, iProductIdx, fPriceWithoutTax, fPriceWithTax){
    inputElement = parentElement.parentNode.getElementsByTagName('input').item(0);
    
    if (sign == '+' && (arguments.length == 5 || (arguments.length >= 6 && arguments[5] == (-1)) || (arguments.length >= 6 && inputElement.value < arguments[5]))) {
        inputElement.value++; // arguments[2]==(-1) - gdy produkt jest wyczerpany (nie istnieja informacje na jego temat w bazie danych) dajemy wowczas wolna reke administratorowi
        setBasketCount(iProductIdx, inputElement.value, arguments[5], fPriceWithoutTax, fPriceWithTax);
    }
    
    if (sign == '-' && (inputElement.value > 1)) {
        inputElement.value--;
        setBasketCount(iProductIdx, inputElement.value, arguments[5], fPriceWithoutTax, fPriceWithTax);
    }
}

function setBasketCount(iIdx, iCount, iMaxCount, fPriceWithoutTax, fPriceWithTax){
    var url = sShopAddr + sLangShort + '/Basket/0/Cheing/';
    var pars = 'index=' + iIdx + '&' + 'count=' + iCount + '&' + 'max=' + iMaxCount;
    var ajaxIndex = ajaxObjects.length;
    
    ajaxObjects[ajaxIndex] = new XHR({
        onRequest: countLoader,
        onSuccess: countResponse,
        onFailure: countResponseError
    }).send(url, pars);
    
    function countLoader(originalRequest){
    }
    function countResponseError(originalRequest){
    }
    function countResponse(originalRequest){
        if ($('value-with-tax[' + iIdx + ']') != undefined) {
            $('value-with-tax[' + iIdx + ']').setText(number_format(fPriceWithTax * iCount, 2, '.', ''));
        }
        if ($('value-without-tax[' + iIdx + ']') != undefined) {
            $('value-without-tax[' + iIdx + ']').setText(number_format(fPriceWithoutTax * iCount, 2, '.', ''));
        }
        sumValue();
    }
}


function sumValue(){
    var fValueWithTax = 0;
    var fValueWithoutTax = 0;
    var iEndKeyProduct = $('iEndKeyProduct').value;
    for (var i = 0; i <= iEndKeyProduct; i++) {
        if ($('value-with-tax[' + i + ']') != undefined) {
            fValueWithTax += parseFloat($('value-with-tax[' + i + ']').innerHTML);
        }
        if ($('value-without-tax[' + i + ']') != undefined) {
            fValueWithoutTax += parseFloat($('value-without-tax[' + i + ']').innerHTML);
        }
    }
    $('sum-value-with-tax').innerHTML = number_format(fValueWithTax, 2, '.', '');
    if ($('sum-value-without-tax') != undefined) {
        $('sum-value-without-tax').innerHTML = number_format(fValueWithoutTax, 2, '.', '');
    }
}


function deleteBasketProduct(iIdx, oElement){
    var url = sShopAddr + sLangShort + '/Basket/' + iIdx + '/Delete/';
    var ajaxIndex = ajaxObjects.length;
    //alert(url);
    ajaxObjects[ajaxIndex] = new XHR({
        onRequest: deleteLoader,
        onSuccess: deleteResponse,
        onFailure: deleteResponseError
    }).send(url);
    
    function deleteLoader(originalRequest){
    }
    function deleteResponseError(originalRequest){
    }
    function deleteResponse(originalRequest){
        var oTr = oElement.parentNode.parentNode;
        oTr.parentNode.removeChild(oTr);
        sumValue();
    }
}

function deleteCheckroomProduct(iIdx, oElement){
    var url = sShopAddr + sLangShort + '/Basket/' + iIdx + '/CheckroomDelete/';
    var ajaxIndex = ajaxObjects.length;
    
    ajaxObjects[ajaxIndex] = new XHR({
        onRequest: deleteLoader,
        onSuccess: deleteResponse,
        onFailure: deleteResponseError
    }).send(url);
    
    function deleteLoader(originalRequest){
    }
    function deleteResponseError(originalRequest){
    }
    function deleteResponse(originalRequest){
        var oTr = oElement.parentNode.parentNode;
        oTr.parentNode.removeChild(oTr);
        sumValue();
    }
}

// czyta plik na serwerze
function process(){
    // lancuch parametrow
    var params = new String();
    
    if (arguments[0] == 'order') {
        params = "order=" + arguments[0] + "&";
        params += "country=" + arguments[1] + "&";
        params += "type1=" + arguments[2] + "&";
        params += "type2=" + arguments[3] + "&";
        params += "type3=" + arguments[4] + "&";
        params += "weight=" + arguments[5] + "&";
        params += "lang=" + arguments[6];
        
    }
    
    if (arguments[0] == 'newsletter') {
        var sEmail = $('email').value;
        params = "newsletter=" + sEmail + "&";
        params += "lang=" + arguments[1];
        bNewsletter = true;
        bOrder = false;
    }
    else {
        if (arguments[0] == 'order') {
            bOrder = true;
            bNewsletter = false;
        }
    }
    
    
    var ajaxIndex = ajaxObjects.length;
    
    ajaxObjects[ajaxIndex] = new XHR({
        method: 'get',
        onRequest: orderLoader,
        onSuccess: orderResponse,
        onFailure: orderResponseError
    }).send(path, params);
    
    //var summaryCostCurrency = $('summaryCostCurrency');
    
    function orderLoader(originalRequest){
        if (bNewsletter) {
            if ($('newsletterResponse') != undefined) 
                $('newsletterResponse').innerHTML = '';
            $('loader').innerHTML = '<img src="' + imagePath + 'ajax-loader.gif" alt="" />';
        }
        if (bOrder) {
            if ($('buttonSubmit') != undefined) 
                $('buttonSubmit').style.display = 'none';
            if ($('plusCost') != undefined) 
                $('plusCost').style.visibility = 'hidden';
            if ($('deliveryCostShow') != undefined) 
                $('deliveryCostShow').style.visibility = 'hidden';
            if ($('deliveryCostCurrency') != undefined) 
                $('deliveryCostCurrency').style.visibility = 'hidden';
            if ($('equalCost') != undefined) 
                $('equalCost').style.visibility = 'hidden';
            if ($('summaryCostShow') != undefined) 
                $('summaryCostShow').style.visibility = 'hidden';
            if ($('summaryCostCurrency') != undefined) 
                $('summaryCostCurrency').style.visibility = 'hidden';
            $('loader-order').innerHTML = '<img src="' + imagePath + 'ajax-loader.gif" alt="" />';
        }
    }
    function orderResponseError(originalRequest){
        if (bNewsletter) {
            $('loader').innerHTML = '';
        }
        if (bOrder) {
            $('loader-order').innerHTML = '';
        }
        alert("Nie moga nawiazac polaczenia z serwerem");
    }
    function orderResponse(originalRequest){
        if (bNewsletter) {
            // przetwarza wiadomosa z serwera
            handleServerResponse(this.response);
            if ($('loader') != undefined && this.transport.readyState == 4) 
                $('loader').innerHTML = '';
        }
        if (bOrder) {
            if ($defined($('buttonSubmit'))) 
                $('buttonSubmit').style.display = 'block';
            if ($defined($('plusCost'))) 
                $('plusCost').style.visibility = 'visible';
            if ($defined($('deliveryCostShow'))) 
                $('deliveryCostShow').style.visibility = 'visible';
            if ($defined($('deliveryCostCurrency'))) 
                $('deliveryCostCurrency').style.visibility = 'visible';
            if ($defined($('equalCost'))) 
                $('equalCost').style.visibility = 'visible';
            if ($defined($('summaryCostShow'))) 
                $('summaryCostShow').style.visibility = 'visible';
            if ($defined($('summaryCostCurrency'))) 
                $('summaryCostCurrency').style.visibility = 'visible';
            // przetwarza wiadomosa z serwera
            handleServerResponse(this.response);
            if ($defined($('loader-order')) && this.transport.readyState == 4) 
                $('loader-order').innerHTML = '';
        }
    }
}


// obsluguje odpowiedz otrzymana z serwera
function handleServerResponse(xmlRequest){
    // pobiera odpowiedz serwera podana jako obiekt DOM XML
    var xmlResponse = xmlRequest.xml;
    
    // przechwycenie potencjalnych bledow przez IE i Opere
    if (!xmlResponse || !xmlResponse.documentElement) 
        throw ("Invalid XML structure:\n" + xmlRequest.text);
    
    // przechwycenie potencjalnych bledow przez Firefox
    var rootNodeName = xmlResponse.documentElement.nodeName;
    if (rootNodeName == "parsererror") 
        throw ("Niepoprawna struktura XML:\n" + xmlRequest.text);
    // pobiera element nadrzedny (element document)
    xmlRoot = xmlResponse.documentElement;
    // sprawdzanie, czy otrzymalismy taki dokument XML, jakiego sie spodziewalismy
    if (rootNodeName != "response" || !xmlRoot.firstChild) 
        throw ("Niepoprawna struktura XML:\n" + xmlRequest.text);
    
    var iResponseNumber = new Number(0);
    var aResponseName = new Array();
    var sResponseName = '';
    var aResponseText = new Array();
    var sResponseText = '';
    var sResponseNameText = '';
    var cntArray = new Number(0);
    var newIndex = new Number(0);
    
    for (i = 0; i < xmlRoot.childNodes.length; i++) {
        xmlRootChild = xmlRoot.childNodes.item(i);
        if (xmlRootChild.nodeName == 'number') //  <number>
            iResponseNumber = xmlRootChild.firstChild.data;
        if (xmlRootChild.nodeName == 'name') {//  <name>
            cntArray = aResponseName.length;
            newIndex = cntArray + 1;
            aResponseName[newIndex] = xmlRootChild.firstChild.data;
        }
        if (xmlRootChild.nodeName == 'content') {//  <content>
            cntArray = aResponseText.length;
            newIndex = cntArray + 1;
            aResponseText[newIndex] = xmlRootChild.firstChild.data;
        }
    }
    
    if (bOrder && $('deliveryCost') != undefined) {
        //  $("response").className = 'responseNewsletterAdd' ;
        //  $("response").className += ' ' + responseType ;
        for (var j = 0; j < aResponseName.length; j++) 
            sResponseNameText += '<br> <b>' + aResponseName[j] + '</b> <br>' + aResponseText[j];
        
        //$("response").innerHTML = iResponseNumber + sResponseNameText ;
        
        $("deliveryCost").value = iResponseNumber;
        if ($('deliveryCostShow') != undefined) 
            $('deliveryCostShow').innerHTML = iResponseNumber;
        //  alert('iResponseNumber:' + parseFloat(iResponseNumber) + '  $("orderCost").value:' + parseFloat($("orderCost").value))
        var iResponseNumberSum = parseFloat(iResponseNumber) + parseFloat($("orderCost").value);
        if ($('summaryCostShow') != undefined) 
            $('summaryCostShow').innerHTML = iResponseNumberSum.toFixed(2);
        
        if ($('plusCost') != undefined) 
            $('plusCost').style.visibility = 'visible';
        if ($('deliveryCostShow') != undefined) 
            $('deliveryCostShow').style.visibility = 'visible';
        if ($('deliveryCostCurrency') != undefined) 
            $('deliveryCostCurrency').style.visibility = 'visible';
        if ($('equalCost') != undefined) 
            $('equalCost').style.visibility = 'visible';
        if ($('summaryCostShow') != undefined) 
            $('summaryCostShow').style.visibility = 'visible';
        if ($('summaryCostCurrency') != undefined) 
            $('summaryCostCurrency').style.visibility = 'visible';
    }
    
    if (bNewsletter && $('newsletterResponse') != undefined) {
    
        for (var j = 0; j < aResponseText.length; j++) 
            if (aResponseText[j] != undefined) 
                sResponseNameText += aResponseText[j];
        
        $('newsletterResponse').style.visibility = 'visible';
        $('newsletterResponse').innerHTML = sResponseNameText;
        
        if (iResponseNumber == 2 && $('email') != undefined) 
            $('email').value = '';
    }
    
    if (bOrder && $('buttonSubmit') != undefined) 
        $('buttonSubmit').style.display = 'block';
    
    
    //  alert(responseNumber + '<br> <b>' + responseName + '</b> <br>' + responseText)	

    // pomyslnie dodany adres, mozna oczyscic pole formularza
    //  if(responseType == 'info') 
    //    $("newsletterEmail").value = '' ;
}

// - - - - - - - - -


function showRadio(){

    aKey = arguments[0];
//    alert("a:"+a[aKey]); 
    if (arguments.length == 1) 
        var aType = a[aKey];
    if (arguments.length == 2) 
        var aType = a[aKey][arguments[1]];
    if (arguments.length == 3) 
        var aType = a[aKey][arguments[1]][arguments[2]];
    
    var oBody = document.body;
    var oDivBase = document.getElementById('PaymentDelivery');
    
    $('buttonSubmit').style.display = 'none';
    $('plusCost').style.visibility = 'hidden';
    $('deliveryCostShow').style.visibility = 'hidden';
    $('deliveryCostCurrency').style.visibility = 'hidden';
    $('equalCost').style.visibility = 'hidden';
    $('summaryCostShow').style.visibility = 'hidden';
    $('summaryCostCurrency').style.visibility = 'hidden';
    $("response").innerHTML = '';
    //$('loader').innerHTML = '';
    
    if (aKey == 'type1') 
        sNextType = 'type2';
    if (aKey == 'type2') 
        sNextType = 'type3';
    //	sNextType = 'type2' ;
    var sOrderHiddenRadio = new String();
    for (var k in aType) 
        if (arguments[1] == undefined) 
            sOrderHiddenRadio += "hiddenRadio('" + sNextType + "','" + aType[k]['value'] + "'); ";
        else 
            sOrderHiddenRadio += "hiddenRadio('" + sNextType + "','" + arguments[1] + "','" + aType[k]['value'] + "'); ";
    
    var oDivGroup = document.createElement('div');
    
    // tytul bloku
    var oH4 = document.createElement('h2');
    switch (aKey) {
        case 'type1':
            var sTxt = $('sTitleBlockDelivery').value;
            break;
        case 'type2':
            var sTxt = $('sTitleBlockPayment').value;
            break;
        case 'type3':
            var sTxt = $('sTitleBlockDeliveryParticular').value;
            break;
    }
    var oH4Txt = document.createTextNode(sTxt);
    oH4.appendChild(oH4Txt);
    
    oDivGroup.appendChild(oH4);
    
    for (var k in aType) {
    
        if (aType[k]['value'] != undefined) {
        
            var oDiv = document.createElement('div');
            
            var sUserAgent = navigator.userAgent;
            var bIsIE = sUserAgent.indexOf("compatible") > -1 && sUserAgent.indexOf("MSIE") > -1;
            var sInputIE = '<input name="' + aKey + '" onclick="' + sOrderHiddenRadio + 'if(' + aType[k]['end'] + ') {getOrderPrice();} else ' + sOrderShowRadio + ' ;" />';
            
            var oInput = document.createElement(bIsIE ? sInputIE : 'input'); // fix bug IE
            oInput.setAttribute('type', 'radio');
            oInput.setAttribute('name', aKey);
            oInput.setAttribute('value', aType[k]['value']);
            oInput.setAttribute('id', 'id' + aKey + k);
            var sOrderShowRadio = new String();
            if (arguments[1] == undefined) 
                sOrderShowRadio = "showRadio('" + sNextType + "','" + aType[k]['value'] + "')";
            else 
                sOrderShowRadio = "showRadio('" + sNextType + "','" + arguments[1] + "','" + aType[k]['value'] + "')";
            //process
            sSendType1 = new String();
            /*
             for (i=0; i<document.forms[0].type1.length; i++)
             if(document.forms[0].type1[i].checked)
             sSendType1 = document.forms[0].type1[i].value ;
             */
            //sSendType1 = document.forms['order'].elements['type1'].data ;
            oInput.setAttribute('onclick', sOrderHiddenRadio + "if(" + aType[k]['end'] + ") {getOrderPrice();} else " + sOrderShowRadio + ";");
            
            var sLabelIE = '<label for="id' + aKey + k + '"></label>';
            var oLabel = document.createElement(bIsIE ? sLabelIE : 'label'); // fix bug IE
            oLabel.setAttribute('for', 'id' + aKey + k);
            oLabel.setAttribute('id', 'idLabel' + aKey + k);
            
            var oTxt = document.createTextNode(aType[k]['txt']);
            
            oLabel.appendChild(oTxt);
            
            oDiv.appendChild(oInput);
            oDiv.appendChild(oLabel);
            oDivGroup.appendChild(oDiv);
            //$('PaymentDelivery').appendChild(oDiv);
        }
    }
    //	  var oHr = document.createElement('hr');	
    //	  $('PaymentDelivery').appendChild(oHr);
    
    oDivGroup.className = 'form-block';
    $('PaymentDelivery').appendChild(oDivGroup);
}


function getOrderPrice(getOrderPrice){
    var iLangValue = document.forms['orderForm'].elements['iLangId'].value;
    var iAreaValue = document.forms['orderForm'].elements['iCountryId'].value;
    var iWeightValue = document.forms['orderForm'].elements['iProductsWeight'].value;
    
    var elementRadio1 = document.forms['orderForm'].elements['type1'];
    var elementRadio2 = document.forms['orderForm'].elements['type2'];
    var elementRadio3 = document.forms['orderForm'].elements['type3'];
    
    sElementRadio1Value = new String();
    if (elementRadio1 == undefined) 
        sElementRadio1Value = '';
    else 
        sElementRadio1Value = getRadioValue(elementRadio1);
    
    sElementRadio2Value = new String();
    if (elementRadio2 == undefined) 
        sElementRadio2Value = '';
    else 
        sElementRadio2Value = getRadioValue(elementRadio2);
    
    sElementRadio3Value = new String();
    if (elementRadio3 == undefined) 
        sElementRadio3Value = '';
    else 
        sElementRadio3Value = getRadioValue(elementRadio3);
    
    //$('response').innerHTML = 'Lang ID: '+iLangValue + '<br/>' + 'Weight: '+iWeightValue + '<br/>' + 'elementRadio1: '+sElementRadio1Value + '<br/>' + 'elementRadio2: '+sElementRadio2Value + '<br/>' + 'elementRadio3: '+sElementRadio3Value ;
    //ajax
    process('order', iAreaValue, sElementRadio1Value, sElementRadio2Value, sElementRadio3Value, iWeightValue, iLangValue);
}

function getRadioValue(elementRadio){
    if (elementRadio.length != undefined) {
        for (i = 0; i < elementRadio.length; i++) {
            if (elementRadio[i].checked) 
                return elementRadio[i].value;
        }
    }
    else {
        if (elementRadio.checked) 
            return elementRadio.value;
    }
    return false;
}

function hiddenRadio(){
    aKeyDel = arguments[0];
    if (arguments.length == 2) {
        aType = a[aKeyDel][arguments[1]];
        hiddenElement(aType, aKeyDel);
        aKeyDel = 'type3'
        hiddenElement(aType, aKeyDel);
    }
    if (arguments.length == 3) {
        aType = a[aKeyDel][arguments[1]][arguments[2]];
        hiddenElement(aType, aKeyDel);
    }
}

function hiddenElement(aType, aKeyDel){
    for (var k = 0 in aType) {
        var oInput = $('id' + aKeyDel + k);
        if (oInput != undefined) {
            //oInput.parentNode.removeChild(oInput);
            var oDiv = oInput.parentNode;
            var oDivGroup = oDiv.parentNode;
            var aH4 = oDivGroup.getElementsByTagName('h2');
            var oH4 = aH4[0];
            
            oDivGroup.parentNode.removeChild(oDivGroup);
            oH4.parentNode.removeChild(oH4);
        }
        /*
         var oLabel = $('idLabel'+aKeyDel+k);
         if(oLabel != undefined)
         oLabel.parentNode.removeChild(oLabel);
         */
    }
}

