var popUpWin = 0;

function popUpWindow() {
    var args = popUpWindow.arguments;
    var width = ',width=' + ((args.length >= 3) ? args[2] : 650);
    var height = ',height=' + ((args.length >= 4) ? args[3] : 480);
    var resizable = ',resizable=' + ((args.length >= 5) ? args[4] : 1);
    var toolbar = ',toolbar=' + ((args.length >= 6) ? args[5] : 1);
    popUpWin = open(args[0], 'popUpWin', 'location=0,directories=0,status=0,scrollbars=1' + width + height + resizable + toolbar);
    popUpWin.focus();
    return args[1];
}

function findObj(theObj, theDoc) {
    var p, i, foundObj;

    if (!theDoc) theDoc = document;
    if ((p = theObj.indexOf("?")) > 0 && parent.frames.length) {
        theDoc = parent.frames[theObj.substring(p + 1)].document;
        theObj = theObj.substring(0, p);
    }
    if (!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
    for (i = 0; !foundObj && i < theDoc.forms.length; i++)
        foundObj = theDoc.forms[i][theObj];
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
        foundObj = findObj(theObj, theDoc.layers[i].document);
    if (!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

    return foundObj;
}

function doAction(butt) {
    var f = document.forms['mainform'];
    f.action.value = butt.value;
    //    document.getElementsByName('action')[0].value = butt.value;
    f.submit();
}

function doActionName(form, actionName) {
    form.action.value = actionName;
    form.submit();
}

function doActionNameVal(form, actionName) {
    if (validar()) {
        form.action.value = actionName;
        form.submit();
    }
}

function doDelete(butt, action) {
    if (action != null && action != '') {
        if (confirm('¿Desea eliminar los elementos seleccionados?')) doActionName(document.forms['mainform'], action);
    }
    else {
        if (confirm('¿Desea eliminar los elementos seleccionados?')) doAction(butt);
    }
}

function seleccionarCheck(chk, nameCh) {
    var arrChecks = document.getElementsByName(nameCh);
    for (var i = 0; i < arrChecks.length; i++) {
        arrChecks[i].checked = chk.checked;
        arrChecks[i].click();
        arrChecks[i].click();
    }
}

function seleccionarFilas(chk, nameHidden) {
    var hiddList = document.getElementsByName(nameHidden);
    if (chk.checked) {
        hiddList[chk.value].value = "S";
    } else {
        hiddList[chk.value].value = "N";
    }
}

// Para trabajo con combos
function addComboOption(combo, value, text, sel) {
    var oOption = document.createElement("OPTION");
    combo.options.add(oOption);
    var oTextNode = document.createTextNode(text);
    oOption.appendChild(oTextNode);
    oOption.value = value;
    if (sel) oOption.setAttribute("selected", "true");
}
function addEmptyOption(combo, sel) {
    addComboOption(combo, "", "", sel);
}
function clearCombo(combo) {
    while (combo.options.length > 0) combo.removeChild(combo.options[0]);
}

function fieldFocus(el, str) {
    if (el != null && el.value == str) {
        el.value = '';
        el.className = 'form_field';
    }
}
function fieldBlur(el, str) {
    if (el != null && el.value == '') {
        el.value = str;
        el.className = 'field_inactive';
    }
}


// Abre la ventana de reenviar password
var wndPwd = null;
function forgetPassword() {
    if (wndPwd != null)
    if (!wndPwd.closed) wndPwd.close();

    var url = "forget-password-popup.do";
    wndPwd = window.open(url, 'wndPwd', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=no,resizable=no,copyhistory=0,width=482,height=400');
    wndPwd.focus();
}


// Abre la pagina para imprimir una orden
var wndOrder = null;
function printOrder(id) {
    if (wndOrder != null)
    if (!wndOrder.closed) wndOrder.close();

    url = "/print-order.do?id=" + id;
    wndOrder = window.open(url, 'wndOrder', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=540');
    wndOrder.focus();
}


// Abre la pagina para mandar un comentario
function newComment() {
    url = "/mycomment.do?rnd="+Math.random();
    // load remote content
    $('#dialog').load(url,{},function (responseText, textStatus, XMLHttpRequest) {
                $('#dialog').dialog('option','width',500);
                $('#dialog').dialog('option','title','Escriba su Comentario');
                $('#dialog').dialog('option', 'buttons', { "Cerrar": function() {$(this).dialog("close");},"Enviar": enviarComentario });
                $('#dialog').dialog('open');
            });
}

// Abre la pagina con la informacion del codigo promocional
var wndProm = null;
function promotionCodeInfo() {
    if (wndProm != null)
    if (!wndProm.closed) wndProm.close();

    url = "/winpopup.do?fn=promotional.code.info";
    wndProm = window.open(url, 'wndProm', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=no,copyhistory=0,width=600,height=440');
    wndProm.focus();
}

var wndZoom = null;
function showBigImage(id, color) {
    //   alert(1);
    if (wndZoom != null)
    if (!wndZoom.closed) wndZoom.close();
    url = "/zoomimg.do?id=" + id;
    if (color != null) url += "&color=" + color;
    wndZoom = window.open(url, 'wndZoom', 'toolbar=yes,location=0,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes,copyhistory=0,width=445,height=490');
    wndZoom.focus();

}

var wndMer = null;
function openMerchant(o, m) {
    if (wndMer != null)
    if (!wndMer.closed) wndMer.close();

    url = "/merchant-form.do?o=" + o;
    if (m != null) url += "&merchant=" + m;
    wndMer = window.open(url, 'wndMer', 'toolbar=no,location=0,directories=no,status=yes,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=750,height=580');
    wndMer.focus();

    document.getElementById("tini").style.display = 'none';
    document.getElementById("tfin").style.display = 'block';
}

function showCalendarRange(nombre, index, dateRange) {
    campos = document.getElementsByName(nombre);
    if (dateRange != null && dateRange != '') {
        gfPop.fPopCalendar(campos[index], dateRange);
    } else {
        hoy = new Date();
        bd = [hoy.getFullYear(),hoy.getMonth() + 1,hoy.getDate()];
        d = new Date(hoy.getFullYear() + 2, hoy.getMonth(), hoy.getDate());
        ed = [d.getFullYear(),d.getMonth() + 1,d.getDate()];
        dateRange = [bd, ed];

        gfPop.fPopCalendar(campos[index], dateRange);
    }
    return false;
}

function showCalendar(nombre, index, dateRange, weekDays) {
    campos = document.getElementsByName(nombre);
    gfPop.fPopCalendar(campos[index], dateRange, weekDays);
    return false;
}

// Abre la pagina con informacion sobre el ip
var wndIP = null;
function showIpInfo(ip) {
    if (wndIP != null)
    if (!wndIP.closed) wndIP.close();

    // url = "http://www.who.is/whois-ip/ip-address/"+ip+"/";
    //  url = "http://www.dnsstuff.com/tools/city.ch?ip="+ip;
    url = "http://www.geobytes.com/IpLocator.htm?GetLocation&ipaddress=" + ip;
    wndIP = window.open(url, 'wndIP', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=600,height=540');
    wndIP.focus();
}

// Abre la pagina con informacion sobre el usuario
var wndUsr = null;
function showUserInfo(id) {
    if (wndUsr != null)
    if (!wndUsr.closed) wndUsr.close();

    url = "userdata.do?id=" + id;
    wndUsr = window.open(url, 'wndUsr', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=600');
    wndUsr.focus();
}

var wndCaixa = null;
function showCaixaInfo(id) {
    if (wndCaixa != null)
    if (!wndCaixa.closed) wndCaixa.close();

    url = "caixarep.do?action=infoForOrder&idorder=" + id;
    wndCaixa = window.open(url, 'wndCaixa', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=500');
    wndCaixa.focus();
}

function createIFrame(n, url, ol) {
    ifrm = document.createElement("IFRAME");
    ifrm.setAttribute("id", n);
    ifrm.setAttribute("name", n);
    ifrm.setAttribute("onload", ol);
    ifrm.setAttribute("src", url);
    ifrm.style.width = 140 + "px";
    ifrm.style.height = 140 + "px";
    document.body.appendChild(ifrm);
}

function validaTextSize(obj, s) {
    if (obj.value.length > s) {
        alert('Solo se permiten ' + s + ' caracteres.');
        obj.value = obj.value.substr(0, s);
        obj.focus();
    }
}

// Abre la pagina con informacion sobre el usuario
var wndTeq = null;
function showStatic(id, link) {
    if (wndTeq != null)
    if (!wndTeq.closed) wndTeq.close();

    url = "/modalsupport.do?fn=" + id;
    if (link != null && link != '') url += "#" + link;
    wndTeq = window.open(url, 'wndTeq', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=500');
    wndTeq.focus();
}

// Abre la pagina para pasar un mensaje a la sesion del usuario
var wndMsg = null;
function sessionMsg(id) {
    if (wndMsg != null)
    if (!wndMsg.closed) wndMsg.close();

    url = "sessionmsg.do?sid=" + id;
    wndMsg = window.open(url, 'wndMsg', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=no,copyhistory=0,width=500,height=300');
    wndMsg.focus();
}


var wndCat = null;
function modalSelectCategory(idField, nameField, selected, multiple) {
    if (wndCat != null)
    if (!wndCat.closed) wndCat.close();

    var url = "categoryman.do?action=showmodal";
    url += "&idField=" + idField;
    url += "&nameField=" + nameField;
    if (selected != null && selected != '') url += "&selected=" + selected;
    if (multiple != null) url += "&multiple=" + multiple;

    wndCat = window.open(url, 'wndCat', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=no,resizable=no,copyhistory=0,width=400,height=500');
    wndCat.focus();
}

// Abre la pagina para pasar un email
var wndEmail = null;
function sendEmail(t, s, b) {
    if (wndEmail != null)
    if (!wndEmail.closed) wndEmail.close();

    url = "sendemail.do?p=0";
    if (t != null && t != '') url += "&to=" + t;
    if (s != null && s != '') url += "&subject=" + s;
    if (b != null && b != '') url += "&body=" + b;
    wndEmail = window.open(url, 'wndEmail', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=no,copyhistory=0,width=500,height=400');
    wndEmail.focus();
}

var wndCel = null;
function recargaDeCelular() {
    if (wndCel != null)
    if (!wndCel.closed) wndCel.close();
    url = "/recargarmovil.do";
    wndCel = window.open(url, 'wndCel', 'toolbar=no,location=0,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=600');
    wndCel.focus();
}

var wndSp = null;
function openSpecialCateg(d, c, s, idCarr, tit) {
    if (wndSp != null)
    if (!wndSp.closed) wndSp.close();
    url = "/specialorder.do?action=show";
    if (d != null && d != '') url += "&departamentId=" + d;
    if (c != null && c != '') url += "&categoryId=" + c;
    if (s != null && s != '') url += "&subcategoryId=" + s;
    if (idCarr != null && idCarr != '') url += "&carrierId=" + idCarr;
    if (tit != null && tit != '') url += "&title=" + tit;
    wndSp = window.open(url, 'wndSp', 'toolbar=1,location=1,directories=no,status=no,menubar=1,scrollbars=yes,resizable=yes,copyhistory=0,width=900,height=500');
    wndSp.focus();
}

var wndRm = null;
function openRemesas() {
    if (wndRm != null)
    if (!wndRm.closed) wndRm.close();
    url = "/remesas.do?action=show";
    wndRm = window.open(url, 'wndRm', 'toolbar=1,location=1,directories=no,status=no,menubar=1,scrollbars=yes,resizable=yes,copyhistory=0,width=600,height=500');
    wndRm.focus();
}


function showGalery(id, name, lang) {
    var url = "http://www.caribeinsider.com/_galerias/_mallhabana/photos.jsp?&key=" + id;
    url += "&lang=" + lang;
    url += "&name=" + name;
    var wndAlb = window.open(url, 'wndAlb', 'toolbar=yes,location=1,directories=no,status=no,menubar=1,scrollbars=yes,resizable=yes,copyhistory=0,width=700,height=500');
    wndAlb.focus();
}


function isValidEmail(strEmail) {
    validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
    return strEmail.search(validRegExp) != -1;
}

function copyToClipboard(inElement) {
    if (document.all) {
        var range = document.body.createTextRange();
        range.moveToElementText(inElement);
        range.execCommand('Copy');
    } else {
        var flashcopier = 'flashcopier';
        if (!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var tagPref = '<' + inElement.tagName + '>';
        var tagSuff = '</' + inElement.tagName + '>';
        var divinfo = '<embed src="../_clipboard.swf" FlashVars="clipboard=' + tagPref + escape(inElement.innerHTML) + tagSuff + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

var ajax = true;
function comprar(index) {
    if (window.ajax) {
        addProductToCart(index);
    } else {
        document.mainform.elem.value = index;
        document.mainform.action.value = 'update';
        document.mainform.submit();
    }
}

function addHomeProductToCart(index) {
    var arrIdProd = document.getElementsByName('id_product');
    var arrCant = document.getElementsByName('cantidad');
    if (index < arrIdProd.length && index < arrCant.length) {
        var idProd = arrIdProd[index].value;
        var cant = arrCant[index].value;
        if (eval(cant) > 0) {
            var btn = $('#button_' + index);
            btn.html('');

            jQuery.getJSON("/department.do", {action:'ajaxUpdate',idProduct:idProd,cantidad:cant,rnd:Math.random()}, function(data) {
                if (data.result == 'ok') {
                    btn.html('<a href="/shopping-cart.do" class="css-button button_buy_short"/>');
                    updateShopCartTotal();
                }
                if (data.result == 'fail') {
                    if (data.error != '') alert(data.error);
                }
            });
        }
    }
}

function addProductToCart(index) {
    var arrIdProd = document.getElementsByName('id_product');
    var arrCant = document.getElementsByName('cantidad');
    if (index < arrIdProd.length && index < arrCant.length) {
        var idProd = arrIdProd[index].value;
        var cant = arrCant[index].value;
        if (eval(cant) > 0) {
            $('#divProdInfo' + idProd).hide();
            $('#divProdWait' + idProd).show();
            $('#divProdAdded').hide();

            jQuery.getJSON("/department.do", {action:'ajaxUpdate',idProduct:idProd,cantidad:cant,rnd:Math.random()}, function(data) {
                $('#divProdInfo' + data.id).show();
                $('#divProdWait' + data.id).hide();
                $('#divErrors').html('');
                if (data.result == 'ok') {
                    $('#divProdAdded').show();
                    $('#numCartProds' + data.id).html(data.msg);
                    updateShopCartTotal();
                } else if (data.result == 'fail') {
                    $('#divProdAdded').hide();
                    $('#divErrors').html(data.error);
                    if (data.error != '') alert(data.error);
                }
            });
        }
    }
}

function updateShopCartTotal() {
    var url = "/ajax-utils.do?action=getShopTotal";
    $('#spanShopCartTotal').html("<img src='/images/site/es/shopload.gif' alt='Cargando...' />");
    $('#spanShopCartTotal').load(url, {rnd:Math.random()}, function() {
        $('span.shopping-cart-price').priceTable({focusBkg:'',focusBrd:'', hintAlign:'right', classname:'hint-sc',
            onSizeWidth:function() {
                return $('#spanShopCartTotal').width() + 12;
            },
            onPosLeft:function() {
                return $('#spanShopCartTotal').offset().left;
            }
        });
    });
}

function listCategory(dep, cat, subcat) {
    var url;
    if (document.getElementById('div_maincontent') != null && false) {
        url = "department.do?fwd=ajax";
        url += "&id=" + dep;
        if (cat != null && cat != '') url += "&categ=" + cat;
        if (subcat != null && subcat != '') url += "&subcateg=" + subcat;
        url += "&rnd=" + Math.random();
        $('#div_maincontent').load(url);
    } else {
        url = "department.do";
        url += "?id=" + dep;
        if (cat != null && cat != '') url += "&categ=" + cat;
        if (subcat != null && subcat != '') url += "&subcateg=" + subcat;
        document.location.href = url;
    }
}

function listDepByCode(code, fwd, ajaxv) {
    var url;
    if (document.getElementById('div_maincontent') != null && false) {
        url = "department.do?rnd=" + Math.random();
        url += "&depcode=" + code;
        if (fwd != null && fwd != '') url += "&fwd=" + fwd;
        $('#div_maincontent').load(url);
    } else {
        url = "department.do";
        url += "?depcode=" + code;
        if (ajaxv != null && ajaxv != '') url += "&detailview=" + ajaxv;
        document.location.href = url;
    }
}

function loading(elId) {
    $('#' + elId).html('<div style="background-image: url(../../images/admin/autocomplete_spinner.gif);background-repeat: no-repeat;background-position: 6px center;padding: 4px 4px 4px 24px;background-color:White;font-size:10pt;font-weight:lighter;color:black;">Cargando.....</div>');
}

function cleanField(fn) {
    var fldArr = document.getElementsByName(fn);
    if (fldArr != null && fldArr.length > 0) {
        var i;
        for (i = 0; i < fldArr.length; i++) fldArr[i].value = '';
    }
}

function showDialog(elId, title, w, h) {
    if (title != null && title != '') {
        $('#dialog-title').html(title);
        $('#dialog-title').show();
    }
    else $('#dialog-title').hide();
    $('#dialog-content').html($('#' + elId));
    if (w != null) $('#dialog').width(w);
    if (h != null) $('#dialog').height(h);
    var ll = $(window).scrollLeft() + parseInt(($(window).width() - w) / 2);
    $('#dialog').css('left', parseInt(ll) + 'px');
    h = $('#dialog').height();
    if (h < 1) h = 200;
    var tt = $(window).scrollTop() + parseInt(($(window).height() - h) / 2);
    $('#dialog').css('top', tt + 'px');
    $('#overlay_dialog').width($(document).width());
    $('#overlay_dialog').height($(document).height());
    $('#overlay_dialog').show();
    return false;
}
function showDialogAjax(url, title, w, h) {
    if (title != null && title != '') {
        $('#dialog-title').html(title);
        $('#dialog-title').show();
    }
    else $('#dialog-title').hide();
    loading('dialog-content');
    if (w != null) $('#dialog').css('width', w + 'px');
    if (h != null) $('#dialog').css('height', h + 'px');
    var ll = $(window).scrollLeft() + parseInt(($(window).width() - w) / 2);
    $('#dialog').css('left', parseInt(ll) + 'px');
    h = $('#dialog').height();
    if (h < 1) h = 200;
    var tt = $(window).scrollTop() + parseInt(($(window).height() - h) / 2);
    $('#dialog').css('top', tt + 'px');
    $('#overlay_dialog').width($(document).width());
    $('#overlay_dialog').height($(document).height());
    $('#overlay_dialog').show();
    $('#dialog-content').load(url);
    return false;
}

function hideDialog() {
    $('#overlay_dialog').hide();
    return false;
}
