//================================================================================================================
//--- Global variables
//================================================================================================================
var strAjaxPath = '/include/ajax/ajaxRequest.asp';              //--- Default AJAX request path
var strCaptchaPath = '/include/captcha/captchaValidation.asp';  //--- AJAX request path for the captcha validation
var ajaxRequest;                                                //--- Used to store the AJAX request
var intShippingCost = 15;                                       //--- Set the shipping costs
//================================================================================================================

/*==========================================================
Description:    Open a new window
Parameters:     strURL:         Page URL
                strWinName:     Window name
                strWinWidth:    Window width
                strWinHeight:   Window height
Created:        02.11.2009/JOD
Modified:       ---
==========================================================*/
function jsfOpenWin(strURL, strWinName, strWinWidth, strWinHeight) {
    if (document.cmMailForm.cmFormItem_strCandidatureCat.value != '') {
        window.open(strURL, strWinName, 'width=' + strWinWidth + ',height=' + strWinHeight);
    } else {
        alert('Wählen Sie bitte die Option Bewerbung als zuerst');
    }
}

/*==========================================================
Description:    Open a window
Parameters:     strURL:     Page URL
Created:        16.12.2009/JOD
Modified:       ---
==========================================================*/
function jsfOpenURL(strURL) {
    window.location.href = strURL;
}

/*==========================================================
Description:    Write the e-mail address with JS to avoid
                spam problems
				
Parameters:     strUserName:    e-mail address
                strDomain:      domain of the address
                strLinkText:    string to link. If empty, the email will be displayied
Created:        17.11.2009/JOD
Modified:       05.12.2009/JAP
==========================================================*/
function jsfHideEmail(strUserName, strDomain, strLinkText) {
	if (strLinkText=='')
	{
		strLinkText = strUserName + '@' + strDomain
	}
    document.write('<a href=\"mailto:' + strUserName + '@' + strDomain + '\" style=\"border-bottom-style:none;\">'+ strLinkText +'</a>');
}

/*=================================================
Description:  Perform an AJAX request
Parameters:   strParams:   params for the request
Returns:      AJAX response as JSON
Created:      02.11.2009/JOD
Modified:
=================================================*/
function doAjaxRequest(strParams, strRequestPath) {
    var ajaxRetVal = '';
    var ajaxProcess = new Ajax.Request(strRequestPath, {
        method: 'post',
        parameters: strParams,
        contentType: 'application/x-www-form-urlencoded; charset=ISO-8859-1',
        asynchronous: false,
        onSuccess: function(transport) {
            return transport.responseText;
        }
    });
    ajaxRetVal = ajaxProcess.transport.responseText.evalJSON();
    //--- Return AJAX response
    return ajaxRetVal;
}

/*==========================================================
Description:    Add a product item to the basket
Parameters:     intProductID:       Product ID
                strProductName:     Product name
                strProductPrice:    Product price
                intProductQuantity: Product quantity
                strAction:          Incremente or decremente
                strMode:            Basket or detail
Created:        02.11.2009/JOD
Modified:
==========================================================*/
function jsfAddItemToBasket(intProductID, strProductName, strProductPrice, intProductQuantity, strAction,strMode) {
    if (intProductQuantity == '') {
        intProductQuantity = document.getElementById('cmFormItemProduct_' + intProductID + '_Anzahl').value;
    }
    //--- Show an error warning if the quantity is not defined
    if (intProductQuantity == '') {
        alert('Bitte Anzahl auswählen');
    } else {
        //--- Show the AJAX loader image
        jsfShowAjaxLoader();
        var strParams = 'productID=' + intProductID + '&productName=' + strProductName + '&productPrice=' + strProductPrice + '&productQuantity=' + intProductQuantity + '&action=' + strAction;
        ajaxRequest = doAjaxRequest(strParams, strAjaxPath);
        var delayFunction = function() { jsfWriteBasket(ajaxRequest); };
        setTimeout(delayFunction, 500);
        if (strMode == 'basket') {
            jsfClearElement('cmFormItemProduct_' + intProductID + '_Anzahl');
        } else if(strMode == 'detail') {
            jsfWriteProductIncrement(intProductID, strProductName, strProductPrice);
        }
    }
}

/*====================================================
Description:    Load the basket using AJAX
Parameters:     intDisplayType: 0 = basket / 1 = order
Created:        02.11.2009/JOD
Modified:       ---
====================================================*/
function jsfLoadBasket(intDisplayType) {
    var strParams = '';
    var delayFunction;
    //--- Create an AJAX request to load the current basket
    ajaxRequest = doAjaxRequest(strParams, strAjaxPath);
    if (ajaxRequest.basketEmpty != 'true') {
        if (intDisplayType == 0) {
            jsfShowAjaxLoader();
            delayFunction = function() { jsfWriteBasket(ajaxRequest); };
            setTimeout(delayFunction, 500);
        } else if (intDisplayType == 1) {
            delayFunction = function() { jsfWriteUserOrder(ajaxRequest); };
            setTimeout(delayFunction, 500);
        }
    } else {
        //--- Write comment for an empty basket
        jsfWriteEmptyBasket();
    }
}

/*=================================================
Description:    Display the AJAX loader image while
                updating the basket using AJAX
Parameters:     ---
Created:        02.11.2009/JOD
Modified:       ---
=================================================*/
function jsfShowAjaxLoader() {
    document.getElementById('panelShopBasket').innerHTML = '<div class="clsAjaxLoader"><img src="/images/ajaxLoader.gif" alt="" /></div>';
}

/*=================================================
Description:    Remove a product item from the basket
                using AJAX
Parameters:     intProductID:   product ID
Created:        02.11.2009/JOD
Modified:       ---
=================================================*/
function jsfDeleteItem(intProductID) {
    if(confirm('Möchten Sie wirklich diesen Produkt löschen?')) {
        jsfShowAjaxLoader();
        var strParams = 'productID=' + intProductID +'&action=delete';
        ajaxRequest = doAjaxRequest(strParams, strAjaxPath);
        var delayFunction = function() { jsfWriteBasket(ajaxRequest); };
        jsfClearElement('cmFormItemProductDetail_' + intProductID + '_Anzahl');
        setTimeout(delayFunction, 500);
    }
}

/*========================================
Description:    Clear an HTML element
Parameters:     intProductID:   product ID
Created:        02.11.2009/JOD
Modified:       ---
========================================*/
function jsfClearElement(strObjID) {
    var objElement = document.getElementById(strObjID);
    //--- Check if the HTML element exists
    if (jsfCheckIsObject(strObjID)) {
        objElement.value = '';
    }
}

/*============================================
Description:    Check if an HTML object exists
Parameters:     objID:   ID of the element
Returns:        True or false
Created:        11.11.2009/JOD
Modified:       ---
============================================*/
function jsfCheckIsObject(objID) {
    if (document.getElementById(objID)) { 
        return true; 
    } else {
         return false; 
    }
}

/*=========================================================
Description:    Write a default text if the basket is empty
Parameters:     ---
Created:        02.11.2009/JOD
Modified:       ---
=========================================================*/
function jsfWriteEmptyBasket() {
    if (jsfCheckIsObject('panelShopBasket') && jsfCheckIsObject('boxSendBasket')) {
        document.getElementById('panelShopBasket').innerHTML = '<div class="clsEmptyBasket">Ihr Warenkorb ist leer</div>';
        document.getElementById('boxSendBasket').style.display = 'none';
    }
}

/*=================================================
Description:  Delete the content of an HTML element
Parameters:   intProductID:   product ID
Created:      02.11.2009/JOD
Modified:
=================================================*/
function jsfWriteBasket(ajaxRequest) {
    //--- Check if a have an empty basket to display a message
    if (ajaxRequest.productsItems.length == 0) {
        jsfWriteEmptyBasket();
    } else {
        var strRetVal = '<table border="0" cellpadding="0" cellspacing="0">';
        //--- Loop through the whole basket JSON object
        for (i = 0; i < ajaxRequest.productsItems.length; i++) {
            //--- Read values from JSON
            var intProductID            = ajaxRequest.productsItems[i].productID;
            var strProductName          = ajaxRequest.productsItems[i].productName;
            var lngProductPrice         = ajaxRequest.productsItems[i].productPrice;
            var intProductQuantity      = ajaxRequest.productsItems[i].productQuantity;
            //--- Format the number using two decimals
            var lngTotalProductPrice = (lngProductPrice * intProductQuantity).toFixed(2);
            //--- Write records from the JSON
            strRetVal = strRetVal + '<tr>' +
                                        '<td><img src="/images/space.gif" width="14px" height="1px" alt="" /></td>' +
                                        '<td><img src="/images/space.gif" width="81px" height="1px" alt="" /></td>' +
                                        '<td><img src="/images/space.gif" width="55px" height="1px" alt="" /></td>' +
                                        '<td><img src="/images/space.gif" width="80px" height="1px" alt="" /></td>' +
                                        '<td><img src="/images/space.gif" width="50px" height="1px" alt="" /></td>' +
                                    '</tr>' +
                                    '<tr>' +
                                        '<td colspan="5"><img src="/images/space.gif" width="1px" height="10px" alt="" /></td>' +
                                    '</tr>' +
                                    '<tr>' +
                                        '<td></td>' +
                                        '<td><a href="/onlineShopProduktDetail?productID=' + intProductID + '">' + strProductName + '</a></td>' +
                                        '<td><div style="float:left;"><input type="text" value="' + intProductQuantity + '" class="clsFormItemBasketCount" readonly="readonly" /></div><div style="float:left;padding:2px 0px 0px 3px;"><img src="/images/shop/addRemoveItem.gif" usemap="#addRemoveItem_' + intProductID + '" alt="" /></div>' +
                                            '<map name="addRemoveItem_' + intProductID + '">' +
                                                    '<area shape="rect" coords="0,0,10,8" href="javascript:jsfAddItemToBasket(' + intProductID + ',\'' + strProductName + '\', \'' + lngProductPrice + '\',1, \'incremente\',\'basket\');" alt="Einfügen" title="Einfügen">' +
                                                    '<area shape="rect" coords="0,8,9,15" href="javascript:jsfAddItemToBasket(' + intProductID + ',\'' + strProductName + '\', \'' + lngProductPrice + '\',1, \'decremente\',\'basket\');" alt="Entfernen" title="Entfernen">' +
                                            '</map>' +
                                        '</td>' +
                                        '<td>CHF&nbsp;' + lngTotalProductPrice + '</td>' +
                                        '<td><img src="/images/shop/deleteProductItem.gif" alt="" onclick="jsfDeleteItem(' + intProductID + ');" style="cursor:pointer;" /></td>' +
                                    '</tr>' +
                                    '<tr>' +
                                        '<td colspan="5"><img src="/images/space.gif" width="1px" height="10px" alt="" /></td>' +
                                    '</tr>'
        }
        //--- Write basket total price
        strRetVal = strRetVal + '<tr>' +
                                    '<td colspan="5"><div class="textDottedSeparator"></div></td>' +
                                '</tr>' +
                                '<tr>' +
                                    '<td></td>' +
                                    '<td class="clsShopBold" style="padding: 10px 0px 10px 0px;">Preis Total</td>' +
                                    '<td></td>' +
                                    '<td class="clsShopBold" style="padding: 10px 0px 10px 0px;">CHF&nbsp;' + ajaxRequest.basketTotalPrice + ' </td>' +
                                    '<td></td>' +
                                '</tr>' +
                            '</table>'
        //--- Write basket
        document.getElementById('panelShopBasket').innerHTML = strRetVal;
        //--- Show send basket button
        document.getElementById('boxSendBasket').style.display = '';
    }
}

/*=====================================================================
Description:    Get the value to a selected key in the shop basket JSON
Parameters:     ajaxRequest:            JSON object
                intDetailedProductID:   ID of the product
                strSelectedKey:         Selected key
Returns:        The value corresponding to the selected key
Created:        11.11.2009/JOD
Modified:       ---
=====================================================================*/
function jsfGetProductInfos(ajaxRequest, intDetailedProductID, strSelectedKey) {
    var strRetVal = 0;
    //--- Check if we have an empty basket
    if (ajaxRequest.basketEmpty != 'true') {
        //--- Loop through the whole JSON
        for (i = 0; i < ajaxRequest.productsItems.length; i++) {
            //--- Loop through all JSON keys to search the corresponding product ID
            for (var key in ajaxRequest.productsItems[i]) {
                if (ajaxRequest.productsItems[i][key] == intDetailedProductID) {
                    //--- Get the value of the desired key
                    strRetVal = ajaxRequest.productsItems[i][strSelectedKey];
                }
            }
        }
    }
    return strRetVal;
}

/*=====================================================================
Description:    
Parameters:     
                
                
Returns:        
Created:        11.11.2009/JOD
Modified:       ---
=====================================================================*/
function jsfWriteProductIncrement(intDetailedProductID,strDetailedProductName,lngDetailedProductPrice) {
    //--- Load shop basket
    jsfLoadBasket(0);
    var strRetVal = '';
    var strParams = '';
    //--- Get the JSON shop
    //ajaxRequest = doAjaxRequest(strParams, strAjaxPath);
    var intDetailedProductQuantity = jsfGetProductInfos(ajaxRequest, intDetailedProductID, 'productQuantity');
    strRetVal = '<div style="float:left;margin-left:15px;">Anzahl&nbsp;<input type="text" name="cmFormItemProductDetail_' + intDetailedProductID + '_Anzahl" id="cmFormItemProductDetail_' + intDetailedProductID + '_Anzahl" value="' + intDetailedProductQuantity + '" class="clsFormItemBasketCount" readonly="readonly" /></div><div style="float:left;padding:2px 0px 0px 3px;"><img src="/images/shop/addRemoveItem.gif" usemap="#addRemoveItem_' + intDetailedProductID + '" alt="" /></div>' +
                '<map name="addRemoveItem_' + intDetailedProductID + '">' +
                    '<area shape="rect" coords="0,0,10,8" href="javascript:jsfAddItemToBasket(' + intDetailedProductID + ',\'' + strDetailedProductName + '\', \'' + lngDetailedProductPrice + '\',1, \'incremente\',\'detail\');" alt="Einfügen" title="Einfügen">' +
                    '<area shape="rect" coords="0,8,9,15" href="javascript:jsfAddItemToBasket(' + intDetailedProductID + ',\'' + strDetailedProductName + '\', \'' + lngDetailedProductPrice + '\',1, \'decremente\',\'detail\');" alt="Entfernen" title="Entfernen">' +
                '</map>';
    document.getElementById('boxProductIncrement').innerHTML = strRetVal;
}

/*==============================================================
Description:    Write the user's order
Parameters:     ajaxRequest:    the user's basket as JSON object
Returns:        ---
Created:        11.11.2009/JOD
Modified:       ---
==============================================================*/
function jsfWriteUserOrder(ajaxRequest) {
    var strProductName, lngProductPrice, intProductQuantity;
    var strRetVal;
    //--- Check if the basket is empty
    if (ajaxRequest.productsItems.length == 0) {
        strRetVal = '<div style="padding-bottom:10px;"><b>Ihr Warenkorb ist leer</b></div>';
    } else {
        document.getElementById('lblSendOrder').style.display = '';
        //--- Get the basket total price
        var lngTotalPrice = ajaxRequest.basketTotalPrice;
        strRetVal = '<table border="0" cellpadding="0" cellspacing="0" width="455px">' +
                            '<tr>' +
                                '<td><img src="/images/space.gif" width="300px" height="1px" alt="" /></td>' +
                                '<td><img src="/images/space.gif" width="75px" height="1px" alt="" /></td>' +
                                '<td><img src="/images/space.gif" width="80px" height="1px" alt="" /></td>' +
                            '</tr>' +
                            '<tr>' +
                                '<td colspan="3"><div class="textDottedSeparator"></div></td>' +
                            '</tr>';
        //--- Loop through the whole basket JSON object
        for (i = 0; i < ajaxRequest.productsItems.length; i++) {
            strProductName = ajaxRequest.productsItems[i].productName;
            lngProductPrice = ajaxRequest.productsItems[i].productPrice;
            intProductQuantity = ajaxRequest.productsItems[i].productQuantity
            strRetVal = strRetVal + '<tr>' +
                                        '<td>' + strProductName + '</td>' +
                                        '<td align="left">Anzahl:&nbsp;' + intProductQuantity + '</td>' +
                                        '<td align="right" style="padding-right:5px;">CHF&nbsp;' + (lngProductPrice * intProductQuantity).toFixed(2) + '</td>' +
                                    '</tr>' +
                                    '<tr>' +
                                        '<td colspan="3"><div class="textDottedSeparator"></div></td>' +
                                    '</tr>';
        }
        //--- Get the total basket price including the shipping costs
        var lngBasketTotal = (parseFloat(lngTotalPrice)) + (intShippingCost);
        strRetVal = strRetVal + '<tr>' +
                                    '<td>Gesamt</td>' +
                                    '<td></td>' +
                                    '<td align="right" style="padding-right:5px;">CHF&nbsp;' + lngTotalPrice + '</td>' +
                                '<tr>' +
                                '<tr>' +
                                    '<td colspan="3"><img src="/images/space.gif" width="1px" height="5px" alt="" /></td>' +
                                '</tr>' +
                                '<tr>' +
                                    '<td>Versandkosten</td>' +
                                    '<td></td>' +
                                    '<td align="right" style="padding-right:5px;">CHF&nbsp;' + intShippingCost.toFixed(2) + '</td>' + 
                                '<tr>' +
                                '<tr>' +
                                    '<td colspan="3"><div class="textDottedSeparator"></div></td>' +
                                '</tr>'+
                                '<tr>' +
                                    '<td class="clsShopBold">Gesamtotal</td>' +
                                    '<td></td>' +
                                    '<td class="clsShopBold" align="right" style="padding-right:5px;">CHF&nbsp;' + lngBasketTotal + '</td>' + 
                                '</tr>' +
                                '<tr>' +
                                    '<td colspan="3"><div class="textDottedSeparator"></div></td>' +
                                '</tr>';
        strRetVal = strRetVal + '</table>';
    }
    //--- Write HTML output
    document.getElementById('orderConfirmation').innerHTML = strRetVal;
    //jsfReadFields();
}

/*function jsfReadFields() {
    var strSenderAddress = '<p><strong>Ihre Rechnungsadresse</strong><p>';
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderTitle');
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderFirstName');
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderLastName');
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderStreet');
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderLocation');
    strSenderAddress = strSenderAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'senderPhone');
    jsfWriteUserAdress(strSenderAddress, 'boxSenderAddress');
    var strRecipientAddress = '<p><strong>Ihre Lieferadresse</strong></p>';
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientTitle');
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientFirstName');
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientLastName');
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientStreet');
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientLocation');
    strRecipientAddress = strRecipientAddress + '#' + jsfGetCustomerInfos(ajaxRequest, 'recipientPhone');
    jsfWriteUserAdress(strRecipientAddress, 'boxRecipientAddress');
}*/

/*function jsfGetCustomerInfos(ajaxRequest, strField) {
    var strSelVal;
    if (ajaxRequest.userInfos.length != 0) {
        for (i = 0; i < ajaxRequest.userInfos.length; i++) {
            for (var key in ajaxRequest.userInfos[i]) {
                if (key == strField) {
                    strSelVal = ajaxRequest.userInfos[i][key];
                }
            }
        }
    }
    return strSelVal;
}*/

/*function jsfWriteUserAdress(strAddress,strBoxID) {
    var strVal = '';
    arrAddress = strAddress.split("#");
    for (i = 0; i < arrAddress.length; i++) {
        strVal = strVal + arrAddress[i] + '<br />';
    }
    document.getElementById(strBoxID).innerHTML = strVal;
}*/

/*=================================================
Description:  Perform an AJAX request
Parameters:   strParams:   params for the request
Returns:      AJAX response as JSON
Created:      02.11.2009/JOD
Modified:
=================================================*/
function jsfCheckFrm(frm) {
    //--- Validate form required fields
    if (jsfCheckForm(frm)) {
        //--- Get the catpcha value entered by user
        var strCaptchaVal = document.getElementById('captchaCode').value;
        var strParams = 'captchaVal=' + strCaptchaVal;
        //--- Do AJAX request to validate the captcha
        ajaxRequest = doAjaxRequest(strParams, strCaptchaPath);
        //--- Check if the captcha value is correct
        if (ajaxRequest.captchaValidation == '1') {
            //--- Send form to save user's informations
            frm.submit();
        } else {
            //--- Show an error message and reload the captcha
            alert('Der Captcha ist nicht gültig');
            jsfReloadCaptcha('imgCaptcha')
        }
    }
}

function jsfCheckBabyPostcard(frm) {
    if (jsfCheckForm(frm)) {
        frm.submit();
    }
}

/*==========================================
Description:    Get the value of a field
Parameters:     strFieldID:  ID of the field
Returns:        Value of the field
Created:        02.11.2009/JOD
Modified:
==========================================*/
function getFormVal(strFieldID) {
    return document.getElementById(strFieldID).value;
}

/*==========================================
Description:    Clear the value of a field
Parameters:     strFieldID:  ID of the field
Created:        02.11.2009/JOD
Modified:
==========================================*/
function jsfClearField(strFieldID) {
    document.getElementById(strFieldID).value = '';
}

/*=================================================
Description:    Reload the captcha
Parameters:     strImgCaptchaID:  ID of the captcha
Created:        02.11.2009/JOD
Modified:
=================================================*/
function jsfReloadCaptcha(strImgCaptchaID) {
    var objImage = document.images[strImgCaptchaID];
    if (objImage == undefined) {
        return;
    }
    var now = new Date();
    //--- Clear the captcha value used by the user
    jsfClearField(strImgCaptchaID);
    //--- Set the new captcha image
    objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
}

function jsfShowToMotherPanel(obj) {
    if (obj.checked) {
        document.getElementById('boxToRecipient').style.display = 'none';
        document.getElementById('boxToMother').style.display = '';
        document.getElementById('txtRecipientMail').disabled = 'disabled';
    } else {
        document.getElementById('boxToRecipient').style.display = '';
        document.getElementById('boxToMother').style.display = 'none';
        document.getElementById('txtRecipientMail').disabled = '';
    }
}

function jsfCopyFields(cbo) {
    var objForm = document.forms['frmOrder'];
    if (cbo.checked) {
        objForm.recipientTitle.selectedIndex = objForm.senderTitle.selectedIndex;
        objForm.recipientFirstName.value = objForm.senderFirstName.value;
        objForm.recipientLastName.value = objForm.senderLastName.value;
        objForm.recipientStreet.value = objForm.senderStreet.value;
        objForm.recipientLocation.value = objForm.senderLocation.value;
        objForm.recipientLocation.value = objForm.senderLocation.value;
    }
}
