﻿var isIE = false;
var isOpera = false;
var isMozilla = false;
var isSafari = false;
var isKonq = false;
var isIE9 = false;

function CheckBrowserVersion()
{
    sUserAgent = navigator.userAgent;
    isOpera = sUserAgent.indexOf("Opera") > -1;
    isIE = sUserAgent.indexOf("compatible") > -1 &&
         sUserAgent.indexOf("MSIE") > -1 &&
         !isOpera;

    if (isIE)
    {
        var versionIE = getIEVersion();
        isIE9 = (versionIE >= 9.0) && (versionIE < 10.0);
    }
    isKHTML = sUserAgent.indexOf("KHTML") > -1 &&
            sUserAgent.indexOf("AppleWebKit") > -1;
    if (isKHTML)
    {
        isSafari = sUserAgent.indexOf("AppleWebKit") > -1;
        isKonq = sUserAgent.indexOf("Konqueror") > -1;
    }
    isMozilla = sUserAgent.indexOf("Gecko") > -1 &&
              !isKHTML;
}
CheckBrowserVersion();

function getIEVersion()
{
    if (isIE)
    {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            return parseFloat(RegExp.$1);
    }
    return null;
}

function attachEventToElement(eventElement, eventName, eventFunction)
{
    if (isIE)
    {
        eventElement.attachEvent("on" + eventName, eventFunction);
    }
    else
    {
        eventElement.addEventListener(eventName, eventFunction, true);
    }
}

function getDocumentBodyElement()
{
    if (isIE || isMozilla)
    {
        return document.documentElement;
    }
    else if (isOpera)
    {
        return document.body;
    }
    else
    {
        if (document.documentElement)
        {
            return document.documentElement;
        }
        else if (document.body)
        {
            return document.body;
        }
    }
    return null;
}

function getCurrStyle(defObj)
{
    if (defObj)
    {
        if (defObj.currentStyle)
        {
            return defObj.currentStyle;
        }
        else if (window.getComputedStyle)
        {
            return document.defaultView.getComputedStyle(defObj, null);
        }
    }
    return null;
}
function getCurrStyleValue(defObj, IEstyleProp, MozStyleProp)
{
    if (defObj.currentStyle)
    {
        return defObj.currentStyle[IEstyleProp];
    }
    else if (window.getComputedStyle)
    {
        return document.defaultView.getComputedStyle(defObj, null).getPropertyValue(MozStyleProp);
    }
    return null;
}
function getCurrStyleFloat(defObj)
{
    if (defObj)
    {
        if (defObj.currentStyle)
        {
            return defObj.currentStyle.styleFloat;
        }
        else if (window.getComputedStyle)
        {
            return document.defaultView.getComputedStyle(defObj, null).cssFloat;
        }
    }
    return null;
}
function getStyleFloat(defObj)
{
    if (defObj)
    {
        if (defObj.style.styleFloat || (defObj.style.styleFloat == ""))
        {
            return defObj.style.styleFloat;
        }
        else if (defObj.style.cssFloat || (defObj.style.cssFloat == ""))
        {
            return defObj.style.cssFloat;
        }
    }
    return null;
}
function setStyleFloat(defObj, value)
{
    if (defObj)
    {
        if (defObj.style.styleFloat || (defObj.style.styleFloat == ""))
        {
            defObj.style.styleFloat = value;
        }
        else if (defObj.style.cssFloat || (defObj.style.cssFloat == ""))
        {
            defObj.style.cssFloat = value;
        }
    }
}

function getDimensions(defObj)
{
    if (defObj.style.display != 'none' && defObj.style.display != null) // Safari bug
        return { width: defObj.offsetWidth, height: defObj.offsetHeight };

    return { width: defObj.clientWidth, height: defObj.clientHeight };
}


function YesNoCancelMsgBox(question)
{
    if (isIE || window.VBYesNoCancelMsgBox)
    {
        return VBYesNoCancelMsgBox(question);
    }
    else
    {
        return confirm(question) ? 6 : 7;
    }
}

function YesNoMsgBox(question)
{
    if (isIE || window.VBYesNoMsgBox)
    {
        return VBYesNoMsgBox(question);
    }
    else
    {
        return confirm(question) ? 6 : 7;
    }
}

function YesNoWarrningMsgBox(question)
{
    if (isIE || window.VBYesNoWarrningMsgBox)
    {
        return VBYesNoWarrningMsgBox(question);
    }
    else
    {
        return confirm(question) ? 6 : 7;
    }
}

function OKInformationMsgBox(infoText)
{
    if (isIE || window.VBOKInformationMsgBox)
    {
        VBOKInformationMsgBox(infoText);
    }
    else
    {
        alert(infoText);
    }
}

function isLeftButtonClick(ev)
{
    if (isIE && !isIE9)
    {
        return ev.button == 1;
    }
    else
    {
        return ev.button == 0;
    }
}

function isRightButtonClick(ev)
{
    return ev.button == 2;
}

function IsAppPath(path)
{
    return window.location.href.substr(0, window.location.href.length - 'default.aspx'.length) == file.href;
}

function GetRelativePath(path)
{
    prefix = window.location.href.substr(0, location.href.length - location.pathname.length - location.search.length);
    if (path.indexOf(prefix) >= 0)
    {
        return path.substr(prefix.length, path.length - prefix.length);
    }
    else
    {
        return path;
    }
}

function GetRelativeExtensionPath(path)
{
    if (path == null || path == '')
        return null;

    if (path.indexOf('//') == -1)
        return path;

    path = path.substr(path.indexOf('//') + 2);
    if (path.indexOf('/') != 0)
        path = path.substr(path.indexOf('/'));
    return path;
}

function RefreshLabel4Disable(controlID, isFormDisabled)
{
    // its necessary to refresh label because on show property page
    // (disable current page) label duplicate text
    control = document.getElementById(controlID);
    if (control)
    {
        if (isFormDisabled)
        {
            control.style.visibility = 'visible';
        }
        else
        {
            control.style.visibility = '';
        }
    }
}

function SetSelectControlsVisible(parentControl, value)
{
    // value - 'hidden', 'visible'
    for (var i = 0; i < parentControl.childNodes.length; i++)
    {
        if (parentControl.childNodes[i].tagName &&
	       (parentControl.childNodes[i].tagName.toLowerCase() == 'select'))
        {
            parentControl.childNodes[i].style.visibility = value;
        }
        SetSelectControlsVisible(parentControl.childNodes[i], value);
    }
}
function HideSelectControls(parentControlID)
{
    parentControl = document.getElementById(parentControlID);
    if (parentControl)
    {
        SetSelectControlsVisible(parentControl, 'hidden');
    }
}
function ShowSelectControls(parentControlID)
{
    parentControl = document.getElementById(parentControlID);
    if (parentControl)
    {
        SetSelectControlsVisible(parentControl, 'visible');
    }
}

function ConvertStringToBool(strValue)
{
    if (strValue && (strValue == 't'))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function setDiabledAllElements(parentElement, isDisabled)
{
    if ((parentElement.disabled != null) &&
      (parentElement.disabled != undefined))
    {
        parentElement.disabled = isDisabled;
    }
    if (parentElement.childNodes)
    {
        for (var i = 0; i < parentElement.childNodes.length; i++)
        {
            setDiabledAllElements(parentElement.childNodes[i], isDisabled)
        }
    }
}

function ToggleAdvancedSearch(panelID, categoriesID, brandsID, inStockID)
{
    var panel = document.getElementById(panelID);
    var categoriesDrop = document.getElementById(categoriesID);
    var brandsDrop = document.getElementById(brandsID);
    var inStockCheck = document.getElementById(inStockID);
    if (panel)
    {
        if (isControlVisible(panel)) // hide + reset filters
        {
            panel.style.display = 'none';
            if (categoriesDrop)
                categoriesDrop.selectedIndex = 0;
            if (brandsDrop)
                brandsDrop.selectedIndex = 0;
            if (inStockCheck)
                inStockCheck.checked = false;
        }
        else // show
        {
            panel.style.display = 'block';
        }
    }
    return false;
}

function ToggleControlVisiblity(controlID)
{
    var control = document.getElementById(controlID);
    if (control)
    {
        control.style.display = isControlVisible(control) ? 'none' : 'block';
    }
    return false;
}

function isControlVisible(control)
{
    if (control.style.display == 'none')
        return false;
    else
        return true;
}

function setControlVisible(control, visible)
{
    control.style.display = visible ? 'block' : 'none';
}

// workaround for radio buttons in repeater
function SetUniqueRadioButton(nameregex, current)
{
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++)
    {
        elm = document.forms[0].elements[i];
        if (elm.type == 'radio')
        {
            if (re.test(elm.name))
            {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}

function CountLeftChars(textBox, infoLabelID)
{
    var infoLabel = document.getElementById(infoLabelID);

    if ((textBox == null) || (infoLabel == null))
        return;

    var maxChars = getMaxCount(textBox);
    var leftChars = maxChars - textBox.value.length;
    if (leftChars > 0)
    {
        infoLabel.className = 'AddCMSSysPropertyLeftInfoLabel';
    }
    else
    {
        infoLabel.className = 'AddCMSSysPropertyToLongInfoLabel';
        leftChars = 0;
    }
    infoLabel.innerHTML = GetResourceText('PropertyInfoCharsLeft', leftChars);
}

function CountLeftWords(textBox, infoLabelID)
{
    var infoLabel = document.getElementById(infoLabelID);

    if ((textBox == null) || (infoLabel == null))
        return;


    var wordsCount = 0;
    if (textBox.value.length > 0)
    {
        var wordsArr = textBox.value.split(', ');
        wordsCount = textBox.value.split(', ').length;
    }

    var maxWords = getMaxCount(textBox);
    var leftWords = maxWords - wordsCount;
    if (leftWords > 0)
    {
        infoLabel.className = 'AddCMSSysPropertyLeftInfoLabel';
    }
    else
    {
        infoLabel.className = 'AddCMSSysPropertyToLongInfoLabel';
        leftWords = 0;
    }
    infoLabel.innerHTML = GetResourceText('PropertyInfoWordsLeft', leftWords);
}

function getMaxCount(textBox)
{
    var maxWordsStr = textBox.getAttribute('maxCount');
    if (maxWordsStr)
        return parseInt(maxWordsStr);
    else
        return 10;
}

function deleteTagFromPage(item, tagID, fieldIDs)
{
    item.style.display = 'none';

    if (fieldIDs.value != '')
        fieldIDs.value = fieldIDs.value + ',';

    fieldIDs.value = fieldIDs.value + tagID;
}

function WebForm_FireDefaultButton(event, target)
{
    if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea")))
    {
        var defaultButton;
        defaultButton = document.getElementById(target);
        if (defaultButton && typeof (defaultButton.click) != "undefined")
        {
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation)
                event.stopPropagation();
            return false;
        }
    }
    return true;
}

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';
        /*imputControlDim.height = 0 in calendar.aspx*/
        //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();
}

// functions for priority drop downs

function priorityDropDownChange(dropDown, textBoxID)
{
    var textBox = document.getElementById(textBoxID);
    if (dropDown && textBox)
        setPriorityTextBoxVisible(textBox, dropDown);
}

function setPriorityTextBoxVisible(textBox, dropDown)
{
    if (!textBox || !dropDown)
        return;

    if ((dropDown.selectedIndex >= 0)
        && ((dropDown.options[dropDown.selectedIndex].value.toLowerCase() == 'user')
            || (dropDown.options[dropDown.selectedIndex].value.toLowerCase() == '-2')))
    {
        setControlVisible(textBox, true);
    }
    else
    {
        if (dropDown.selectedIndex >= 0)
            textBox.value = dropDown.options[dropDown.selectedIndex].text;
        else
            textBox.value = '';
        setControlVisible(textBox, false);
    }
}

function getCheckBox(sender)
{
    var innerCheck = null;
    if (sender.tagName.toLowerCase() == 'input')
    {
        innerCheck = sender;
    }
    else
    {
        var innerChecksArr = sender.getElementsByTagName('input');
        if (innerChecksArr != null && innerChecksArr.length > 0)
            innerCheck = innerChecksArr[0];
    }
    return innerCheck;
}

function removeTagForm(textbox)
{
    if (textbox.value != '')
        textbox.value = textbox.value.replace(/(<form[^\>]*\>)([\s\S]*)(\<\/form\>)/i, "$2");
}

function rewriteIdentifierAutofill(identifierTextBox, nameTextBox)
{
    if (nameTextBox && identifierTextBox)
    {
        var str = nameTextBox.value || '';
        //        var regEx = /\s+/g;
        //        str = str.replace(regEx, '-');
        identifierTextBox.value = getUrlAutofill(str);
    }
}

function rewriteTitleMenuAutofill(titleMenuTextBox, nameTextBox)
{
    if (nameTextBox && titleMenuTextBox)
    {
        var str = nameTextBox.value || '';
        titleMenuTextBox.value = str;
    }
}

function getUrlAutofill(value)
{
    if (value)
    {
        var regEx = /\s+/g;
        value = value.replace(regEx, '-');
        // remove special chars
        value = value.replace(/\?+/g, '');
        value = value.replace(/\&+/g, '');
        value = value.replace(/\#+/g, '');
        value = value.replace(/\*+/g, '');
        value = value.replace(/\\+/g, '');
        value = value.replace(/\/+/g, '');
        value = value.replace(/\:+/g, '');
        value = value.replace(/\<+/g, '');
        value = value.replace(/\>+/g, '');
        value = value.replace(/\|+/g, '');
        value = value.replace(/\++/g, '');
        value = value.replace(/\%+/g, '');
        value = value.replace(/\"+/g, '');
        return value;
    }
    return '';
}

function amountCrossTableCompare(cobminationID, disponible, stock, order)
{
    var errorBox = document.getElementById("ErrorBox");

    if (order > disponible)
    {
        if (amountCrossTableIsErrosSpanExists(cobminationID))
        {
            return;
        }
        else
        {
            var errorTextSpan = document.createElement('span');
            errorTextSpan.setAttribute('id', cobminationID);
            errorTextSpan.setAttribute('class', 'errorTextLabel');
            errorTextSpan.innerHTML = "Nie da rady ziomuś";
            errorBox.appendChild(errorTextSpan);
        }

    }
}

function amountCrossTableIsErrosSpanExists(id)
{
    if (document.getElementById(id) == null)
        return false;
    else
        return true;
}

// itemsIDArray - arrays of IDs elements to hide / show
// next = 1 (show next item) or -1 (show prev item)
function ChangeVisibleItemToNext(objectGalleryID, step)
{
    var gallery = document.getElementById(objectGalleryID);
    if (gallery == null)
        return;

    var imgIndex = gallery.attributes['img_index'].value;
    if (imgIndex != null)
        imgIndex = parseInt(imgIndex);
    else
        imgIndex = 0;
        
    var imgCount = 0;
    var imgArray = new Array();
    for (var i = 0; gallery.childNodes.length > i; i++)
    {
        if (gallery.childNodes[i].className == undefined)
            continue;
        
        if (gallery.childNodes[i].className.indexOf('AddCMSSysUserImageGalleryImageContener') != -1)
        {
            imgArray[imgCount] = gallery.childNodes[i];
            imgCount = imgCount + 1;
         }
     }

     if ((step > 0) && (imgCount - 1 <= imgIndex))
         imgIndex = 0;
     else if ((step < 0) && (imgIndex <= 0))
         imgIndex = imgCount - 1;
     else
         imgIndex = imgIndex + step;

     for (var i = 0; imgArray.length > i; i++)
     {
         imgArray[i].className = 'AddCMSSysUserImageGalleryImageContener';
         if (i != imgIndex)
             imgArray[i].className += ', AddCMSSysUserImageGalleryImageContenerHidden';
     }

     gallery.attributes['img_index'].value = imgIndex;
}

function IsNullOrEmptyOrUndefinied(value)
{
    return (typeof(value) == "undefined") || (value == null) || (value.toString() == '');
}

function GetValue(value)
{
    return IsNullOrEmptyOrUndefinied(value) ? '' : value;
}

function FindByID(arrayToCheck, id)
{
    for (var index = arrayToCheck.length; --index >= 0; )
    {
        if (arrayToCheck[index]['ID'] == id)
        {
            return arrayToCheck[index];
        }
    }
    return null;
}

function SetTextInSpanByArray(elementAndDataPairsArray)
{
    for (var i = elementAndDataPairsArray.length; --i >= 0; )
    {
        if (IsNullOrEmptyOrUndefinied(elementAndDataPairsArray[i][0]))
        {
            continue;
        }
        
        var elem = document.getElementById(elementAndDataPairsArray[i][0]);
        if (elem == null)
        {
            continue;
        }
        
        elem.innerHTML = GetValue(elementAndDataPairsArray[i][1]);
    }
}

function GetHttpAbsAddress(address)
{
    address = GetValue(address);
    if (address.length == 0)
    {
        return '';
    }
    
    var httpPrefix = 'http://';
    
    if ((address.length < httpPrefix.length) || (address.substr(0, httpPrefix.length).toLowerCase() != httpPrefix))
    {
        return httpPrefix + address;
    }

    return address;
}
