﻿var ie = navigator.appName.indexOf('Microsoft') != -1;

function newWin(nazwa, szer, wys) {
    odlewa = (screen.width - szer) / 2;
    odgory = (screen.height - wys) / 2;
    szer = szer + 28;
    wys = wys + 28;
    config = 'left=' + odlewa + ',top=' + odgory + ',width=' + szer + ',height=' + wys + ',innerheight=' + wys + ',innerwidth=' + szer + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no';
    cel = window.open('', 'okno', config)
    cel.document.write('<HTML><HEAD>');
    cel.document.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
    cel.document.write('<TITLE></title>');
    cel.document.write('</HEAD>');
    cel.document.write('<body  leftmargin=10 topmargin=14 marginheight=10 marginwidth=10  style="background-image: url(/gfx/baccara.gif);background-position: center center; background-repeat: no-repeat; text-align:center;">');
    cel.document.write('<a href=# onclick="javascript:self.close();"><img src=' + nazwa + ' class=obw alt="Kliknij aby zamknąć okno" style="border: 1px solid #000;" align=center></a>');
    cel.document.write('</body></html>');
    cel.focus();
}

function newhtm(nazwa, szer, wys, scroll) {
    odlewa = (screen.width - szer) / 2;
    odgory = (screen.height - wys) / 2;
    if (!scroll)
        scroll = 'no';
    config = 'left=' + odlewa + ',top=' + odgory + ',width=' + szer + ',height=' + wys + ',innerheight=' + wys + ',innerwidth=' + szer + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=yes';
    pralines = window.open(nazwa, 'okno', config)
    pralines.focus();
}

function openNewWindow(fileName, windowName, windowHeight, windowWidth, input) {
    email = input.form.email.value;
    popup = window.open(fileName + "?email=" + email, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2));
    return false;
}

function openNewBlankWindow(fileName, windowName, windowHeight, windowWidth, setId) {
    popup = window.open(fileName + "?setId=" + setId, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2));
}

/* passes parameters inside order form */
/*	param1 - imie i nazwisko
param2 - nazwa firmy
param3 - ulica z numerem
param4 - kod pocztowy
param5 - miasto
param6 - panstwo
*/
function passParams(param1, param2, param3, param4, param5, param6, param7) {
    document.getElementById('prop\(_delivery_name\)').value = param1;
    document.getElementById('prop\(_delivery_companyName\)').value = param2;
    document.getElementById('prop\(_delivery_street\)').value = param3;
    document.getElementById('prop\(_delivery_postcode\)').value = param4;
    document.getElementById('prop\(_delivery_city\)').value = param5;
    document.getElementById('prop\(_delivery_country\)').value = param6;
    document.getElementById('prop\(delivery_phone\)').value = param7;
}

function waitAndForward(seconds) {
    setTimeout('window.location="/Home"', seconds);
}

function changeElementDisplay(elementName) {
    document.getElementById(elementName).className = switchStyleClasses(document.getElementById(elementName).className, 'hide', 'show');
}
function swapDisplay(elementId) {
    var el = document.getElementById(elementId);
    if (!el)
        return;
    if (el.style.display != 'none')
        el.style.display = 'none';
    else {
        el.style.display = (el.tagName.toLowerCase() == 'tbody') ? 'table-row-group' : 'block';
    }
}
function setDisplay(elementId, show) {
    var e = document.getElementById(elementId);
    if (!e)
        return;
    e.style.display = show ? ((e.tagName.toLowerCase() == 'tbody') ? (ie ? 'table-header-group' : 'table-row-group') : 'block') : 'none';
}
function switchStyleClasses(actualClassName, firstClass, secondClass) {
    var classes = new Array();
    classes = actualClassName.split(' ');
    for (var i = 0; i < classes.length; i++) {
        if (classes[i] == firstClass)
            classes[i] = secondClass;
        else {
            if (classes[i] == secondClass)
                classes[i] = firstClass;
        }
    }

    var newClassName = '';
    for (var i = 0; i < classes.length; i++) {
        if (i == classes.length - 1)
            newClassName += classes[i];
        else
            newClassName += classes[i] + ' ';
    }

    return newClassName;
}

function toTop() {
    window.scroll(0, 0);
}

/*
This function generates list of objects's values that were selected by user (using
checkboxes). As a list separator is used given sequenceSeparator.
*/
function generateObjectsSequence(objectsName, sequenceSeparator) {
    var objects = new Array();

    for (var i = 0; i < document.getElementsByName(objectsName).length; i++) {
        if (document.getElementsByName(objectsName)[i].checked == true)
            objects[objects.length] = document.getElementsByName(objectsName)[i].value;
    }

    if (objects.length > 0) {
        var objectsSequence = '';
        for (var i = 0; i < objects.length; i++) {
            objectsSequence += objects[i];
            if ((i + 1) < objects.length)
                objectsSequence += sequenceSeparator;
        }
        return objectsSequence;
    }
    return '';
}

function openNewWindow(fileName, windowName, windowHeight, windowWidth, parameter) {
    popup = window.open(shopBase + fileName, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2) + ', scrollbars = yes');
    popup.param = parameter;
}

function openNewParameterWindow(fileName, windowName, windowWidth, windowHeight, parameter) {
    popup = window.open(shopBase + fileName, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (
screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2) + ', scrollbars = no');
    popup.t = parameter;
}

function openNewParamWindow(fileName, windowName, windowWidth, windowHeight, parameter) {
    popup = window.open(shopBase + fileName + '?param=' + parameter, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2) + ', scrollbars = no');
}

function submitForm(form) {
    var form = document.getElementById(form);

    try {
        form.submit();
    } catch (err) {
        alert("Wybrany obiekt nie jest formularzem.");
    }
}

function onlyDigits(e) {
    var key;
    var keychar;
   
    if (window.event)
        key = window.event.keyCode;       
    else if (e)
        key = e.which;
    else
        return true;

    if (key > 95 && key < 106)
        return true;

    if (key > 47 && key < 58)
        return true;
    
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27) )
        return true;
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;
    else
        return false;
}

/* 
Shows or hides additional layer with basic cart information. 
*/
function showCart() {
    var hiddenCart = document.getElementById("hiddenCart");

    if (hiddenCart.style.display == "none")
        hiddenCart.style.display = "block";
    else
        hiddenCart.style.display = "none";
}

function linkWindow(fileName, windowName, windowHeight, windowWidth) {
    popup = window.open(shopBase + fileName, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2) + ', scrollbars = yes');
}

function initSelects() {
    var sSelects = document.getElementsByName('sOffset');
    for (var i = 0; i < sSelects[0].options.length; i++) {
        if (sSelects[0].options[i].value == document.getElementsByName('offset')[0].value) {
            for (var j = 0; j < sSelects.length; j++)
                sSelects[j].selectedIndex = i;
            return;
        }
    }
}

function submitCategoryPaging(selectNo) {
    var sSelects = document.getElementsByName('sOffset');
    document.getElementsByName('offset')[0].value = sSelects[selectNo].options[sSelects[selectNo].selectedIndex].value;
    document.categoryForm.submit();
}

function submitSearchPaging(selectNo) {
    var sSelects = document.getElementsByName('sOffset');
    document.getElementsByName('offset')[0].value = sSelects[selectNo].options[sSelects[selectNo].selectedIndex].value;
    document.getElementById('searchPaging').submit();
}

function showProducerCategories(selectedIndex) {
    var tbody = 'categoriesForProducer';
    var producers = document.getElementById('producers');
    var value = producers.options[producers.selectedIndex].value;

    /* ukrycie i wyzerowanie nieużywanych selectów */
    for (i = 0; i < document.getElementsByName(tbody).length; i++) {
        if (document.getElementsByName(tbody)[i].className != 'hide') {
            document.getElementsByName('temp')[i].selectedIndex = 0;
            document.getElementsByName(tbody)[i].className = switchStyleClasses(document.getElementsByName(tbody)[i].className, 'hide', 'show');
        }
    }

    /* przywrócenie głównej kategorii */
    if (selectedIndex == 0) {
        document.getElementById('mainCategoryTree').className = switchStyleClasses(document.getElementById('mainCategoryTree').className, 'hide', 'show');
        return;
    }

    /* ustawienie kategorii jesli zostala wybrana */
    if (document.getElementById(value).className == 'hide')
        document.getElementById(value).className = switchStyleClasses(document.getElementById(value).className, 'hide', 'show');
}

function setChosenCategoryId() {
    var categoryId = '';
    for (i = 0; i < document.getElementsByName('temp').length; i++) {
        if ((select = document.getElementsByName('temp')[i]).selectedIndex > 0)
            categoryId = select.options[select.selectedIndex].value;
    }
    document.getElementById('propertyToSet').value = categoryId;
}

function submitProducerItemSearch(categoryId) {
    document.getElementById('producerItemSearch').submit();
}

function toggleProducers() {
    var p = document.getElementById('prod_div');
    var l = document.getElementById('prod_link');

    if (p.style.display == 'none') {
        p.style.display = 'block';
        l.className = 'rollOff';
    } else {
        p.style.display = 'none';
        l.className = 'rollOn';
    }
}

function submitFilterForm(producerId, producerSymbol, requestUrl) {

    document.getElementById('fProducerId').value = producerId;

    if (requestUrl.indexOf('index.jsp') != -1) {
        if (producerSymbol != '')
            document.getElementById('fReferer').value = document.getElementById('fReferer').value + producerSymbol;
        else
            document.getElementById('fReferer').value = '';
    } else {
        if (requestUrl.indexOf('search') != -1) {
            if (producerSymbol != '')
                document.getElementById('fReferer').value = requestUrl + '?producerId=' + producerId;
            else
                document.getElementById('fReferer').value = '';
        } else {
            if (requestUrl.indexOf('producer') != -1) {
                if (producerSymbol != '')
                    document.getElementById('fReferer').value = document.getElementById('fReferer').value + producerSymbol;
                else
                    document.getElementById('fReferer').value = '';
            } else {
                document.getElementById('fReferer').value = requestUrl;
                document.getElementById('fSymbol').value = producerSymbol;
            }
        }

    }

    document.getElementById('filterForm').submit();
}

function refreshCart(price, id) {
    var src = document.getElementsByName('quantities[' + id + ']')[0];
    var target = document.getElementById('cartItemValue[' + id + ']');

    var sum = Math.round(src.value * price * 100.00) / 100.00;
    target.innerHTML = sum.toFixed(2);

    var sum = 0;
    var amounts = document.getElementsByName('cartItemValue');

    for (var i = 0; i < amounts.length; i++)
        sum += Math.round(amounts[i].innerHTML * 100) / 100;

    document.getElementById('cartSum').innerHTML = sum.toFixed(2);
}

function cartInc(field) {
    var value = parseInt(document.getElementById(field).value);
    if (typeof value == "number")
        value++;
    document.getElementById(field).value = value;
}

function cartDec(field) {
    var value = parseInt(document.getElementById(field).value);
    if (typeof value == "number" && value > 0)
        value--;
    document.getElementById(field).value = value;
}

function toggleImage(c, pl, bl) {
    var color = nopl(c);
    var popup = document.getElementById('popupImage');
    var big = document.getElementById('bigImage');

    bl = bl.substring(0, bl.lastIndexOf('.')) + '_' + color + bl.substring(bl.lastIndexOf('.'), bl.length);
    big.src = bl;

    pl = pl.substring(0, pl.lastIndexOf('.')) + '_' + color + pl.substring(pl.lastIndexOf('.'), pl.length);
    popup.href = 'javascript:Popup("' + pl + '");';
}

function nopl(s) {
    var polish = "ąćęłńóśźż";
    var nonPolish = "acelnoszz";

    for (var i = 0; i < polish.length; i++)
        s = replace(s, polish.charAt(i), nonPolish.charAt(i));

    return s;
}

function replace(s, arg0, arg1) {
    for (var i = 0; i < s.length; i++)
        if (s.charAt(i) == arg0)
        s = s.substring(0, i) + arg1 + s.substring(i + 1, s.length);

    return s;
}

function hideEmpty(arg0, name) {
    var objName = 's' + name;
    if (arg0 == null || arg0.length == 0)
        document.getElementById(objName).style.display = 'none';
}

/*********** UNIVERSAL ROLLING MECHANISM ***********/
/* 
This is basic representation of roll mechanism single item. It
does not contain launching image (it's launched with basic HTML
link).
*/
function rmItem(layerId) {
    this.layerId = layerId;
    this.imageId = null;
    this.imageOn = null;
    this.imageOff = null;

    var currentDisplay = document.getElementById(layerId).style.display;
    if (currentDisply != 'none') {
        this.state = true;
        this.orgDisplay = currentDisplay;
    } else {
        this.state = false;
        this.orgDisplay = 'inline';
    }
}

/*
This is representation of roll mechanism single item.
Parameters:
layerId - id of layer that is to be rolled;
imageId - id of image that is rolling mechanism launcher;
imageOn - path of an image that is shown when layer is HIDDEN;
imageOff - path of an image that is shown when layer is VISIBLE;
*/
function rmItem(layerId, imageId, imageOn, imageOff) {
    this.layerId = layerId;
    this.imageId = imageId;
    this.imageOn = imageOn;
    this.imageOff = imageOff;

    var currentDisplay = document.getElementById(layerId).style.display;
    if (currentDisplay != 'none') {
        this.state = true;
        this.orgDisplay = currentDisplay;
    } else {
        this.state = false;
        this.orgDisplay = 'inline';
        // TODO: how to solve it? what display should be set? block? inline? or maybe default for given object type?
    }
}

/*
This is initialization of roll mechanism.
*/
function rmInit() {
    rmArray = new Array();
}

/*
This function adds rmItem to rmArray.
*/
function rmAdd(layerId) {
    var item = new rmItem(layerId);
    rmArray[rmArray.length] = item;
}

/*
This function adds rmItem with it's launching image set to rmArray.
*/
function rmAdd(layerId, imageId, imageOn, imageOff) {
    var item = new rmItem(layerId, imageId, imageOn, imageOff);
    rmArray[rmArray.length] = item;
}

/*
This function returns rmItem with given layerId from rmArray.
*/
function rmGet(layerId) {
    for (i = 0; i < rmArray.length; i++) {
        if (rmArray[i].layerId == layerId)
            return rmArray[i];
    }
}

/*
This function changes state of given layer to opposite one.
*/
function rmChangeState(layerId) {
    for (i = 0; i < rmArray.length; i++) {
        if (rmArray[i].layerId == layerId) {
            if (rmArray[i].state == true)
                rmArray[i].state = false;
            else
                rmArray[i].state = true;
        }
    }
}

/*
This function executes rolling mechanism on given layer. It also
switches image that represents roll mechanism launcher.
*/
function rmExecute(layerId) {
    var item = rmGet(layerId);
    if (item != null) {
        if (item.state == true) {
            document.getElementById(item.layerId).style.display = 'none';
            if (item.imageId != null)
                document.getElementById(item.imageId).src = item.imageOn;
            rmChangeState(item.layerId);
        } else {
            document.getElementById(item.layerId).style.display = item.orgDisplay;
            if (item.imageId != null)
                document.getElementById(item.imageId).src = item.imageOff;
            rmChangeState(item.layerId);
        }
    }
}

function submitCartForm(itemSymbol) {
    if (document.getElementById(itemSymbol + 'quantity').value != 1)
        document.getElementById('quantity').value = document.getElementById(itemSymbol + 'quantity').value;
    document.getElementById('itemSymbol').value = itemSymbol;
    if (document.getElementById(itemSymbol + 'colors') != null)
        document.getElementById('itemColor').value = document.getElementById(itemSymbol + 'colors').options[document.getElementById(itemSymbol + 'colors').options.selectedIndex].value;
    document.getElementById('addToCart').submit();
}

function changeProducer() {
    var producersList = document.getElementById('producersList').options;
    var selIndex = producersList.selectedIndex;
    var symbol = producersList[selIndex].value;
    if (symbol != '')
        document.location = '/do/producer?symbol=' + symbol;
}

function switchPopup(id) {
    var eth = document.getElementsByTagName('span');
    for (var i = 0; i < eth.length; i++) {
        if (eth[i].className == 'elementsToHide')
            eth[i].style.display = 'none';
    }
    document.getElementById('popup' + id).style.display = 'inline';
}

function submitAddOpinion(itemId) {
    document.getElementById('itemId').value = itemId;
    document.getElementById('addOpinionForm').submit();
}

function filterByProducer(selIndex) {
    var producers = document.getElementById('producers').options;
    var producer = document.getElementById('producerToFilter');
    producer.value = producers[selIndex].value;
    document.getElementById('categoryFilterForm').submit();
}

function priceNegotiationSubmit() {
    document.priceNegotiationForm.submit();
}

function showOrderEditor(orderCartItemId) {
    var qv = document.getElementById('qv' + orderCartItemId);
    var qe = document.getElementById('qe' + orderCartItemId);

    if (qv.style.display == 'none') {
        qe.style.display = 'none';
        qv.style.display = 'inline';
    } else {
        qe.style.display = 'inline';
        qv.style.display = 'none';
    }
}

function submitOrderChanges(orderId, orderCartItemId) {
    document.getElementById('orderId').value = orderId;
    document.getElementById('orderCartItemId').value = orderCartItemId;
    document.getElementById('orderCartItemQuantity').value = document.getElementById('q' + orderCartItemId).value;
    document.getElementById('orderModifyForm').submit();
}

function submitCategoryForProducerForm(categoryId) {
    document.getElementById('c').value = categoryId;
    document.getElementById('categoryForProducerForm').submit();
}

function toggle(big, popup) {
    var toggle = document.getElementById("toggle");

    var link = document.createElement("a");
    link.setAttribute("href", "javascript:popup('" + popup + "')");

    var image = document.createElement("img");
    image.setAttribute("src", big);

    link.appendChild(image);

    toggle.replaceChild(link, toggle.firstChild);
}

function popup(nazwa) {
    Popup(nazwa);
}

function setForgottenPassword(customersLogin, customersEmail) {
    var login = document.getElementById(customersLogin);
    var email = document.getElementById(customersEmail);

    if (login == null || email == null)
        return false;

    email.value = login.value;

    return true;
}
/* 
New version of Popup. It does not load forever and may contain title for an image.
*/
function Popup(file, subtitle) {
    iNewWindow(file, 0, 0, subtitle);
}

function iNewWindow(file, windowWidth, windowHeight, subtitle) {
    var sizes = false;

    if (windowHeight > 0) {
        sizes = true;
        windowWidth = windowWidth + 28;
        windowHeight = windowHeight + 28;
        var fromLeft = (screen.width - windowWidth) / 2;
        var fromTop = (screen.height - windowHeight) / 2;
    } else {
        windowWidth = 800;
        windowHeight = 600;
        fromLeft = (screen.width) / 4;
        fromTop = (screen.height) / 4;
    }

    base = document.getElementsByTagName("base")[0];
    if (base)
        baseurl = base.href;
    else
        baseurl = null;

    config = "left = " + fromLeft + ", top = " + fromTop + ", width = " + windowWidth + ", height = " + windowHeight + ", innerheight = " + windowHeight + ", innerwidth = " + windowWidth + ", toolbar = no, location = no, directories = no, status = no, menubar = no, resizable = yes, scrollbars = yes";

    target = window.open("", "popuped", config);
    target.document.writeln('<html><head>');

    if (baseurl)
        target.document.writeln('<base href="' + baseurl + '" />');

    /* somehow it doesn't work...
    target.document.writeln('<link rel="stylesheet" href="' + baseurl + 'css/main.css" type="text/css" />');
    */
    target.document.writeln('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />');
    target.document.writeln('<title>' + document.title + '</title>');

    if (!sizes) {
        target.document.writeln('<script type="text/javascript">');
        target.document.writeln('var temp = self.location.href.split("?");');
        target.document.writeln('var picUrl = (temp.length > 1) ? temp[1] : "";');
        target.document.writeln('var NS = (navigator.appName == "Netscape") ? true : false;');
        target.document.writeln('function fitPic() {');
        target.document.writeln('iImg1 = document.getElementById("img1");');
        target.document.writeln('iWidth = (NS) ? window.innerWidth : document.body.clientWidth;');
        target.document.writeln('iHeight = (NS)? window.innerHeight : document.body.clientHeight;');
        target.document.writeln('if (iImg1.width > 800) iWidth = 640 - iWidth; else {iWidth = iImg1.width + 32 - iWidth;}');
        target.document.writeln('if (iImg1.height > 600) iHeight = 600 - iHeight; else {iHeight = iImg1.height + 32 - iHeight;}');
        target.document.writeln('window.resizeBy(iWidth, iHeight-1);');
        target.document.writeln('self.focus();');
        target.document.writeln('};');
        target.document.writeln('function setTitle() {');
        target.document.writeln('self.document.title = top.opener.document.title;');
        target.document.writeln('};');
        target.document.writeln('function myurlencode(string) {');
        target.document.writeln('return escape(string).replace(/[+]/g, "%2B");');
        target.document.writeln('}');
        target.document.writeln('function setPosition() {');
        target.document.writeln('var img = document.getElementById("img1");');
        target.document.writeln('window.moveTo((screen.width - img.width) / 2, (screen.height - img.height) / 2);');
        target.document.writeln('}');
        target.document.writeln('</script>');
    }

    target.document.writeln('</head>');
    target.document.writeln('<body id="imagepopup">');
    target.document.write('<table style="width: 100%; height: 100%;"><tr><td style="text-align: center; vertical-align: middle;"><a href="javascript:self.close();"><img src="');
    target.document.write(file.replace(/[#]/g, "%23"));
    target.document.write('" id="img1" class="obw" alt="Kliknij, aby zamkn?? okno..." style="border: 1px solid #000;" onload="javascript:fitPic();"></a></td></tr></table>');

    if (subtitle)
        target.document.writeln('<div id="subtitle">' + subtitle + '</div>');

    if (!sizes) {
        target.document.writeln('<script language="javascript" type="text/javascript">');
        target.document.writeln('	setTitle();');
        target.document.writeln('</script>');
    }

    target.document.writeln('<script type="text/javascript">');
    target.document.writeln('setPosition();');
    target.document.writeln('</script>');
    target.document.writeln('</body>');
    target.document.writeln('</html>');
    target.document.close();

    target.focus();
}
