﻿function CMSOnSubmit()
{
    CMSClearEmptyText4Password()
}

function CMSClearEmptyText4Password()
{
    var elements = document.getElementsByTagName('input');
    if (elements != null)
    {
        for (var i = 0; i < elements.length; i++)
        {
            if (elements[i].type == 'password')
            {
                CMSFieldOnFocus(elements[i]);
            }
        }
    }
}

function CMSFieldOnFocus(o)
{
    if ((o != null) && (o.attributes['emptyText'] != null) && (o.value == o.attributes['emptyText'].value))
        o.value = '';
}
function CMSFieldOnBlur(o)
{
    if ((o != null) && (o.attributes['emptyText'] != null) && (o.value == ''))
        o.value = o.attributes['emptyText'].value;
}
function CMSFieldInitializeEmptyValue(o)
{
    if ((o != null) && (o.attributes['emptyText'] != null) && (o.value == ''))
        o.value = o.attributes['emptyText'].value;
}

function CMSOverlayLabel(inputControlClientID, labelControlClientID)
{
    this.inputControl = document.getElementById(inputControlClientID);
    this.labelControl = document.getElementById(labelControlClientID);

    this.hideLabel = function(event)
    {
        event = event || window.event;
        var eventTarget = event.target || event.srcElement;
        if (!eventTarget || !eventTarget.overlayObject) return;

        eventTarget.overlayObject.labelControl.style.display = 'none';
        eventTarget.overlayObject.inputControl.focus();
    };

    this.showLabel = function(event)
    {
        event = event || window.event;
        var eventTarget = event.target || event.srcElement;
        if (!eventTarget || !eventTarget.overlayObject) return;

        if (eventTarget.overlayObject.inputControl.value.length <= '0')
        {
            eventTarget.overlayObject.labelControl.style.display = '';
        }
    };

    ///////////////////////////////////////////////////////////////////////////////////
    // Initialization
    this.Init = function()
    {
        if (!this.labelControl || !this.inputControl) return;

        this.labelControl.overlayObject = this;
        this.inputControl.overlayObject = this;

        var imputControlDim = getDimensions(this.inputControl);
        this.labelControl.style.height = imputControlDim.height + 'px';
        this.labelControl.style.width = imputControlDim.width + 'px';
        this.labelControl.style.position = 'absolute';
        this.labelControl.style.lineHeight = imputControlDim.height + 'px';
        //this.labelControl.style.textAlign = 'center';

        if ((this.inputControl.disabled == null) || (this.inputControl.disabled == undefined) ||
            !this.inputControl.disabled)
        {
            attachEventToElement(this.labelControl, 'click', this.hideLabel);
            attachEventToElement(this.inputControl, 'focus', this.hideLabel);
            attachEventToElement(this.inputControl, 'blur', this.showLabel);
        }

        if (this.inputControl.value.length <= '0')
        {
            this.labelControl.style.display = '';
        }
        else
        {
            this.labelControl.style.display = 'none';
        }
    }
    this.Init();
}

function BuyButtonPerformAction(buttonClientID, hiddenFieldClientID, articleData)
{
    buttonControl = document.getElementById(buttonClientID);
    hiddenFieldControl = document.getElementById(hiddenFieldClientID);
    if (!buttonControl || !hiddenFieldControl) return;

    hiddenFieldControl.value = articleData;
    buttonControl.click();
    return false;
}

function getXMLHttpRequest()
{
    var xhr;
    if (window.XMLHttpRequest)
    {
        if (!(xhr = new XMLHttpRequest())) return false;
    } else
    {
        try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e)
        {
            try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; }
        }
    }
    return xhr;
}

function voteArticle(url, vote, controlID, articleID, currRateLiID, maxValue, imgWidth, avgRateLabelID, totalVotesLabelID, voteSuccesLabelID, voteFailedLabelID, voteRatedYetLabelID)
{
    var xhr = getXMLHttpRequest();
    if (xhr != null)
    {
        var url = url + '?cid=' + controlID + '&aid=' + articleID + '&vote=' + vote;
        xhr.open('GET', url, true);
        xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4)
            {
                xhr.onreadystatechange = function() { };
                voteResponse(xhr, currRateLiID, maxValue, imgWidth, avgRateLabelID, totalVotesLabelID, voteSuccesLabelID, voteFailedLabelID, voteRatedYetLabelID);
            }
        };
        xhr.send(null);
    }
    return false;
}

function voteResponse(xhr, currRateLiID, maxValue, imgWidth, avgRateLabelID, totalVotesLabelID, voteSuccesLabelID, voteFailedLabelID, voteRatedYetLabelID)
{
    var success = false;
    var ratedYet = false;
    var avgRateLabel = document.getElementById(avgRateLabelID);
    var totalVotesLabel = document.getElementById(totalVotesLabelID);
    var voteSuccesLabel = document.getElementById(voteSuccesLabelID);
    var voteFailedLabel = document.getElementById(voteFailedLabelID);
    var voteRatedYetLabel = document.getElementById(voteRatedYetLabelID);
    var currRateLi = document.getElementById(currRateLiID);

    if (xhr && (xhr.status == 200) && xhr.responseText && (xhr.responseText != ''))
    {
        var values = xhr.responseText.split(';');
        if (values.length && values.length >= 1)
        {
            var result = values[0].toLowerCase();
            if ((result == 'ok') && (values.length >= 3) && avgRateLabel && totalVotesLabel)
            {
                var votes = values[1];
                var avgRate = values[2];
                avgRateLabel.innerHTML = avgRate;
                totalVotesLabel.innerHTML = votes;
                setRateWidth(currRateLi, maxValue, imgWidth, avgRate);
                success = true;
            }
            else ((result == 'fail') && (values.length >= 2))
            {
                var errorMessage = values[1];
                if (errorMessage == '100') // rated yet
                    ratedYet = true;
                voteFailedLabel.innerHTML = errorMessage;
            }
        }
    }
    if (voteSuccesLabel && voteFailedLabel)
    {
        setControlVisible(voteSuccesLabel, success);
        setControlVisible(voteFailedLabel, !success && !ratedYet);
        setControlVisible(voteRatedYetLabel, !success && ratedYet);
    }
}

function setRateWidth(currRateLi, maxValue, imgWidth, rate)
{
    var rateValueFloat = parseFloat(rate.replace(',', '.')) * 100;
    if (rateValueFloat && rateValueFloat != NaN)
    {
        var rateValue = parseInt(rateValueFloat);
        if (currRateLi && rateValue && rateValue != NaN)
        {
            var width = (imgWidth * maxValue * rateValue / maxValue) / 100;
            currRateLi.style.width = parseInt(width) + 'px';
        }
    }
}

function setControlVisible(control, visible)
{
    control.style.display = visible ? 'block' : 'none';
}

function attributeEligibleOnChange(url, attributesPanelID, languageID, currencyID, articleID,
    labelPriceIDList, labelWeightIDList, labelStorageIDList)
{
    var xhr = getXMLHttpRequest();
    if (xhr != null)
    {
        var atributesList = getAttributeEligible(attributesPanelID);
        var url = url + '?langID=' + languageID + '&currID=' + currencyID + '&artID=' + articleID + '&alist=' + atributesList + '&wgcont=' + labelWeightIDList + '&stcont=' + labelStorageIDList;
        xhr.open('GET', url, true);
        xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4)
            {
                xhr.onreadystatechange = function() { };
                attributeEligibleOnChangeResponse(xhr, labelPriceIDList, labelWeightIDList, labelStorageIDList);
            }
        };
        xhr.send(null);
    }
    return false;
}

function getAttributeEligible(attributesPanelID)
{
    var attributesPanel = document.getElementById(attributesPanelID);
    var atributesList = '';
    if (attributesPanel)
    {
        for (var i = 0; i < attributesPanel.childNodes.length; i++)
        {
            if ((attributesPanel.childNodes[i].attributes != null) &&
                (attributesPanel.childNodes[i].attributes['panelAttribute'] != null))
            {
                for (var j = 0; j < attributesPanel.childNodes[i].childNodes.length; j++)
                {
                    var control = attributesPanel.childNodes[i].childNodes[j];
                    if ((control.attributes != null) && (control.attributes['attributeID']))
                    {
                        atributesList = atributesList +
                                control.attributes['attributeID'].value + '/a';
                        atributesList = atributesList +
                                control.attributes['attributeTypeID'].value + '/a';

                        atributesList = atributesList +
                                getAttributeEligibleValue(control);

                        if (control.attributes['attributeSettingValue'])
                        {
                            atributesList = atributesList + "/a";
                            atributesList = atributesList +
                                control.attributes['attributeSettingValue'].value;
                        }
                        atributesList = atributesList + '/t';
                    }
                }
            }
        }
    }
    return atributesList;
}

function getAttributeEligibleValue(control)
{
    if (control && (control.tagName.toLowerCase() == 'select'))
    {
        return control.value;
    }
    else if (control && (control.tagName.toLowerCase() == 'span'))
    {
        var checkbox = getInnerCheckBoxSpanControl(control)
        if (checkbox)
            return checkbox.checked;
    }
    else if (control && (control.tagName.toLowerCase() == 'input') && (control.type == 'checkbox'))
    {
        return control.checked;
    }
    else if (control && (control.tagName.toLowerCase() == 'input'))
    {
        return control.value;
    }
}

function isCheckBoxControl(control)
{
    return control && (typeof (control.tagName) != 'undefined')
        && (control.tagName.toLowerCase() == 'input')
        && (control.type.toLowerCase() == 'checkbox');
}

function getInnerCheckBoxSpanControl(control)
{
    if (control)
    {
        var inputs = control.getElementsByTagName('input');
        if (isCheckBoxControl(inputs[0]))
            return inputs[0];
    }
    return null;
}

function attributeEligibleOnChangeResponse(xhr, labelPriceIDList, labelWeightIDList,
    labelStorageIDList)
{
    if (xhr && (xhr.status == 200) && xhr.responseText && (xhr.responseText != ''))
    {
        var values = xhr.responseText.split('/t');
        if (values.length && values.length >= 1)
        {
            //Update prices
            if (values.length && values.length >= 2)
            {
                var labelPriceID = labelPriceIDList.split(';');
                for (var i = 0; i < labelPriceID.length; i++)
                    attributeEligibleSetPriceValue(labelPriceID[i], values[0], values[1])
            }

            //Update weights
            if (values.length && values.length >= 3)
                attributeEligibleSetWeightValue(values[2]);

            //Update storages
            if (values.length && values.length >= 4)
                attributeEligibleSetStorageValue(values[3]);
        }
    }
}

function attributeEligibleSetPriceValue(labelValueID, priceValue, previousPriceValue)
{
    var labelValue = document.getElementById(labelValueID);
    var prefix = '';

    if (labelValue)
    {
        if (labelValue.attributes['valuePrefix'])
            prefix = labelValue.attributes['valuePrefix'].value;

        if (labelValue.attributes['isPreviousPriceLabel'])
            labelValue.innerHTML = prefix + previousPriceValue;
        else
            labelValue.innerHTML = prefix + priceValue;
    }
}

function attributeEligibleSetValue(labelValueID, value)
{
    var labelValue = document.getElementById(labelValueID);
    var prefix = '';

    if (labelValue)
    {
        if (labelValue.attributes['valuePrefix'])
            prefix = labelValue.attributes['valuePrefix'].value;

        labelValue.innerHTML = prefix + value;
    }
}

function attributeEligibleSetStorageValue(labelStorageStringList)
{
    //Structure storage list
    var indexControlID = 0;
    var indexControlValue = 1;
    var indexControlFormat = 2;

    var storageCtrlStructList = labelStorageStringList.split(';');
    for (var i = 0; i < storageCtrlStructList.length; i++)
    {
        var storageCtrlStruct = storageCtrlStructList[i].split(':');
        if (storageCtrlStruct.length != 3)
            continue;

        var labelStorage = document.getElementById(storageCtrlStruct[indexControlID]);
        if (!labelStorage)
            continue;

        if ((storageCtrlStruct[indexControlValue] != ''))
        {
            if ((labelStorage.attributes['showAsNumber']) && (labelStorage.attributes['showAsNumber'].value == 't'))
                attributeEligibleSetValue(storageCtrlStruct[indexControlID], storageCtrlStruct[indexControlValue]);
            else if (labelStorage.attributes['textInStock'])
                labelStorage.innerText = labelStorage.attributes['textInStock'].value;
        }
        else
        {
            if (labelStorage.attributes['textOutOfStock'])
                labelStorage.innerHTML = labelStorage.attributes['textOutOfStock'].value;
        }
    }
}

function attributeEligibleSetWeightValue(labelWeightStringList)
{
    //Structure weight list
    var indexControlID = 0;
    var indexControlValue = 1;
    var indexControlFormat = 2;

    var weightCtrlStructList = labelWeightStringList.split(';');
    for (var i = 0; i < weightCtrlStructList.length; i++)
    {
        var weightCtrlStruct = weightCtrlStructList[i].split(':');
        if (weightCtrlStruct.length != 3)
            continue;

        var labelWeight = document.getElementById(weightCtrlStruct[indexControlID]);
        if (!labelWeight)
            continue;

        attributeEligibleSetValue(weightCtrlStruct[indexControlID], weightCtrlStruct[indexControlValue]);
    }
}
