﻿function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function addUnLoadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != 'function') {
        window.onunload = func;
    }
    else {
        window.onunload = function() {
            if (oldonunload) {
                oldonunload();
            }
            func();
        }
    }
}

function addCart(pid, variant1, variant2, addCartUrl) {
    var variant1Ddl = document.getElementById(variant1);
    var variant2Ddl = document.getElementById(variant2);
    var url = addCartUrl + '?PrdID=' + pid;

    if (variant1Ddl) {
        url += '&v1=' + variant1Ddl.selectedIndex;
    }

    if (variant2Ddl) {
        url += '&v2=' + variant2Ddl.selectedIndex;
    }

    document.location.href = url;

}

function changePrice(numVariants, variantPrefix, priceControl, basePrice) {
    var spnPrice = document.getElementById(priceControl);
    if (spnPrice) {
        var value = parseFloat(basePrice);
        var variant;

        for (i = 1; i <= numVariants; i++) {
            variant = document.getElementById(variantPrefix + i);
            if (variant) {
                value += parseFloat(variant.options[variant.selectedIndex].value);
            }
        }
        
        var formattedValue = formatNumber(parseFloat(value), 2);
        spnPrice.innerHTML = (formattedValue.replace('.', ',') + ' &euro;');
    }
}

function formatNumber(pnumber, decimals) {
    if (isNaN(pnumber)) { return 0 };
    if (pnumber == '') { return 0 };

    var snum = new String(pnumber);
    var sec = snum.split('.');
    var whole = parseFloat(sec[0]);
    var result = '';

    if (sec.length > 1) {
        var dec = new String(sec[1]);
        dec = String(parseFloat(sec[1]) / Math.pow(10, (dec.length - decimals)));
        dec = String(whole + Math.round(parseFloat(dec)) / Math.pow(10, decimals));
        var dot = dec.indexOf('.');
        if (dot == -1) {
            dec += '.';
            dot = dec.indexOf('.');
        }
        while (dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    } else {
        var dot;
        var dec = new String(whole);
        dec += '.';
        dot = dec.indexOf('.');
        while (dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    }
    return result;
}

function showModalWindow(text) {

    var yOffset;
    var xOffset = 0;
    if (self.pageYOffset) {
        // all except Explorer
        xSize = self.innerWidth;
        yOffset = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        // Explorer 6 Strict
        xSize = document.documentElement.clientWidth;
        yOffset = document.documentElement.scrollTop;
        xOffset = 100;
    }
    else if (document.body) {
        // all other Explorers
        xSize = document.body.clientWidth;
        yOffset = document.body.scrollTop;
        xOffset = 100;
    }

    var top = ((screen.availHeight / 2) + yOffset) - 200 + 'px';

    var modal = document.getElementById('divMessageBox');
    //modal.style.left = screen.availWidth / 2 - 150 + 'px';
    modal.style.left = xSize / 2 - 150 + 'px';
    modal.style.top = top;

    modal.innerHTML = text;
    $('divMessageBox').appear({ duration: 0.2 });

}

function hideDiv(divID) {
    var div = document.getElementById(divID);
    if (div) {
        div.style.visibility = 'hidden';
    }
}

function hideShowDivs(show, hide)
{
    if (show != '' && hide != '')
    {
        var showDiv = document.getElementById(show);
        
        var divs = hide.split('|');
        for (i = 0; i < divs.length; i++)
        {
            document.getElementById(divs[i]).style.display = 'none';
        }
        
        showDiv.style.display = 'block';
    }
}

function toggleDiv(chk, target)
{
    var div = document.getElementById(target);
    
    if (div)
    {
        if (chk.checked)
        {
            div.style.display = 'block';
        }
        else
        {
            div.style.display = 'none';
        }
    }
}

function chkboxMaster(chk, prefix)
{

    var arrChk = document.getElementsByName(prefix);
    
    for (i = 0; i < arrChk.length; i++)
    {
        arrChk[i].checked = chk.checked;
    }

}

function setFocus(control, color)
{
    control.style.backgroundColor = '#' + color;
}

function replaceInnerHTML(target, content)
{
    var control = document.getElementById(target);
    control.innerHTML = content;
}

function appendInnerHTML(target, content)
{
    var control = document.getElementById(target);
    control.innerHTML = control.innerHTML + content;
}

function setControlValue(target, value)
{
    var control = document.getElementById(target);
    control.value = value;
}

function getControlValue(target)
{
    var control = document.getElementById(target);
    return control.value;
}

function showControl(target)
{
    var loading = document.getElementById(target);
    loading.style.display = 'block';
}

function hideControl(target)
{
    var loading = document.getElementById(target);
    loading.style.display = 'none';
}

function changeBgColor(target, color, cursor)
{
    target.style.backgroundColor = color;
}

function copyFormFields(checkbox, fields)
{
    for (pairIndex in fields.split(';'))
    {
        var origin = document.getElementById(fields.split(";")[pairIndex].split(',')[0])
        var destination = document.getElementById(fields.split(";")[pairIndex].split(',')[1])
        
        if (checkbox.checked)
        {
            if (origin.tagName == 'INPUT' || origin.tagName == 'TEXTAREA')
            {
                destination.value = origin.value;
            }
            else if (origin.tagName == 'SELECT')
            {
                destination.selectedIndex = origin.selectedIndex;
            }
            
            destination.disabled = true;
        }
        else
        {
            if (origin.tagName == 'INPUT' || origin.tagName == 'TEXTAREA')
            {
                destination.value = '';
            }
            else if (origin.tagName == 'SELECT')
            {
                destination.selectedIndex = 0;
            }
            
            destination.disabled = false;
        }
        
    }

    //var control = document.getElementById(fields);
    //alert(control.tagName);
}

var numbersonly = "()- 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";

function res(control)
{
    control.value = control.value.replace(/([^0-9])/g,"");
}

function vbv(root)
{
    var wWidth = 330;
    var wHeight = 300;
    var wTop = (screen.availHeight - wHeight) / 2
    var wLeft = (screen.availWidth - wWidth) / 2
    var vbvWindow = window.open(root + '/vbv.aspx', 'vbv', 'width=' + wWidth + ',height=' + wHeight + ',top=' + wTop + ',left=' + wLeft);
}

function cvv(root)
{
    var wWidth = 400;
    var wHeight = 380;
    var wTop = (screen.availHeight - wHeight) / 2
    var wLeft = (screen.availWidth - wWidth) / 2
    var vbvWindow = window.open(root + '/cvv.aspx', 'cvv', 'width=' + wWidth + ',height=' + wHeight + ',top=' + wTop + ',left=' + wLeft);
}
        
function ddlNavigate(url, parameter, control)
{
    if (control.options[control.selectedIndex].value != '')
    {
        document.location.href = url + '?' + parameter + '=' + control.options[control.selectedIndex].value;
    }
}

function rollOver(imageID, imageURL)
{
    var image = document.getElementById(imageID);
    image.src = imageURL;
}

function showThumb(imageControl, thumbURL)
{
    var image = document.getElementById(imageControl);
    if(image)
    {
        image.src = thumbURL;
    }
}

function showImage(productID, imageURL)
{
    window.open('/galeria.aspx?pid=' + productID + '&img=' + imageURL , 'galeria', 'toolbar = no, location = no, menubar = no, scrollbars = yes');
}

/***** RATE *****/
function rateChange(rate, imagePrefix)
{
    for(i = 1; i <= 5; i++)
    {
        var imageType = 0;
        if(i <= rate)
        {
            imageType = 1;
        }
        document.getElementById(imagePrefix + i).src = '../img/rate' + imageType + '.gif';
    }
}

function rateProduct(sid, pid, rate)
{
    document.getElementById('divRateFeedback').innerHTML = '<span style="font-size:9px; color: #909090; font-style: oblique;">A gravar classificação...</span>'
    callAjax('../ajax/rateProduct.aspx?sid=' + sid + '&pid=' + pid + '&rate=' + rate, 'divRateFeedback')
}
/***** RATE *****/

function setContent(control, text, replacer, color)
{
    if(control.value == text)
    {
        control.style.color = color;
        control.value = replacer;
    }
}

function openPopup(url, name, width, height)
{
    var left = (screen.availWidth / 2) - (width / 2);
    var top = (screen.availHeight / 2) - (height / 2);
    
    window.open(url, name, 'width=' + width + ', height=' + height + ', top=' + top + ', left=' + left + ', scrollbars=no, resizable=no');
}

function recomendar(pid, ctrlNome, ctrlEmail, ignoraNome, ignoraEmail, canal)
{
    var nome = document.getElementById(ctrlNome).value;
    var email = document.getElementById(ctrlEmail).value;
    
    if (nome == ignoraNome)
    {
        nome = '';
    }
    
    if (email == ignoraEmail)
    {
        email = '';
    }
    
    openPopup('/recomendar.aspx?pid=' + pid + '&nome=' + nome + '&email=' + email + '&canal=' + canal, 'recomendar', 400, 350);
}

/***** Verificação de entrada de apenas caracteres específicos ******/
function res(control)
{
    control.value = control.value.replace(/([^0-9])/g,"");
}

function preventEnter()
{
    return !(window.event && window.event.keyCode == 13);
}

function closeOrder()
{
    return confirm('De certeza que deseja fechar a encomenda?\nSe o fizer não poderá mais alterar o estado dos produtos nem da encomenda.');
}

function checkQuickSearch(e, dropDownID, searchPage)
{
    if(typeof event!= 'undefined')
    {
        var pressedkey = window.event.keyCode;
    }
    else
    {
        var pressedkey = e.charCode;
        if (pressedkey == 0)
        {
            pressedkey = e.keyCode;
        }
    }

    if (pressedkey == 13)
    {
        doQuickSearch(dropDownID, searchPage);
        return false;
    }
}

function doQuickSearch(dropDownID, searchPage)
{
    var search = document.getElementById('txtQuickSearch');
    var dropDown = document.getElementById(dropDownID);
    
    if (search && search.value != '')
    {
        document.location.href = searchPage + '?s=1&k=' + search.value + '&CatID=' + dropDown.options[dropDown.selectedIndex].value;
    }
}

function displayCTT(control) {
    var div = document.getElementById('divCTT');
    div.style.display = (control.options[control.selectedIndex].value == 1) ? 'block' : 'none';
}

function displayFromAddress(control) {
    var div = document.getElementById('divMoradaRementente');
    div.style.display = (control.options[control.selectedIndex].value == 1) ? 'block' : 'none';
}