var _ecAjaxDebug = false;
var _ecAjaxBuffer = false;
var _ecCurBlock = false;
var _ecFCKLoaded = false;
var _ecOrdersTimeout = false;
var _ecVisitesTimeout = false;
var _ecProductsBuffer = new Array();
var _ecProductsVariationsBuffer = new Array();
var _ecChartOrders = false;
var _ecChartVisites = false;

/* ajax general */
function ecommerce_ajaxView(objDest, strAction, strIdFieldName, strId, strBlock, fnCallBack, blnCustom) {
    //empty, loading
    if (!$(objDest).html()) {
        $(objDest).html("<p style='height:50px;'>&nbsp;</p>");
    }

    $(objDest).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    //load view
    var ajaxUrl = "action=" + (blnCustom ? "ajax/admin/" : "modules/ecommerce/ajax/admin/") + strAction + "&commandView=1&" + strIdFieldName + "=" + strId + "&block=" + strBlock;

    if (_ecAjaxBuffer) {
        $(objDest).html(_ecAjaxBuffer);
        $(objDest).unblock();

        _ecAjaxBuffer = false;

    } else {
        if (_ecAjaxDebug == true) {
            window.open("ajax.php?" + ajaxUrl);
        } else {
            $.ajax({
                type: "GET",
                url: "ajax.php",
                data: ajaxUrl,
                async: true,
                dataType: "html",
                success: function (data, textStatus) {
                    $(objDest).html(data);
                    $(objDest).unblock();
                    
                    if (fnCallBack) {
                        fnCallBack($(objDest));
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $(objDest).html("");
                    $(objDest).unblock();
                }
            });
        }
    }
}

function ecommerce_ajaxEdit(objDest, strAction, strIdFieldName, strId, strBlock, strParams, fnCallBack, blnCustom) {
    //only one block at same time
    if (_ecAjaxBuffer && _ecCurBlock) {
        ecommerce_ajaxView(_ecCurBlock, false, false, false, false, false);
    }

    //loading
    $(objDest).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '1px solid #999999', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    //load edit
    var ajaxUrl = "action=" + (blnCustom ? "ajax/admin/" : "modules/ecommerce/ajax/admin/") + strAction + "&commandEdit=1&" + strIdFieldName + "=" + strId + "&block=" + strBlock + (strParams ? "&" + strParams : "");

    if (_ecAjaxDebug == true) {
        window.open("ajax.php?" + ajaxUrl);
    } else {
        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: ajaxUrl,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                _ecAjaxBuffer = $(objDest).html();
                _ecCurBlock = objDest;

                $(objDest).html(data);
                $(objDest).unblock();

                if (fnCallBack) {
                    fnCallBack($(objDest));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(objDest).unblock();
            }
        });
    }
}

function ecommerce_ajaxSave(objDest, strAction, strIdFieldName, strId, strBlock, fnCallBack, fnErrorCallBack, blnCustom) {
    //saving
    $(objDest).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Saving' />&nbsp;Saving</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '1px solid #999999', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    //tinyMCE
    if (tinyMCE) {
        tinyMCE.triggerSave();
    }

    //save ajaxFrm
    var ajaxUrl = "action=" + (blnCustom ? "ajax/admin/" : "modules/ecommerce/ajax/admin/") + strAction + "&commandUpdate=1&" + strIdFieldName + "=" + strId + "&block=" + strBlock + "&" + $("#" + strBlock + "Frm").serialize().replace(/%E2%82%AC/g, '%80');

    if (_ecAjaxDebug == true) {
        window.open("ajax.php?" + ajaxUrl);
    } else {
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: ajaxUrl,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                $(objDest).html(data);
                $(objDest).unblock();

                if (!(strAction == "ecommerce_categoriesAdmin" &&  strBlock == "categoriesData") && $(objDest).find("form").length == 0) {
                    var tip = $("<div class='messageOk'>" + $("#ajaxSaveSuccess").html() + "</div>");

                    $(objDest).prepend(tip);
                    tip.fadeOut(4000, function() {
                        tip.remove();
                     });
                }

                _ecAjaxBuffer = false;
                _ecCurBlock = false;

                if (fnCallBack) {
                    fnCallBack($(objDest));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (fnErrorCallBack) {
                    $(objDest).unblock();
                    fnErrorCallBack();
                } else {
                    $(objDest).unblock();
                }
            }
        });
    }
}

function ecommerce_ajaxDelete(strAction, strIdFieldName, strId, strBlock, fnCallBack, blnCustom) {
    var ajaxUrl = "action=" + (blnCustom ? "ajax/admin/" : "modules/ecommerce/ajax/admin/") + strAction + "&commandDelete=1&" + strIdFieldName + "=" + strId + "&block=" + strBlock;

    if (_ecAjaxDebug == true) {
        window.open("ajax.php?" + ajaxUrl);
    } else {
        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: ajaxUrl,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                $.blockUI({ 
                    message: $(data), 
                    css: { top: '15%', opacity: '.9', backgroundColor: '#ffffff', border: '2px solid #999999' },
                    overlayCSS: { backgroundColor: '#666666' }
                });

                if (fnCallBack) {
                    fnCallBack($(objDest));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(objDest).unblock();
            }
        });
    }
}

function ecommerce_ajaxDeleteConfirm(strAction, strIdFieldName, strId, strBlock, fnCallBack, blnCustom) {
    top.location.href = "admin.php?action=" + (blnCustom ? "admin/" : "modules/ecommerce/admin/") + strAction + "&commandDelete=1&" + strIdFieldName + "=" + strId;
}

function ecommerce_deleteObjectImage(oSrc, e) {
    $(oSrc).parents("li").fadeOut(300, function() {
        $(oSrc).parents("li").remove();
     });

    return cancelEvent(e);
}

/* admin general */
function ecommerce_listCheckAll(blnCheck, event) {
    $(".dataTable input[type=checkbox]").each(function (i) {
        $(this).attr("checked", (blnCheck ? "checked" : ""));
    });

    return cancelEvent(event);
}

function ecommerce_listCheckEnsure(strNoSelected, strConfirm, event, bIncludeFirst) {
    var iCount = 0;
    var sConfirm, oOption;
	var bFirst = bIncludeFirst || false;

    $(".dataTable input[type=checkbox]").each(function (i) {
        if (((!bFirst && i > 0) || bFirst) && $(this).attr("checked")) {
            iCount++;
        }
    });

    if (!iCount) {
        alert(strNoSelected);
        return cancelEvent(event);

    } else if (!$("#execAction").val()) {
        return cancelEvent(event);
    } else {
        oOption = $("#execAction").attr("options");
        oOption = oOption[$("#execAction").attr("selectedIndex")];

        sConfirm = strConfirm;
        sConfirm = sConfirm.replace("%1", oOption.text);
        sConfirm = sConfirm.replace("%2", iCount);

        if (oOption.value.substr(-3) != "_NC" && !confirm(sConfirm)) {
            return cancelEvent(event);
        }
    }
}

function ecommerce_deleteImage(sName, txtUpload) {
	$("#" + sName).val("");
	$("#" + sName + "_img").slideUp();
	$("#" + sName + "_delete").hide();
	$("#" + sName + "_upload").val(txtUpload);
}

/* charts */
function renderChart(objChart, strChart, strPeriod, objSrc, event, strGAParams) {
	if (strGAParams) {
		var ajaxUrl = "action=modules/ecommerce/ajax/admin/gaCharts&target=" + strChart + strGAParams;
	} else {
		var ajaxUrl = "action=modules/ecommerce/ajax/admin/charts&target=" + strChart + "&time=" + strPeriod;
	}

    if (objSrc) {
        $(objSrc).parents("ul").children().each(function (i) {
            $(this).attr("className", "");
        });

        $(objSrc).parents("li").attr("className", "selected");
    }

	if (objChart) {
		objChart.destroy();
		objChart = false;
	}

	$("#" + strChart).html("<div class=\"chartLoading\"><img src=\"" + xopieCDN + "images/admin/loading.gif\" alt=\"Loading\" />&nbsp;Loading</div>");

	if (_ecAjaxDebug == true) {
		window.open("ajax.php?" + ajaxUrl);
	} else {
		$.ajax({
			type: "GET",
			url: "ajax.php",
			data: ajaxUrl,
			async: true,
			dataType: "text",
			success: function (data, textStatus) {
				if (data != "error") {
					eval(data);

					objChart = new Highcharts.Chart({
						chart: {
							renderTo: strChart,
							defaultSeriesType: "areaspline"
						},
						plotOptions: {
							areaspline: {
								fillOpacity: 0.5
							}
						},
						title: {
							text: ""
						},
						tooltip: {
							formatter: function() {
								return this.point.name;
							}
						},
						legend: {
							enabled: false
						},
						credits: {
							enabled: false
						},
						xAxis: {
							categories: gaChart.xTitles,
							title: {
								text: ""
							}
						},
						yAxis: {
							title: {
								text: ""
							},
							plotLines: [{
								value: 0,
								width: 1,
								color: '#d8d8d8'
							}],
							allowDecimals: false
						},
						series: [{
							name: strChart,
							data: gaChart.xValues
						}]
					});

					return objChart;
				} else {
					$("#" + strChart).html("<div class=\"chartLoading\"><a href=\"admin.php?action=modules/ecommerce/admin/ecommerce_settingsWebmasters\">Google Analytics authentication error</a></div>");
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {

			}
		});
	}

	if (event) {
		cancelEvent(event);
	}

	return objChart;
}

function togglePeriodTop(strPeriod, objSrc, event) {
    if (objSrc) {
        $(objSrc).parents("ul").children().each(function (i) {
            $(this).attr("className", "");
        });

        $(objSrc).parents("li").attr("className", "selected");
    }

    var ajaxUrl = "action=modules/ecommerce/ajax/admin/top&time=" + strPeriod;

    if (_ecAjaxDebug == true) {
        window.open("ajax.php?" + ajaxUrl);
    } else {
        $("#topStats").block({  
            message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
            css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
            overlayCSS: { backgroundColor: '#ededed' }
        });

        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: ajaxUrl,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                $("#topStats").html(data);
                $("#topStats").unblock();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }

    return (event ? cancelEvent(event) : false);
}

/* categories */
function ecommerce_initTreeCategories(blnInitTree) {
    //optionsMenu
    $("ul#categories li div").each(function (i) {
        var om = $(this).children("span.optionsMenu");
        var to;

        $(this).unbind("mouseover");
        $(this).unbind("mouseout");
        
        $(this).mouseover(function() {
            clearTimeout(to);
            om.css("display", "inline");
        });

        $(this).mouseout(function() {
            to = setTimeout(function() {om.fadeOut(50); }, 50);
        });
    });

    //tree
    $("ul#categories").NestedSortable({
        accept: "page-item1",
        noNestingClass: "no-nesting",
        opacity: 0.7,
        helperclass: "helper",
        onChange: function(serialized) {
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: "action=modules/ecommerce/ajax/admin/ecommerce_categoriesSort&" + serialized[0].hash,
                async: true,
                dataType: "text",
                success: function (data, textStatus) {
                    //none
                }
            });
        },
        onStop: function() {
            $("ul#categories").SortableDestroy();
            ecommerce_initTreeCategories(true);
        },
        autoScroll: true,
        nestingPxSpace: 1,
        handle: ".sort-handle"
    });
}

function ecommerce_addEmbeddedCategory(idCategoryParent, strCurLocale, event) {
    if (idCategoryParent == 0) {
        strDest = "#categoriesData";
    } else {
        strDest = "#categoriesData";
    }

    ecommerce_ajaxEdit(strDest, "ecommerce_categoriesAdmin", "idCategory", "", "categoriesData", "idCategoryParent=" + idCategoryParent + "&mode=embedded", function(objDest) {
        $(objDest).slideDown(500, function() {
            $("#name_" + strCurLocale).focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_showEmbeddedCategory(idCategoryParent, code) {
    var code = $(code);

    if (idCategoryParent) {
        strDest = "#categories";
    } else {
        strDest = "#" + idCategoryParent + " > ul";

        if ($(strDest).attr("tagName") != "UL") {
            $("#" + idCategoryParent).append($("<ul ul class=\"page-list\"></ul>"));
        }
    }

    $(strDest).prepend(code);
    ecommerce_initTreeCategories(false);

    code.effect("pulsate", { times: 2 }, 500);
}

function ecommerce_toggleCategory(objSrc, event) {
    var bShow = true;

    if ($("#productList").attr("id")) {
        if ($("#productList").parent().attr("id") == $(objSrc).parent().parent().attr("id")) {
            bShow = false;
        }

        $("#productList").slideUp(100, function() {
            $("#productList").remove();
        });
    }

    if (bShow) {
        setTimeout(function() {
            $(objSrc).parent().after($("<div id='productList' class='productList'></div>"));
            ecommerce_ajaxView($("#productList"), "ecommerce_categoriesAdmin", "idCategory", $(objSrc).parent().parent().attr("id"), "categoriesProducts", function() {
                $("#productList ul#ec_pl1").sortable({
                    cursor: "move",
                    opacity: 0.6,
                    handle: ".sort_handler",
                    connectWith: ["#ec_pl2"],
                    cursorAt: "top left",
                    placeholder: "helper",
                    update: ecommerce_productsSortCallback
                });

                $("#productList ul#ec_pl2").sortable({
                    cursor: "move",
                    opacity: 0.6,
                    handle: ".sort_handler",
                    connectWith: ["#ec_pl1"],
                    cursorAt: "top left",
                    placeholder: "helper",
                    update: ecommerce_productsSortCallback
                });

                $("#productList").slideDown(100);
            });
        }, 125);
    }

    return (event ? cancelEvent(event) : false);
}

function ecommerce_productsSortCallback(event, ui) {
    var count = 1;

    $("#productList li").each(function(i) {
        $(this).find("span").html(count + ".");
        count++;
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_productsSort&" + $("#productList ul#ec_pl1").sortable("serialize") + "&" +  $("#productList ul#ec_pl2").sortable("serialize"),
        async: true,
        dataType: "text",
        success: function (data, textStatus) {
            //none
        }
    });
}

function ecommerce_setProductCategory(oSrc) {
    if ($("#categoryMode_exists").attr("checked")) {
        $(".addCategory_new").slideUp(200);
    } else {
        $(".addCategory_new").slideDown(200);
        $("#idCategory").val("");
    }
}

function ecommerce_setProductMake(oSrc) {
    if ($("#makeMode_exists").attr("checked")) {
        $(".addMake_new").slideUp(200);
    } else {
        $(".addMake_new").slideDown(200);
        $("#idMake").val("");
    }
}

function ecommerce_toggleAllTags(event) {
    if ($("#allTags").css("display") == "none") {
        $("#allTags").slideDown(300);
    } else {
        $("#allTags").slideUp(300);
    }

    return cancelEvent(event);
}

function ecommerce_addTag(objDest, strTag) {
    if ($(objDest).val().indexOf(strTag + " ") < 0) {
        $(objDest).val($(objDest).val() + strTag + " ");
    }
}

/* clients */
function ecommerce_addClientAddress(event) {
    var oTemplate = $("#addressTemplate");
    var sTemplate = "<tr>" + oTemplate.html() + "</tr>";

    while (sTemplate.indexOf("#row#") > -1) { 
        sTemplate = sTemplate.replace("#row#", oTemplate.siblings().length - 2);
    }

    oTemplate.before($(sTemplate));

    return cancelEvent(event);
}

function ecommerce_deleteClientAddress(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    if (objRow.siblings().length > 2) {
        objRow.fadeOut(300, function() {
            objRow.remove();
        });
    }

    return cancelEvent(event);
}

function ecommerce_ensureDefaultAddress() {
    $("table#clientAddresses [name*=isDefault]").each(function(i) {
        if ($(this).attr("checked")) {
            $("#isDefaultIndex").val(i);
        }
    });
}

/* control ecommerceExceptions */
function ecommerce_changeTable(objSrc) {
    var sId = $(objSrc).attr("id");

    $(objSrc).find("option").each(function() {
        $("#" + sId.replace("ctable", $(this).val() + "_fields")).hide();
    });

    $("#" + sId.replace("ctable", $(objSrc).val() + "_fields")).show();
}

function ecommerce_changeField(objSrc, sPrefix) {
    var sId = $(objSrc).attr("id");
    var sIdInput = sPrefix + "_cvalue";
    var sIdSel = sPrefix + "_cvalue_sel_cnt";

    if ($(objSrc).val() == "country") {
        $("#" + sIdInput).hide();
        $("#" + sIdSel).show();
    } else {
        $("#" + sIdInput).show();
        $("#" + sIdSel).hide();    
    }
}

function ecommerce_changeCountry(objSrc) {
    var sId = $(objSrc).attr("id");
    var sIdInput = sId.replace("_sel", "");

    $("#" + sIdInput).val($(objSrc).val());
}

function ecommerce_addCondition(strId, strBlock, event) {
    var oTemplate = $("#" + strId + "_" + strBlock + "_template");
    var sTemplate = "<div class='condition'>" + oTemplate.html() + "</div>";

    while (sTemplate.indexOf("#cond#") > -1) { 
        sTemplate = sTemplate.replace("#cond#", oTemplate.siblings().length - 3);
    }
//[]Comprobar que id no ocupat!!!
    oTemplate.before($(sTemplate));

    return cancelEvent(event);
}

function ecommerce_deleteCondition(objSrc, event) {
    if ($(objSrc).parents("div.exception").children().length > 5) {
        $(objSrc).parents("div.condition").fadeOut(200, function() {
            $(objSrc).parents("div.condition").remove();
        });
    }

    return cancelEvent(event);
}

function ecommerce_addException(strId, event) {
    var oTemplate = $("#" + strId + "_template");
    var sTemplate = "<div class=\"exception\">" + oTemplate.html() + "</div>";

    while (sTemplate.indexOf("#block#") > -1) { 
        sTemplate = sTemplate.replace("#block#", oTemplate.siblings().length);
    }
//[]Comprobar que id no ocupat!!!
    oTemplate.before($(sTemplate));

    return cancelEvent(event);
}

function ecommerce_deleteException(objSrc, event) {
    $(objSrc).parents("div.exception").fadeOut(200, function() {
        $(objSrc).parents("div.exception").remove();
    });

    return cancelEvent(event);
}


/* control ecommerceCountries */
function toggleCountry(objSelect, strProvinceId, blnPersist) {
    objSelect = $(objSelect);

    if (objSelect.val()) {
        var objProvince = $(strProvinceId);
        var strCode = objSelect.children(":selected").attr("rel");
        var blnFound = false;
        var strProvince;

        if (objProvince) {
            strProvince = objProvince.value;

            objProvince.parent().children("select").each(function (i) {
                if ($(this).attr("id") == strCode + "." + objProvince.attr("id")) {
                    $(this).show();
                    blnFound = true;

                    if (blnPersist) {
                        $(this).val(strProvince);
                    } else {
                        $(this).val("");
                    }
                } else {
                    $(this).hide();
                }                    
            });

            if (blnFound) {
                objProvince.hide();
            } else {
                objProvince.show();
            }
        }
    }
}

/* orders */
function ecommerce_toggleOrderStatus(event) {
    $("#order_status").slideToggle(300);

    return cancelEvent(event);
}

function ecommerce_toggleFirstLabel() {
    if ($("#usefirstLabel").attr("checked")) {
        $("#firstLabel_cnt").slideDown(200);
    } else {
        $("#firstLabel_cnt").slideUp(100);
    }
}

function ecommerce_changeOrderStatus(sNewStatus, oldStatus) {
	if (sNewStatus != oldStatus && (sNewStatus == "ECOMMERCE_ORDERS_STATUS_PAID" || sNewStatus == "ECOMMERCE_ORDERS_STATUS_SEND")) {
		$("#cnt_statusNotify").slideDown(300);
	} else {
		$("#cnt_statusNotify").slideUp(200);
	}
}

function ecommerce_changeOrderStatusWManufactured(sNewStatus, oldStatus) {
	if (sNewStatus != oldStatus && (sNewStatus == "ECOMMERCE_ORDERS_STATUS_PAID" || sNewStatus == "ECOMMERCE_ORDERS_STATUS_SEND" || sNewStatus == "ECOMMERCE_ORDERS_STATUS_MANUFACTURED")) {
		$("#cnt_statusNotify").slideDown(300);
	} else {
		$("#cnt_statusNotify").slideUp(200);
	}
}

function ecommerce_changeOrdersAction(strAction) {
	if (strAction) {
		$("#resultsActionsChecks").find("span").each(function(i) {
			if ($(this).attr("class").indexOf(strAction) > -1) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	}
}

/* variations */
function ecommerce_toggleVariation(objChk, intVariationId, blnBuffer) {
    if (!$(objChk).attr("checked")) {
        _ecProductsBuffer[intVariationId] = "";

        $("#variationItems_" + intVariationId).find("tr.sortable").each(function(i) {
            if (blnBuffer) {
                _ecProductsBuffer[intVariationId] += "<tr class='sortable'>" + $(this).html() + "</tr>";
            }

            $(this).remove();
        });

        $("#variationItems_" + intVariationId).find("tr").each(function(i) {
            $(this).hide();
        });

        $("#variationItems_" + intVariationId + "_add").hide();
    } else {
        $("#variationItems_" + intVariationId).find("tr").each(function(i) {
            $(this).show();
        });

        $("#variationItems_" + intVariationId + "_add").show();

        if (_ecProductsBuffer[intVariationId]) {
            $("#variationItems_" + intVariationId + "_template").before(_ecProductsBuffer[intVariationId]);
            $("#variationItems_" + intVariationId + "_template").hide();

            $("#variationItems_" + intVariationId + " tbody").sortable("refresh");

            _ecProductsBuffer[intVariationId] = false;
        } else {
            ecommerce_defaultVariationItems(false, intVariationId, false);
        }
    }
}

function ecommerce_addVariationItem(strTableId, event) {
    var oTemplate = $("#" + strTableId + "_template");
    var sTemplate = "<tr class=\"sortable\">" + oTemplate.html() + "</tr>";

    oTemplate.before($(sTemplate));
    $("#" + strTableId + " tbody").sortable("refresh");

    return cancelEvent(event);
}

function ecommerce_deleteVariationItem(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    if (objRow.siblings().length > 2) {
        objRow.fadeOut(300, function() {
            objRow.remove();
            $("#variationItems tbody").sortable("refresh");
        });
    }

    return cancelEvent(event);
}

function ecommerce_deleteVariationItems(sDivId, event) {
    $("#" + sDivId).fadeOut(300, function() {
        $("#" + sDivId).remove();
    });

    return cancelEvent(event);
}

function ecommerce_defaultVariationItems(strConfirmMsg, intVariationId, event) {
    if (!strConfirmMsg || (strConfirmMsg && confirm(strConfirmMsg))) {
        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: "action=modules/ecommerce/ajax/admin/variationItems&idVariation=" + intVariationId,
            async: true,
            dataType: "text",
            success: function (data, textStatus) {
                $("#variationItems_" + intVariationId).find("tr.sortable").each(function(i) {
                    $(this).remove();
                });

                eval("data=" + data);

                if (data.length) {
                    jQuery.each(data, function(index, item) {
                        ecommerce_addVariationItem("variationItems_" + intVariationId, event);
                        var objRow = $("#variationItems_" + intVariationId).find("tr.sortable:last");

                        jQuery.each(item, function(key, value) {
                            var objInput = objRow.find("[name*=" + key + "]");

                            if (key == "isDefault") {
                                objInput.attr("checked", (value ? "1" : "0"));
                            } else if (key.indexOf("name_") == 0) {
                                objInput = objRow.find("input." + key);
                                objInput.val(value);
                            } else {
                                objInput.val(value);
                            }
                        });
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }

    if (event) {
        return cancelEvent(event);
    }
}

function ecommerce_ensureDefaultVariationItem() {
    $("tr.sortable [name*=isDefault]").each(function(i) {
        if ($(this).attr("checked")) {
            $("#isDefaultIndex").val(i);
        }
    });
}

function ecommerce_ensureMultipleDefaultVariationsItems() {
    $("input[name*=isDefaultIndex_]").each(function(i) {
        hdn = this;

        $("tr.sortable [name*='isDefault[" + this.name.substr(15) + "]']").each(function(j) {
            if ($(this).attr("checked")) {
                $(hdn).val(j);
            }
        });

    });
}

function ecommerce_productAddVariation(oSrc, event) {
    var oTemplate = $("#variation_template");
    var sTemplate = oTemplate.html();
    var sId = 1000;

    while ($(oSrc).parent().find("#variation_ECPNV_" + sId).length > 0) {
        sId++;
    }

    sId = "ECPNV_" + sId;

    while (sTemplate.indexOf("#NEW#") > -1) { 
        sTemplate = sTemplate.replace("#NEW#", sId); 
    } 

    $(oSrc).before($(sTemplate));

    $("#variationItems_" + sId + " tbody").sortable({
        opacity: 0.6,
        handle: ".sort_handler",
        items: "> tr.sortable"
    });

    return cancelEvent(event);
}

function ecommerce_productDeleteVariation(sId, event) {
    $("#" + sId).remove();

    return cancelEvent(event);
}

function ecommerce_productUpdateVariationsConfirm(bHasStocks, sQuestion) {
    var idVariation, bUpdateStocks;

    if (!bHasStocks) {
        return true;
    } else {
        bUpdateStocks = false;

        $("form#productsVariationsFrm input[type=checkbox]").each(function (i) {
            idVariation = ($(this).attr("id") ? $(this).attr("id") : $(this).attr("name")).substr(14);

            if (idVariation != "#NEW#]" && (($(this).attr("checked") && !_ecProductsVariationsBuffer[idVariation]) || (!$(this).attr("checked") && _ecProductsVariationsBuffer[idVariation]))) {
                bUpdateStocks = true;
            }
        });

        if (bUpdateStocks) {
            if (confirm(sQuestion)) {
                $("#updateStocks").val("1");
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}

function ecommerce_productToggleRangsPrices(bShow) {
	if (bShow) {
		$("#rangs_prices_cnt").slideDown(200);

		if (parseFloat($("#rangs_prices_priceFirst").val()) == 0 || isNaN(parseFloat($("#rangs_prices_priceFirst").val()))) {
			$("#rangs_prices_priceFirst").val($("#price").val());
		}

		$("#price_cnt").slideUp(200, function() {
			$("#price_alert_cnt").slideDown(200);
		});
	} else {
		$("#rangs_prices_cnt").slideUp(200);
		$("#price_alert_cnt").slideUp(200, function() {
			$("#price_cnt").slideDown(200);
		});
	}
}

function ecommerce_productCheckRangsIni() {
	var rangsIni = $("input[name*=pricesRangsIni]");
	var rangsEnd = $("input[name*=pricesRangsEnd]");

	for (var i = 1; i < rangsIni.length; i++) {
		if (parseInt(rangsEnd.eq(i - 1).val()) >= parseInt(rangsIni.eq(i).val())) {
			rangsIni.eq(i).val(parseInt(rangsEnd.eq(i - 1).val()) + 1);
		}

		if (rangsIni.eq(i).val() && rangsEnd.eq(i).val() && parseInt(rangsEnd.eq(i).val()) <= parseInt(rangsIni.eq(i).val())) {
			rangsEnd.eq(i).val(parseInt(rangsIni.eq(i).val()) + 1);
		}
	}
}

function ecommerce_productsAddRang(event) {
    $("#rangs_prices_row_last").before("<div class=\"row\">" + $("#rangs_prices_row_template").html() + "</div>");
    return cancelEvent(event);
}

/* banners */
function ecommerce_toggleBannerType(strType) {
	if (strType == "ECOMMERCE_BANNER_TYPE_HTML") {
		$("#nonhtml_cont").slideUp(100);
		$("#html_cont").slideDown(100);
	} else {
		$("#nonhtml_cont").slideDown(100);
		$("#html_cont").slideUp(100);

		if (strType == "ECOMMERCE_BANNER_TYPE_IMAGE") {
			$("#text_cont").slideUp(100);
		} else {
			$("#text_cont").slideDown(200);
		}
	}
}

function ecommerce_writeFlash(sId, sImg, iW, iH) {
	var h = Math.ceil((iH * $("#" + sId).width()) / iW);
	$("#" + sId).flash({
		width: "100%",
		height: h + "px",
		wmode: "transparent",
		src: sImg
	});
}

/* account */
function ecommerce_toggleOrderPaymethod() {
    if ($("#paymethod_INVOICES_PAYMETHOD_CARD").attr("checked")) {
        $("#paymethod_INVOICES_PAYMETHOD_CARD_help:hidden").slideDown(400);
        $("#paymethod_INVOICES_PAYMETHOD_DIRECTBILLING_help:visible").slideUp(100);
    } else {
        $("#paymethod_INVOICES_PAYMETHOD_CARD_help:visible").slideUp(100);
        $("#paymethod_INVOICES_PAYMETHOD_DIRECTBILLING_help:hidden").slideDown(400);
    }
}

function ecommerce_toggleAdyenPaymethod() {
    if ($("#newCard_1").attr("checked")) {
        $("#newCard_1_help").slideDown(400);
        $("#newCard_0_help").slideUp(100);
    } else {
        $("#newCard_1_help").slideUp(100);
        $("#newCard_0_help").slideDown(400);
    }
}

function ecommerce_buyServiceAmounts() {
	var base = parseFloat($("#quota").val() ? $("#" + $("#quota").val()).val() : 0);
	var tax = parseFloat((base / 100) * $("#tax").val());
	var total = base + tax;

	$("#base").html(number_format(base, 2, ",", "."));
	$("#tax_amount").html(number_format(tax, 2, ",", "."));
	$("#total").html(number_format(total, 2, ",", "."));
}

function ecommerce_buyPlanAmounts() {
	var base = parseFloat($("#quota").val() ? $("#" + $("#quota").val()).val() : 0);
	var tax = parseFloat((base / 100) * $("#tax").val());
	var total = base + tax;

	$("#base").html(number_format(base, 2, ",", "."));
	$("#tax_amount").html(number_format(tax, 2, ",", "."));
	$("#total").html(number_format(total, 2, ",", "."));

	$("#totalsBox_priceMonth").hide();
	$("#totalsBox_priceYear").hide();
	$("#totalsBox_" + $("#quota").val()).show();
}

/* taxes */
function ecommerce_addTaxesException(event) {
    var oTemplate = $("#taxesExceptionTemplate");
    var sTemplate = "<tr>" + oTemplate.html() + "</tr>";
	var oLastCty = oTemplate.siblings().eq(oTemplate.siblings().length - 1).find("select[id*=country_]")
	var iNext = parseInt(oLastCty.attr("id").substring(oLastCty.attr("id").indexOf("_") + 1)) + 1;

    while (sTemplate.indexOf("#row#") > -1) { 
        sTemplate = sTemplate.replace("#row#", iNext);
    }

    oTemplate.before($(sTemplate));

    return cancelEvent(event);
}

function ecommerce_deleteTaxesException(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    if (objRow.siblings().length > 2) {
        objRow.fadeOut(300, function() {
            objRow.remove();
        });
    }

    return cancelEvent(event);
}

/* invoices */
function ecommerce_addInvoicesTax(event) {
    var oTemplate = $("#invoicesTaxTemplate");
    var sTemplate = "<tr>" + oTemplate.html() + "</tr>";

    oTemplate.before($(sTemplate));

    return cancelEvent(event);
}

function ecommerce_deleteInvoicesTax(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    if (objRow.siblings().length > 2) {
        objRow.fadeOut(300, function() {
            objRow.remove();
        });
    }

    return cancelEvent(event);
}

function ecommerce_toggleInvoiceType(objSrc, sProforma, event) {
	if ($(objSrc).val() == "ECOMMERCE_INVOICES_TYPE_INVOICE") {
		$("#invoiceNumber").val($("#cur_invoiceNumber").val());
	} else {
		$("#invoiceNumber").val(sProforma);
	}
}

function ecommerce_setInvoiceClient(arrClient, event) {
	$("#clientName").val(arrClient[1]);
	$("#clientId").val(arrClient[0]);
	$("#clientCompany").val(arrClient[2]);
	$("#clientIdentity").val(arrClient[3]);
	$("#clientAddress").val(arrClient[4]);
	$("#clientCp").val(arrClient[5]);
	$("#clientTown").val(arrClient[6]);
	$("#clientProvince").val(arrClient[7]);
	$("#clientCountry").val(arrClient[8]);
	$("#clientEmail").val(arrClient[9]);

    return cancelEvent(event);
}

function ecommerce_addInvoiceDetail(event) {
    var oTemplate = $("#invoicesDetailTemplate");
    var sTemplate = "<tr class=\"detail\">" + oTemplate.html() + "</tr>";

    oTemplate.before($(sTemplate));
	initTextAreas();

    return cancelEvent(event);
}

function ecommerce_deleteInvoiceDetail(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    if (objRow.siblings().length > 2) {
        objRow.fadeOut(300, function() {
            objRow.remove();
        });
    }

    return cancelEvent(event);
}

function ecommerce_updateInvoiceDetail(objRow, event) {
	var quantity = parseInt(objRow.find("input[name^='quantity']").val() ? objRow.find("input[name^='quantity']").val() : 0);
	var priceU = parseFloat(objRow.find("input[name^='priceU']").val() ? objRow.find("input[name^='priceU']").val() : 0);
	var discount = parseFloat(objRow.find("input[name^='discount']").val() ? objRow.find("input[name^='discount']").val() : 0);
	var tax1_sel = objRow.find("select[name^='tax1']").val();
	var tax2_sel = objRow.find("select[name^='tax2']").val();
	var tax1 = 0, tax2 = 0, atax1 = 0, atax2 = 0;
	var subtotal = 0, total = 0;

	if (tax1_sel) {
		objRow.find("input.tax1_name").val(tax1_sel.substring(0, tax1_sel.indexOf("##")));
		objRow.find("input.tax1_percent").val(tax1_sel.substring(tax1_sel.indexOf("##") + 2));
		var tax1 = objRow.find("input.tax1_percent").val();
	} else {
		objRow.find("input.tax1_name").val("");
		objRow.find("input.tax1_percent").val("");
	}

	if (tax2_sel) {
		objRow.find("input.tax2_name").val(tax2_sel.substring(0, tax2_sel.indexOf("##")));
		objRow.find("input.tax2_percent").val(tax2_sel.substring(tax2_sel.indexOf("##") + 2));
		var tax2 = objRow.find("input.tax2_percent").val();
	} else {
		objRow.find("input.tax2_name").val("");
		objRow.find("input.tax2_percent").val("");
	}

	subtotal = priceU;
	subtotal = (discount > 0 ? subtotal - ((subtotal / 100) * discount) : subtotal);

	atax1 = parseFloat(tax1 != 0 ? (subtotal / 100) * tax1 : 0);
	atax2 = parseFloat(tax2 != 0 ? (subtotal / 100) * tax2 : 0);

	subtotal = (subtotal + atax1 + atax2) * quantity;

	objRow.find("input.subtotal").val(subtotal);
	objRow.find("span.subtotal").html(number_format(subtotal, 2, ",", "."));

	
	objRow.parent().children("tr.detail").each(function(i) {
		total += parseFloat(($(this).find("input.subtotal").val() ? $(this).find("input.subtotal").val() : 0));
	});

	$("#total").html(number_format(total, 2, ",", "."));
}

/* products */
function toggleTax() {
    if ($("#taxType").val() != "") {
        $("#tax_cnt").slideDown(200);
    } else {
        $("#tax_cnt").slideUp(100);
    }
}

function toggleStock() {
    if ($("#stockType").val() == "ECOMMERCE_PRODUCTS_STOCK_UNITS" || !$("#stockType").val()) {
        $("#stock_cnt").slideDown(200);
    } else {
        $("#stock_cnt").slideUp(100);
    }

    if ($("#stockType").val() == "ECOMMERCE_PRODUCTS_STOCK_SOON" || $("#stockType").val() == "ECOMMERCE_PRODUCTS_STOCK_ONDEMAND") {
        $("#stockNotes_cnt").slideDown(200);
    } else {
        $("#stockNotes_cnt").slideUp(100);
    }
}

function collpaseStocks(e) {
    $("#cnt_stocks").css("overflow-y", "hidden");
    $("#cnt_stocks").css("height", "150px");
    $("#cnt_stocks" + "_expand").show();
    $("#cnt_stocks" + "_collapse").hide();
    if (e) { e.cancelBubble=true;e.returnValue=false;return false; }
}

function expandStocks(e) {
    $("#cnt_stocks").css("overflow-y", "hidden");
    $("#cnt_stocks").css("height", "auto");
    $("#cnt_stocks" + "_expand").hide();
    $("#cnt_stocks" + "_collapse").show();
    if (e) { e.cancelBubble=true;e.returnValue=false;return false; }
}

function toggleVariationsStock(objSrc) {
    var oInput = $(objSrc).parents("tr").find("input[name*=stock]");

    if ($(objSrc).val() == "ECOMMERCE_PRODUCTS_STOCK_UNITS") {
        oInput.attr("disabled", "");
    } else {
        oInput.val(0);
        oInput.attr("disabled", "disabled");
    }
}

function toggleBargain() {
    if ($("#ECOMMERCE_PRODUCTS_OPTION_BARGAIN").attr("checked")) {
        $("#bargain_cnt").slideDown(200);
    } else {
        $("#bargain_cnt").slideUp(100);
    }
}

function toggleHome(msg) {
    if ($("#ECOMMERCE_PRODUCTS_OPTION_HOME").attr("checked")) {
		if (msg) {
			$("#ECOMMERCE_PRODUCTS_OPTION_HOME").attr("checked", false);
			alert(msg);
			return false;
		}
        $("#home_cnt").slideDown(200);
    } else {
        $("#home_cnt").slideUp(100);
    }
}

function ecommerce_addRelatedProduct(arrProduct, strBaseRootUrl, strEcommerce_delete, strEcommece_move, event) {
    var code = "<tr class=\"sortable\">";
        code+= "<td>";
        code+= "<input type=\"hidden\" name=\"productRelated[]\" value=\"" + arrProduct[0] + "\" />";
        code+= "<img src=\"" + (arrProduct[3] ? "ec_img.php?src=" + arrProduct[3] + "&amp;s=s" : strBaseRootUrl + "modules/ecommerce/images/products/thumb.gif") + "\" alt=\"\" width=\"50\" height=\"50\" class=\"thumbImage\" />";
        code+= "</td>";
        code+= "<td>" + arrProduct[1] + "</td>";
        code+= "<td>" + arrProduct[2] + "</td>";
        code+= "<td>";
        code+= "<a href=\"#\" onclick=\"return ecommerce_deleteRelatedProduct(this, event);\"><img src=\"" + xopieBaseRootUrl + "modules/ecommerce/images/icons/actionmenu_delete.gif\" alt=\"" + strEcommerce_delete + "\" /></a>&nbsp;";
        code+= "<a href=\"#\" class=\"sort_handler\" onclick=\"return cancelEvent(event);\"><img src=\"" + xopieBaseRootUrl + "modules/ecommerce/images/icons/move.gif\" alt=\"" + strEcommece_move + "\" /></a>";
        code+= "</td>";
        code+= "</tr>";

    $("#productRelated").show();
    $("#productRelated tbody").append(code);
    $("#productRelated tbody").sortable("refresh");

    return cancelEvent(event);
}

function ecommerce_deleteRelatedProduct(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    objRow.fadeOut(300, function() {
        objRow.remove();
        $("#productRelated tbody").sortable("refresh");
    });

    return cancelEvent(event);
}

function ecommerce_productsListCheckAll(blnCheck, event) {
	ecommerce_listCheckAll(blnCheck, event);
	ecommmerce_selectAllProductsQ();

	return false;
}

function ecommerce_productsListCheckEnsure(strNoSelected, strConfirm, strConfirmAll, event, bIncludeFirst) {
	return ecommerce_listCheckEnsure(strNoSelected, ($("#allSelected").val()=="1" ? strConfirmAll : strConfirm), event, bIncludeFirst);
}

function ecommerce_productsListbindUnselectClick() {
	ecommmerce_selectAllProductsQ(false);
}

function ecommmerce_selectAllProductsQ(select) {
	if (select===undefined) {
		select = $("#ecommerce_productsAdminListControlSelect").is(':checked');
	}

	$("#allSelectedQuestion").slideUp(400);
	$("input[type='checkbox'][id^='ecommerce_productsAdminListControlSelect.']").unbind("click", ecommerce_productsListbindUnselectClick);

	if (select) {
		$("#selectAllQuestion").slideDown(400);
		$("input[type='checkbox'][id^='ecommerce_productsAdminListControlSelect.']").click(ecommerce_productsListbindUnselectClick);
	} else {
		$("#selectAllQuestion").slideUp(400);
		$("#allSelected").val("0");
	}
}

function ecommmerce_selectAllProducts(select) {		
	if (select===undefined) {
		select = $("#allSelected").val()=="0";
	}

	$("#selectAllQuestion").hide();

	if (select) {
		$("#allSelected").val("1");
		$("#allSelectedQuestion").show();
	} else {
		$("#allSelected").val("0");
		$("#allSelectedQuestion").hide();
		$("#selectAllQuestion").show();
	}

	$(".admin_list input[type='checkbox']").attr('checked','checked');
	$('.pager a').click(function() {
		$(this).attr('href', $(this).attr('href')+"&all="+$("#allSelected").val());
	});

	$("input[type='checkbox'][id^='ecommerce_productsAdminListControlSelect.']").click(ecommerce_productsListbindUnselectClick);
}

/* products comments */
function ecommerce_addEmbeddedProductsComment(objSrc, event) {
    var objDest = $(objSrc).after("<div id='ecommerce_productsCommentsReply' style='display:none;'></div>");

    ecommerce_ajaxEdit("#ecommerce_productsCommentsReply", "ecommerce_productsCommentsAdmin", "idProductsComment", "", "productsCommentsData", "&mode=embedded", function(objDest) {
        $("#ecommerce_productsCommentsReply").slideDown(500, function() {
            $("#title").focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_addShowEmbeddedProductsComment(objDest) {
    if ($(objDest).find("form").length == 0) {
        $(objDest).find(".savedOK").remove();
        $("#results").prepend($(objDest).html());
        $(objDest).remove();
    }
}

function ecommerce_productsCommentsReply(intIdComment, event) {
    if ($("#ecommerce_productsCommentsReply").attr("id")) {
        $('#ecommerce_productsCommentsReply').remove(); 
    }

    $("#comment_" + intIdComment).after("<div id='ecommerce_productsCommentsReply' style='display:none;'></div>");

    ecommerce_ajaxEdit("#ecommerce_productsCommentsReply", "ecommerce_productsCommentsAdmin", "idProductsComment", "", "productsCommentsData", "&mode=embedded&reply=" + intIdComment, function(objDest) {
        $(objDest).slideDown(500, function() {
            $("#title").focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_productsCommentsTogglePublish(intIdComment, event) {
    $("#comment_" + intIdComment).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_productsCommentsAdmin&block=productsCommentsData&commandUpdate=1&cTogglePublish=1&idProductsComment=" + intIdComment,
        async: true,
        dataType: "html",
        success: function (data, textStatus) {
            $("#comment_" + intIdComment).replaceWith(data);
        }
    });

    return cancelEvent(event);
}

function ecommerce_productsCommentsToggleHighlight(intIdComment, event) {
    $("#comment_" + intIdComment).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_productsCommentsAdmin&block=productsCommentsData&commandUpdate=1&cToggleHighlight=1&idProductsComment=" + intIdComment,
        async: true,
        dataType: "html",
        success: function (data, textStatus) {
            $("#comment_" + intIdComment).replaceWith(data);
        }
    });

    return cancelEvent(event);
}

function ecommerce_productsCommentsEdit(intIdComment, event) {
    ecommerce_ajaxEdit($("#comment_" + intIdComment), "ecommerce_productsCommentsAdmin", "idProductsComment", intIdComment, "productsCommentsData", "", false);

    return cancelEvent(event);
}

function ecommerce_productsCommentsSave(intIdComment) {
    ecommerce_ajaxSave("#comment_" + intIdComment, 'ecommerce_productsCommentsAdmin', 'idProductsComment', intIdComment, 'productsCommentsData', function(objDest) {
        $(objDest).html($(objDest).children(":last").html());
    });
}

function ecommerce_productsCommentsDelete(intIdComment, strConfirm, event) {
    if (confirm(strConfirm)) {
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: "action=modules/ecommerce/ajax/admin/ecommerce_productsCommentsAdmin&block=productsCommentsData&commandUpdate=1&cDelete=1&idProductsComment=" + intIdComment,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                $("#comment_" + intIdComment).fadeOut(300, function() {
                    $("#comment_" + intIdComment).remove();
                });
            }
        });
    }

    return cancelEvent(event);
}

/* news */
function ecommerce_addRelatedNew(arrNew, strBaseRootUrl, strEcommerce_delete, strEcommece_move, event) {
    var code = "<tr class=\"sortable\">";
        code+= "<td>";
        code+= "<input type=\"hidden\" name=\"newRelated[]\" value=\"" + arrNew[0] + "\" />";
        code+= "" + arrNew[1]+ "";
        code+= "</td>";
        code+= "<td>" + arrNew[2] + "</td>";
        code+= "<td>";
        code+= "<a href=\"#\" onclick=\"return ecommerce_deleteRelatedNew(this, event);\">" + strEcommerce_delete + "</a>&nbsp;";
        code+= "<a href=\"#\" class=\"sort_handler\" onclick=\"return cancelEvent(event);\">" + strEcommece_move + "</a>";
        code+= "</td>";
        code+= "</tr>";

    $("#newRelated").show();
    $("#newRelated tbody").append(code);
    $("#newRelated tbody").sortable("refresh");

    return cancelEvent(event);
}

function ecommerce_deleteRelatedNew(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    objRow.fadeOut(300, function() {
        objRow.remove();
        $("#newRelated tbody").sortable("refresh");
    });

    return cancelEvent(event);
}

function ecommerce_deleteRelatedDocument(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    objRow.fadeOut(300, function() {
        objRow.remove();
        $("#cont_documents_documents tbody").sortable("refresh");

        if ($("#cont_documents_documents tbody").children().length <= 1) {
            $("#cont_documents_documents").hide();
        }
    });

    return cancelEvent(event);
}

function ecommerce_addRelatedLink(strEcommerce_delete, strEcommece_move, event) {
    var code = "<tr class='sortable'><td><input type='text' name='links_titles[]' value='' size='40' maxlength='255' /></td><td><input type='text' name='links_links[]' value='' size='40' maxlength='255' /></td><td><a href='#' onclick='return ecommerce_deleteRelatedLink(this, event);'>" + strEcommerce_delete + "</a>&nbsp;<a href='#' class='sort_handler' onclick='return cancelEvent(event);'>" + strEcommece_move + "</a></td></tr>";

    $("#cont_links_links").show();
    $("#cont_links_links tbody").append(code);
    $("#cont_links_links tbody").sortable("refresh");

    return cancelEvent(event);
}

function ecommerce_deleteRelatedLink(objSrc, event) {
    var objRow = $(objSrc).parent().parent();

    objRow.fadeOut(300, function() {
        objRow.remove();
        $("#cont_links_links tbody").sortable("refresh");

        if ($("#cont_links_links tbody").children().length <= 1) {
            $("#cont_links_links").hide();
        }
    });

    return cancelEvent(event);
}

/* news comments */
function ecommerce_addEmbeddedNewsComment(objSrc, event) {
    var objDest = $(objSrc).after("<div id='ecommerce_newsCommentsReply' style='display:none;'></div>");

    ecommerce_ajaxEdit("#ecommerce_newsCommentsReply", "ecommerce_newsCommentsAdmin", "idNewsComment", "", "newsCommentsData", "&mode=embedded", function(objDest) {
        $("#ecommerce_newsCommentsReply").slideDown(500, function() {
            $("#comment").focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_addShowEmbeddedNewsComment(objDest) {
    if ($(objDest).find("form").length == 0) {
        $(objDest).find(".savedOK").remove();
        $("#results").prepend($(objDest).html());
        $(objDest).remove();
    }
}

function ecommerce_newsCommentsReply(intIdComment, event) {
    if ($("#ecommerce_newsCommentsReply").attr("id")) {
        $('#ecommerce_newsCommentsReply').remove(); 
    }

    $("#comment_" + intIdComment).after("<div id='ecommerce_newsCommentsReply' style='display:none;'></div>");

    ecommerce_ajaxEdit("#ecommerce_newsCommentsReply", "ecommerce_newsCommentsAdmin", "idNewsComment", "", "newsCommentsData", "&mode=embedded&reply=" + intIdComment, function(objDest) {
        $(objDest).slideDown(500, function() {
            $("#comment").focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_newsCommentsTogglePublish(intIdComment, event) {
    $("#comment_" + intIdComment).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_newsCommentsAdmin&block=newsCommentsData&commandUpdate=1&cTogglePublish=1&idNewsComment=" + intIdComment,
        async: true,
        dataType: "html",
        success: function (data, textStatus) {
            $("#comment_" + intIdComment).replaceWith(data);
        }
    });

    return cancelEvent(event);
}

function ecommerce_newsCommentsToggleHighlight(intIdComment, event) {
    $("#comment_" + intIdComment).block({  
        message: "<h3><img src='" + xopieCDN + "images/admin/loading.gif' alt='Loading' />&nbsp;Loading</h3>",
        css: { opacity: '.8', backgroundColor: '#ffffff', border: '0', padding: '15px 0 0 0' },
        overlayCSS: { backgroundColor: '#ededed' }
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_newsCommentsAdmin&block=newsCommentsData&commandUpdate=1&cToggleHighlight=1&idNewsComment=" + intIdComment,
        async: true,
        dataType: "html",
        success: function (data, textStatus) {
            $("#comment_" + intIdComment).replaceWith(data);
        }
    });

    return cancelEvent(event);
}

function ecommerce_newsCommentsEdit(intIdComment, event) {
    ecommerce_ajaxEdit($("#comment_" + intIdComment), "ecommerce_newsCommentsAdmin", "idNewsComment", intIdComment, "newsCommentsData", "", false);

    return cancelEvent(event);
}

function ecommerce_newsCommentsSave(intIdComment) {
    ecommerce_ajaxSave("#comment_" + intIdComment, 'ecommerce_newsCommentsAdmin', 'idNewsComment', intIdComment, 'newsCommentsData', function(objDest) {
        $(objDest).html($(objDest).children(":last").html());
    });
}

function ecommerce_newsCommentsDelete(intIdComment, strConfirm, event) {
    if (confirm(strConfirm)) {
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: "action=modules/ecommerce/ajax/admin/ecommerce_newsCommentsAdmin&block=newsCommentsData&commandUpdate=1&cDelete=1&idNewsComment=" + intIdComment,
            async: true,
            dataType: "html",
            success: function (data, textStatus) {
                $("#comment_" + intIdComment).fadeOut(300, function() {
                    $("#comment_" + intIdComment).remove();
                });
            }
        });
    }

    return cancelEvent(event);
}

/* faq */
function ecommerce_initTreeFaqCategories(blnInitTree) {
    //optionsMenu
    $("ul#faqCategories li div").each(function (i) {
        var om = $(this).children("span.optionsMenu");
        var to;

        $(this).unbind("mouseover");
        $(this).unbind("mouseout");
        
        $(this).mouseover(function() {
            clearTimeout(to);
            om.css("display", "inline");
        });

        $(this).mouseout(function() {
            to = setTimeout(function() {om.fadeOut(50); }, 50);
        });
    });

    //tree
    if (blnInitTree) {
        $("ul#faqCategories").sortable({
            cursor: "move",
            opacity: 0.7,
            handle: ".sort-handle",
            placeholder: "helper",
            update: ecommerce_faqCategoriesSortCallback
        });
    } else {
        $("ul#faqCategories").sortable("refresh");
    }
}

function ecommerce_addEmbeddedFaqCategory(strCurLocale, event) {
    ecommerce_ajaxEdit("#faqCategoriesData", "ecommerce_faqCategoriesAdmin", "idFaqCategory", "", "faqCategoriesData", "&mode=embedded", function(objDest) {
        $(objDest).slideDown(500, function() {
            $("#name_" + strCurLocale).focus();
        });
    });

    return cancelEvent(event);
}

function ecommerce_showEmbeddedFaqCategory(code) {
    var code = $(code);

    $("#faqCategories").prepend(code);
    ecommerce_initTreeFaqCategories(false);

    code.effect("pulsate", { times: 2 }, 500);
}

function ecommerce_toggleFaqCategory(objSrc, event) {
    var bShow = true;

    if ($("#faqList").attr("id")) {
        if ($("#faqList").parent().attr("id") == $(objSrc).parent().parent().attr("id")) {
            bShow = false;
        }

        $("#faqList").slideUp(100, function() {
            $("#faqList").remove();
        });
    }

    if (bShow) {
        setTimeout(function() {
            $(objSrc).parent().after($("<div id='faqList' class='faqList'></div>"));
            ecommerce_ajaxView($("#faqList"), "ecommerce_faqCategoriesAdmin", "idFaqCategory", $(objSrc).parent().parent().attr("id").replace("faqCategories_", ""), "faqCategoriesFaqs", function() {
                $("#faqList ul#faqs").sortable({
                    cursor: "move",
                    opacity: 0.6,
                    handle: ".sort_handler",
                    update: ecommerce_faqSortCallback
                });

                $("#faqList").slideDown(100);
            });
        }, 125);
    }

    return (event ? cancelEvent(event) : false);
}

function ecommerce_faqCategoriesSortCallback(event, ui) {
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_faqCategoriesSort&" + $("ul#faqCategories").sortable("serialize"),
        async: true,
        dataType: "text",
        success: function (data, textStatus) {
            //none
        }
    });
}

function ecommerce_faqSortCallback(event, ui) {
    var count = 1;

    $("#faqs li").each(function(i) {
        $(this).find("span").html(count + ".");
        count++;
    });

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "action=modules/ecommerce/ajax/admin/ecommerce_faqSort&" + $("ul#faqs").sortable("serialize"),
        async: true,
        dataType: "text",
        success: function (data, textStatus) {
            //none
        }
    });
}

/* prices */
function toggleEcommercePrices() {
	if (parseInt($("#ecommercePrices").val()) > 0) {
		$("#ecommercePrices_cnt").find("div.field").hide();
		$("#ecommercePrices_cnt").slideDown(200, function() {
			for (i = 0; i <= parseInt($("#ecommercePrices").val()); i++) {
				$("#ecommercePrices_cnt").find("div.field").eq(i).show();
			}
		});
	} else {
		$("#ecommercePrices_cnt").slideUp(200);
	}
}

/* designs */
/*
function ecommerce_designColorsToggle() {
    if ($("#settingsDesignColorsCnt").css("position") == "absolute") {
        $("#settingsDesignColorsCnt").css("position", "");
        $("#settingsDesignColorsCnt").css("width", "auto");
        $("#settingsDesignColorsCnt").css("height", "auto");
    
    } else {
        $("#settingsDesignColorsCnt").css("position", "absolute");
        $("#settingsDesignColorsCnt").css("width", "990px");
        $("#settingsDesignColorsCnt").css("top", "0px");
        $("#settingsDesignColorsCnt").css("left", ($(window).width() - 990) /2 + "px" );
        $("#settingsDesignColorsCnt").css("height", "95%");
        $("#settingsDesignColorsCnt").css("background-color", "#fff");    
    }
}

function ecommerce_designDisablePreviewEvents() {
    $("#preview").contents().find("*").bind("click keydown mousedown", function(e) {
        return cancelEvent(e);
    });

    $("#preview").contents().find("form").bind("submit", function(e) {
        return cancelEvent(e);
    });
}

function ecommerce_designPick(strColor, strTemplate, blnIgnore) {
	if (!blnIgnore) {
		$("#pickedColors").find("span.color").each(function(i) {
			if ($(this).attr("color") == strColor) {
				$(this).remove();
			}
		});

		$("#pickedColors").append("<span class=\"color\" color=\"" + strColor + "\" style=\"background-color:" + strColor + ";\" onclick=\"ecommerce_designPick('" + strColor + "', '" + strTemplate + "');\"></span>");

		if ($("#pickedColors").find("span.color").length > 10) {
			$("#pickedColors").find("span.color:first").remove();
		}
	}

	$("#ecommerceTemplateColor").val(strColor.substr(1));
	$("#preview").contents().find("link[href*=public.css]").attr({href: "public.css.php?n=" + strColor.substr(1) + "&t=" + strTemplate}); //old: $("#preview").contents().find("link[href*=public.css]").attr({href: "src/templates/" + strTemplate + "/css/public.css.php?n=" + strColor.substr(1)});
}
*/
/* styles */
function ecommerce_designStylesToggle() {
    if ($("#settingsDesignStylesCnt").css("position") == "absolute") {
		$("#settingsDesignStylesTitle").show();
        $("#settingsDesignStylesCnt").css("position", "");
        $("#settingsDesignStylesCnt").css("width", "auto");
        $("#settingsDesignStylesCnt").css("height", "auto");
    } else {
		$("#settingsDesignStylesTitle").hide();
        $("#settingsDesignStylesCnt").css("position", "absolute");
        $("#settingsDesignStylesCnt").css("width", "1100px");
        $("#settingsDesignStylesCnt").css("top", "0px");
        $("#settingsDesignStylesCnt").css("left", ($(window).width() - 1100) /2 + "px" );
		$("#settingsDesignStylesCnt").css("height", "96%");
		$("#settingsDesignStylesCnt").css("z-index", "100");
        $("#settingsDesignStylesCnt").css("background-color", "#fff");
		scroll(0,0);
    }

	return true;
}

function ecommerce_designInit(bReset) {
	for (var block in _layoutEditorBlocks) {
		for (var feature in _layoutEditorBlocks[block]) {
			$("#" + block + "_" + feature).attr("block", block);
			$("#" + block + "_" + feature).attr("feature", feature);

			$("#" + block + "_" + feature + " .dsedit").attr("block", block);
			$("#" + block + "_" + feature + " .dsedit").attr("feature", feature);

			$("#" + block + "_" + feature + " .dsdelete").attr("block", block);
			$("#" + block + "_" + feature + " .dsdelete").attr("feature", feature);
/*
			if (block == "general" && feature == "color") {
				ecommerce_designSetValue(block, feature, $("#ecommerceTemplateColor").val(), false, false);
			} else {
				ecommerce_designSetValue(block, feature, (_layoutEditorBlocks[block][feature]["defaultValue"] ? _layoutEditorBlocks[block][feature]["defaultValue"] : ""), false, true);
			}
*/
			if (_layoutEditorBlocks[block][feature]["type"] == "colorPicker") {
				if (block == "general" && feature == "color") {
					/*
					iColorPicker(block + "_" + feature + "_picker", function(oElem, sColor) {
						<($(oElem).attr("block"), $(oElem).attr("feature"), sColor, true);
					});
					$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
						var val = $("#ecommerceTemplateColorDefault").val();
						iColorPickerSetValue($(this).attr("block") + "_" + $(this).attr("feature") + "_picker", val);
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), val, true, true);
						return (event ? cancelEvent(event) : false);
					});
					*/
				} else {
					iColorPicker(block + "_" + feature + "_picker", function(oElem, sColor) {
						ecommerce_designSetValue($(oElem).attr("block"), $(oElem).attr("feature"), sColor, true);
					});
					$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
						var val = (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] : "");
						iColorPickerSetValue($(this).attr("block") + "_" + $(this).attr("feature") + "_picker", val);
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), val, true, true);
						return (event ? cancelEvent(event) : false);
					});
				}

			} else if (_layoutEditorBlocks[block][feature]["type"] == "textPicker") {
				$("#" + block + "_" + feature + " .dsedit").click(function(event) {
					return ecommerce_designShowPopup(_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["popup"], event);
				});

				$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_fontfamily", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontfamily"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontfamily"]["defaultValue"] : "auto"), false, true);
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_color", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_color"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_color"]["defaultValue"] : ""), false, true);
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_fontweight", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontweight"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontweight"]["defaultValue"] : ""), false, true);
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_fontstyle", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontstyle"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontstyle"]["defaultValue"] : ""), false, true);
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_textdecoration", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_textdecoration"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_textdecoration"]["defaultValue"] : ""), false, true);

					if (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontsize"]) {
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_fontsize", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontsize"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_fontsize"]["defaultValue"] : ""), false, true);
					}

					ecommerce_designPreviewRefresh(false, false);

					return (event ? cancelEvent(event) : false);
				});

			} else if (_layoutEditorBlocks[block][feature]["type"] == "imagePicker") {
				$("#" + block + "_" + feature + " .dsedit").click(function(event) {
					return ecommerce_designShowPopup(_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["popup"], event);
				});

				$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_file", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_file"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_file"]["defaultValue"] : ""), false, true);

					if (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeat"]) {
						$("#" + $(this).attr("block") + "_" + $(this).attr("feature") + "_repeat").attr("checked", false);
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_repeat", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeat"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeat"]["defaultValue"] : ""), false, true);
					}

					if (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeatx"]) {
					$("#" + $(this).attr("block") + "_" + $(this).attr("feature") + "_repeatx").attr("checked", false);
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_repeatx", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeatx"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeatx"]["defaultValue"] : ""), false, true);
					}

					if (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeaty"]) {
					$("#" + $(this).attr("block") + "_" + $(this).attr("feature") + "_repeaty").attr("checked", false);
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature") + "_repeaty", (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeaty"]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature") + "_repeaty"]["defaultValue"] : ""), false, true);
					}

					ecommerce_designPreviewRefresh(false, false);

					return (event ? cancelEvent(event) : false);
				});

			} else if (_layoutEditorBlocks[block][feature]["type"] == "select") {
				$("#" + block + "_" + feature).change(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), $(this).val(), true);
				});

				$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] : ""), true, true);
					return (event ? cancelEvent(event) : false);
				});

			} else if (_layoutEditorBlocks[block][feature]["type"] == "checkbox") {
				$("#" + block + "_" + feature).change(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), ($(this).attr("checked") ? $(this).val() : false), true);
				});

				$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] : ""), true, true);
					return (event ? cancelEvent(event) : false);
				});

			} else if (_layoutEditorBlocks[block][feature]["type"] == "slider") {
				$("#" + block + "_" + feature + " .dsedit").slider({
					value: _layoutEditorBlocks[block][feature]["defaultValue"],
					min: _layoutEditorBlocks[block][feature]["minValue"],
					max: _layoutEditorBlocks[block][feature]["maxValue"],
					step: _layoutEditorBlocks[block][feature]["stepValue"],
					slide: function(event, ui) {
						ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), ui.value, true);
					}
				});

				$("#" + block + "_" + feature + " .dsdelete").click(function(event) {
					ecommerce_designSetValue($(this).attr("block"), $(this).attr("feature"), (_layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] ? _layoutEditorBlocks[$(this).attr("block")][$(this).attr("feature")]["defaultValue"] : ""), true, true);
					return (event ? cancelEvent(event) : false);
				});
			}
		}
	}

	if ($("#ecommerce_templateCustomCssJs").val() && !bReset) {
		var initBlocks = $.evalJSON($("#ecommerce_templateCustomCssJs").val());

		for (var block in initBlocks) {
			for (var feature in initBlocks[block]) {
				if (typeof(initBlocks[block][feature]["value"]) != "undefined") {
					ecommerce_designSetValue(block, feature, initBlocks[block][feature]["value"], false);
				}
			}
		}
	}

	setTimeout(function() { 
		$(".popUpOptions").css("display", "none"); 
		$(".popUpOptions").css("visibility", "visible"); 
		ecommerce_designShowBlock("general", false); }
	, 250);
}

function ecommerce_designReset(sConfirm, event) {
	if (confirm(sConfirm)) {
		for (var block in _layoutEditorBlocks) {
			for (var feature in _layoutEditorBlocks[block]) {
				ecommerce_designSetValue(block, feature, (_layoutEditorBlocks[block][feature]["defaultValue"] ? _layoutEditorBlocks[block][feature]["defaultValue"] : ""), false);
			}
		}

		ecommerce_designPreviewRefresh(false, false);
	}

	return cancelEvent(event);
}

function ecommerce_designStylesInitIframe() {
	$("#preview").contents().find("head").append("<style id='sdCustomStyles' type='text/css'></style>");
	$("#preview").contents().find("link[href*=userFiles/ecommerce/cache/]").remove();

	//_layoutEditorBlocks["general"]["color"]["valueUpdated"] = (_layoutEditorBlocks["general"]["color"]["value"] && _layoutEditorBlocks["general"]["color"]["value"] != $("#ecommerceTemplateColorDefault").val() ? true : false);
	ecommerce_designPreviewRefresh(false, false);

    $("#preview").contents().find("form").bind("submit", function(e) {
        return cancelEvent(e);
    });
}

function ecommerce_designShowBlock(sBlock, event) {
	$("#options").find("li a").removeClass("active");
	$("li." + sBlock + "Styles a").addClass("active");

	$("div.popUpOptions:visible").hide('slide', { direction: 'right' }, 500);

	$("#featuresWrap").find("div.featuresBlock:visible").slideUp(500);
	$("#" + sBlock + "Block").slideDown(500);

	return (event ? cancelEvent(event) : false);
}

function ecommerce_designSetValue(sBlock, sFeature, sValue, bRefreshPreview, bForceDelete) {
	var realValue = sValue;

	if (_layoutEditorBlocks[sBlock] && _layoutEditorBlocks[sBlock][sFeature]) {
		if (sValue && _layoutEditorBlocks[sBlock][sFeature]["unitsValue"]) {
			realValue = sValue + _layoutEditorBlocks[sBlock][sFeature]["unitsValue"];
		}

		/*
		if (_layoutEditorBlocks[sBlock][sFeature]["type"] == "colorPicker") {
			if (!bForceDelete) {
				$("#" + sBlock + "_" + sFeature + " a.icon img").hide();
				$("#" + sBlock + "_" + sFeature + " a.icon .selectedColor").css("background-color", sValue);
				$("#" + sBlock + "_" + sFeature + " a.icon .selectedColor").show();
				//$("#" + sBlock + "_" + sFeature + " ul.iconSet").show();
			} else {
				$("#" + sBlock + "_" + sFeature + " a.icon .selectedColor").hide();
				//$("#" + sBlock + "_" + sFeature + " ul.iconSet").hide();
				$("#" + sBlock + "_" + sFeature + " a.icon img").show();
			}
		}
		*/

		if (sBlock == "general" && sFeature == "color") {
			/*
			if (_layoutEditorBlocks[sBlock][sFeature]["value"] != sValue) {
				_layoutEditorBlocks[sBlock][sFeature]["valueUpdated"] = true;
				$("#ecommerceTemplateColor").val(sValue);
			}

			$("#" + sBlock + "_" + sFeature + " a.icon img").hide();
			$("#" + sBlock + "_" + sFeature + " a.icon .selectedColor").css("background-color", "#" + sValue);
			$("#" + sBlock + "_" + sFeature + " a.icon .selectedColor").show();
			//$("#" + sBlock + "_" + sFeature + " ul.iconSet").show();
			*/
		}

		if (_layoutEditorBlocks[sBlock][sFeature]["type"] == "slider") {
			$("#" + sBlock + "_" + sFeature + " .dsedit").slider("value", sValue);
		} else if (_layoutEditorBlocks[sBlock][sFeature]["type"] == "colorPicker") {
			realValue = (sValue ? "#" + sValue : "");
			iColorPickerSetValue(sBlock + "_" + sFeature + "_picker", sValue);
		}

		if (sFeature.indexOf("_") > -1) {
			parentFeature = sFeature.substring(0, sFeature.indexOf("_"));
			cssSelector = sFeature.substring(sFeature.indexOf("_") + 1);

			/*
			if (!bForceDelete) {
				$("#" + sBlock + "_" + parentFeature + " ul.iconSet").show();
			} else {
				$("#" + sBlock + "_" + parentFeature + " ul.iconSet").hide();
			}
			*/

			if (_layoutEditorBlocks[sBlock][parentFeature]["type"] == "imagePicker" && cssSelector == "file") {
				sValue = (!sValue || sValue == "none" ? "" : sValue);
				bForceDelete = (!sValue ? true : bForceDelete);

				if (!bForceDelete) {
					$("#" + sBlock + "_" + parentFeature + " a.icon .noImage").hide();
					$("#" + sBlock + "_" + parentFeature + " a.icon .selectedImage").attr("src", "resource.php?src=" + (sValue.indexOf("/") == 0 ? sValue.substr(1) : sValue) + "&w=16&h=16&m=c");
					$("#" + sBlock + "_" + parentFeature + " a.icon .selectedImage").show();
					//$("#" + sBlock + "_" + parentFeature + " ul.iconSet").show();

					realValue = "url(" + sValue + ")";
				} else {
					$("#" + sBlock + "_" + parentFeature + " a.icon .selectedImage").hide();
					//$("#" + sBlock + "_" + parentFeature + " ul.iconSet").hide();
					$("#" + sBlock + "_" + parentFeature + " a.icon .noImage").show();
				}

			} else if (_layoutEditorBlocks[sBlock][parentFeature]["type"] == "textPicker") {
				switch (cssSelector) {
					case "fontfamily":
						sValue = (!sValue || sValue == "inherit" ? "auto" : sValue);
						realValue = (sValue == "auto" ? "inherit" : "'" + sValue + "'");
						$("#" + sBlock + "_" + sFeature).val(sValue);
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("font-family", realValue);
						$("#" + sBlock + "_" + parentFeature + " .featureSummary .ff").html(_layoutSampleText);
						break;

					case "color":
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("color", realValue);
						break;

					case "fontsize":
						$("#" + sBlock + "_" + sFeature + " .dsedit").slider("value", sValue);
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("font-size", realValue);
						//$("#" + sBlock + "_" + parentFeature + " .featureSummary .fs").html(realValue);
						break;

					case "fontweight":
						realValue = (sValue ? sValue : "normal");
						$("#" + sBlock + "_" + sFeature).attr("checked", (sValue == "bold" ? "checked" : ""));
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("font-weight", realValue);
						break;

					case "fontstyle":
						realValue = (sValue ? sValue : "normal");
						$("#" + sBlock + "_" + sFeature).attr("checked", (sValue == "italic" ? "checked" : ""));
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("font-style", realValue);
						break;

					case "textdecoration":
						realValue = (sValue ? sValue : "none");
						$("#" + sBlock + "_" + sFeature).attr("checked", (sValue == "underline" ? "checked" : ""));
						$("#" + sBlock + "_" + parentFeature + " .featureSummary").css("text-decoration", realValue);
						break;
				}

			} else if (sBlock == "background" && (cssSelector == "repeat" || cssSelector == "repeatx" || cssSelector == "repeaty")) {
				$("#background_image_repeat").attr("checked", sValue == "repeat");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["value"] = (sValue == "repeat" ? "repeat" : "");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["realValue"] = (sValue == "repeat" ? "repeat" : "");

				$("#background_image_repeatx").attr("checked", sValue == "repeat-x");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeatx"]["value"] = (sValue == "repeat-x" ? "repeat-x" : "");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeatx"]["realValue"] = (sValue == "repeat-x" ? "repeat-x" : "");

				$("#background_image_repeaty").attr("checked", sValue == "repeat-y");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeaty"]["value"] = (sValue == "repeat-y" ? "repeat-y" : "");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeaty"]["realValue"] = (sValue == "repeat-y" ? "repeat-y" : "");

			} else if (sBlock == "header" && cssSelector == "repeat") {
				sValue = (sValue == "repeat" ? sValue : "no-repeat");
				realValue = (sValue == "repeat" ? sValue : "no-repeat");

				$("#header_image_repeat").attr("checked", sValue == "repeat");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["value"] = sValue;
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["realValue"] = sValue;

			} else if (sBlock == "cart" && cssSelector == "repeat") {
				sValue = (sValue == "repeat" ? sValue : "no-repeat");
				realValue = (sValue == "repeat" ? sValue : "no-repeat");

				$("#cart_image_repeat").attr("checked", sValue == "repeat");
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["value"] = sValue;
				_layoutEditorBlocks[sBlock][parentFeature + "_repeat"]["realValue"] = sValue;
			}
		}

		_layoutEditorBlocks[sBlock][sFeature]["value"] = sValue;
		_layoutEditorBlocks[sBlock][sFeature]["realValue"] = realValue;

		if (bRefreshPreview) {
			ecommerce_designPreviewRefresh(sBlock, sFeature);
		}
	}
}

function ecommerce_designPreviewRefresh(sBlock, sFeature) {
	var aStyles = {};
	var sStyle = "";
	var iCount = 0;
	var bFound = false;

	for (var block in _layoutEditorBlocks) {
		for (var feature in _layoutEditorBlocks[block]) {
			if (_layoutEditorBlocks[block][feature]["realValue"]) {
				if (_layoutEditorBlocks[block][feature]["cssSelectors"] && _layoutEditorBlocks[block][feature]["cssAttributes"]) {
					if (_layoutEditorBlocks[block][feature]["type"] == "colorPicker" && ((_layoutEditorBlocks[block]["image_file"] && _layoutEditorBlocks[block]["image_file"]["value"]) || (_layoutEditorBlocks[block]["imageHover_file"] && _layoutEditorBlocks[block]["imageHover_file"]["value"]) || (_layoutEditorBlocks[block]["imageTitles_file"] && _layoutEditorBlocks[block]["imageTitles_file"]["value"]))) {
						cssAppend = "";
					} else if (_layoutEditorBlocks[block][feature]["cssAppend"]) {
						cssAppend = _layoutEditorBlocks[block][feature]["cssAppend"];
					} else {
						cssAppend = "";
					}

					if (cssAppend) {
						cssAppend = cssAppend.replace(/%value%/g, _layoutEditorBlocks[block][feature]["value"]);
						cssAppend = cssAppend.replace(/%realValue%/g, _layoutEditorBlocks[block][feature]["realValue"]);
					}

					bFound = false;

					for (var i in aStyles) {
						if (aStyles[i]["selectors"] == _layoutEditorBlocks[block][feature]["cssSelectors"]) {
							bFound = i;
						}
					}

					if (bFound) {
						aStyles[bFound]["values"] = aStyles[bFound]["values"] + _layoutEditorBlocks[block][feature]["cssAttributes"] + ":" + _layoutEditorBlocks[block][feature]["realValue"] + (_layoutEditorBlocks[block][feature]["cssImportant"] ? " !important" : "") + ";";
						aStyles[bFound]["append"] = aStyles[bFound]["append"] + cssAppend;
					} else {
						aStyles[iCount] = {
							selectors: _layoutEditorBlocks[block][feature]["cssSelectors"],
							values: _layoutEditorBlocks[block][feature]["cssAttributes"] + ":" + _layoutEditorBlocks[block][feature]["realValue"] + (_layoutEditorBlocks[block][feature]["cssImportant"] ? " !important" : "") + ";",
							append: cssAppend
						};

						iCount++;
					}
				}
			}
		}
	}

	for (var i in aStyles) {
		sStyle = sStyle + aStyles[i]["selectors"] + "{" + aStyles[i]["values"] + "}\n";

		if (aStyles[i]["append"]) {
			sStyle = sStyle + aStyles[i]["append"] + "\n";
		}
	}

	$("#ecommerce_templateCustomCss").val(sStyle);
	$("#ecommerce_templateCustomCssJs").val($.toJSON(_layoutEditorBlocks));

	if ($.browser.msie) {
		$("#preview").contents().find("#sdCustomStyles").remove();
		$("#preview").contents().find("head").append("<style id='sdCustomStyles' type='text/css'>"+$("#ecommerce_templateCustomCss").val()+"</style>");
	} else {
		$('#preview').contents().find('#sdCustomStyles').empty();
		$('#preview').contents().find('#sdCustomStyles').append($("#ecommerce_templateCustomCss").val());
	}

	/*
	if (_layoutEditorBlocks["general"]["color"]["valueUpdated"]) {
		$("#preview").contents().find("link[href*=public.css]").attr({href: "public.css.php?n=" + _layoutEditorBlocks["general"]["color"]["value"] + "&t=" + $("#ecommerceTemplate").val()});
		_layoutEditorBlocks["general"]["color"]["valueUpdated"] = false;
	}
	*/
}

function ecommerce_designShowPopup(sPopup, event) {
	$("#" + sPopup).show("slide", { direction: "right" }, 400);
	return (event ? cancelEvent(event) : false);
}

function ecommerce_designHidePopup(sPopup, event) {
	$("#" + sPopup).hide("slide", { direction: "right" }, 500);
	return (event ? cancelEvent(event) : false);
}

function ecommerce_designInitUploader(sField, sBlock, sFeature) {
	$("#" + sField + "Btn").after("<input type=\"hidden\" name=\"" + sField + "\" id=\"" + sField + "\" value=\"\" />");
	$("#" + sField + "Btn").after("<img id=\"" + sField + "Btn_uploading\" src=\"" + xopieBaseRootUrl + "modules/ecommerce/images/uploading.gif\" style=\"display:none;\" />");

	$.ajax_upload("#" + sField + "Btn", {
		action: "ajax.php",
		name: "upload_image",
		data: {
			action: "modules/ecommerce/ajax/admin/ecommerce_imageUpload"
		},
		onSubmit: function(file, extension) {
			$("#" + sField + "Btn").hide();
			$("#" + sField + "Btn_uploading").show();
		},
		onComplete: function(file, response) {
			$("#" + sField + "Btn_uploading").hide();
			$("#" + sField + "Btn").show();
		},
		onError: function(file, response){
			if (response.indexOf("success:") == 0) {
				$("#" + sField).val("/userFiles/ecommerce/" + response.substr(8));
				ecommerce_designSetValue(sBlock, sFeature, $("#" + sField).val(), true);
			} else {
				alert(response);
			}
		}
	});
}

/* layout */
var _layoutPreviewJQ = false;
var _layoutCurWrap = false;
var _layoutCurWrapInner = false;
var _layoutCurBlock = false;
var _layoutStyles = {};

function ecommerce_designLayoutToggle() {
    if ($("#settingsDesignLayoutCnt").css("position") == "absolute") {
		$("#settingsDesignLayoutTitle").show();
        $("#settingsDesignLayoutCnt").css("position", "");
        $("#settingsDesignLayoutCnt").css("width", "auto");
        $("#settingsDesignLayoutCnt").css("height", "auto");
    } else {
		$("#settingsDesignLayoutTitle").hide();
        $("#settingsDesignLayoutCnt").css("position", "absolute");
        $("#settingsDesignLayoutCnt").css("width", "1200px");
        $("#settingsDesignLayoutCnt").css("top", "0px");
        $("#settingsDesignLayoutCnt").css("left", ($(window).width() - 1200) /2 + "px" );
		$("#settingsDesignLayoutCnt").css("height", "96%");
		$("#settingsDesignLayoutCnt").css("z-index", "100");
        $("#settingsDesignLayoutCnt").css("background-color", "#fff");
		scroll(0,0);
    }

	return true;
}

function ecommerce_designLayoutInitIframe(strBaseRootUrl) {
	$("#preview").contents().find("head").append("<link rel='stylesheet' href='" + strBaseRootUrl + "modules/ecommerce/css/admin.customLayout-client.css' type='text/css' media='all' />");
	//$("#preview").contents().find("head").append("<script type='text/javascript' src='" + strBaseRootUrl + "libs/jquery/jquery.icolorpicker/iColorPicker.js'></script>");

	//$("#preview").contents().find("head").append("<style id='sdCustomStyles' type='text/css'></style>");
	//$("#preview").contents().find("link[href*=userFiles/ecommerce/cache/]").remove();

	_layoutPreviewJQ = window.frames[0].$;

	ecommerce_designLayoutInitSortables();
	ecommerce_designLayoutInitResizables();
	ecommerce_designLayoutInitControls();

	var cssObject = /#([^{]+){([^}]*)}/gim;
	var cssAttrs = /([^:]+):([^;]+);?/gim;
	var oMatch, aMatch;

	while (oMatch = cssObject.exec($("textarea#ecommerce_layoutStyles").val())) {
		oMatch[1] = $.trim(oMatch[1]);

		if (oMatch[1] && oMatch[2]) {
			if (!_layoutStyles[oMatch[1]]) {
				_layoutStyles[oMatch[1]] = {};
			}

			while (aMatch = cssAttrs.exec(oMatch[2])) {
				if (aMatch[1] && aMatch[2]) {
					_layoutStyles[oMatch[1]][aMatch[1]] = aMatch[2];
				}
			}
		}
	}

    $("#preview").contents().find("form").bind("submit", function(e) {
        return cancelEvent(e);
    });
}

function ecommerce_designLayoutInitSortables() {
	_layoutPreviewJQ(".xlayout").sortable("destroy");
	_layoutPreviewJQ(".xlayout").sortable({
		axis: "y",
		items: ".xblockwrap",
		placeholder: "xblockwrap-state-highlight",
		update: function() {
			ecommerce_designLayoutUpdate();
		}
	}).disableSelection();

	_layoutPreviewJQ(".xblockwrapinner").sortable("destroy");
	_layoutPreviewJQ(".xblockwrapinner").sortable({
		items: ".xblock",
		connectWith: ".xblockwrapinner",
		tolerance:"pointer",
		update: function() {
			ecommerce_designLayoutUpdate();
		}
	}).disableSelection();

	_layoutPreviewJQ(".xblocwidgets").sortable("destroy");
	_layoutPreviewJQ(".xblocwidgets").sortable({
		connectWith: ".xblocwidgets",
		handle:".move",
		tolerance:"pointer",
		start: function(event, ui) {
			ui.item.addClass("xwidget-state-sorting");
		},
		stop: function(event, ui) {
			ui.item.removeClass("xwidget-state-sorting");
		},
		update: function() {
			ecommerce_designLayoutUpdate();
			ecommerce_designLayoutInitControls();
		}
	}).disableSelection();
}

function ecommerce_designLayoutInitResizables() {
	_layoutPreviewJQ(".xblock").resizable("destroy");
	_layoutPreviewJQ(".xblock").resizable({
		minWidth: 144,
		maxWidth: 980,
		grid: [82, 980],
		handles: "e",
		resize: function(event, ui) {
			_layoutPreviewJQ(this).height("auto");
		},
		stop: function(event, ui) {
			ecommerce_designLayoutSetStyle(_layoutPreviewJQ(this).attr("id"), "width", _layoutPreviewJQ(this).width() + "px");
		}
	});

	_layoutPreviewJQ(".xblock").each(function(i) {
		ecommerce_designLayoutSetStyle(_layoutPreviewJQ(this).attr("id"), "width", _layoutPreviewJQ(this).width() + "px");
	});
}

function ecommerce_designLayoutInitControls() {
	var strActions;

	_layoutPreviewJQ(".xblockwrapinner").each(function(i) {
		_layoutPreviewJQ(this).find("p.xblockwrapactions").remove();

		strActions = "";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutAddXBlock(this, event);'>Afegir xBlock</a>";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutStyleBlockWrap(this, event);'>Style (wrap)</a>";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutStyleBlockWrapInner(this, event);'>Style (wrap inner)</a>";

		if (_layoutPreviewJQ(this).parents(".xblockwrap").attr("id") != "xheader" && _layoutPreviewJQ(this).parents(".xblockwrap").attr("id") != "xcontent" && _layoutPreviewJQ(this).parents(".xblockwrap").attr("id") != "xfooter" && !_layoutPreviewJQ(this).find("#xpagecontent").length) {
			strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutDeleteXBlockWrap(this, event);'>Delete XBlockWrap</a>";
		}

		_layoutPreviewJQ(this).append("<p class='xblockwrapactions'>" + strActions + "</p>");
	});

	_layoutPreviewJQ(".xblockinner").each(function(i) {
		_layoutPreviewJQ(this).find("p.xblockactions").remove();

		strActions = "";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutAddWidget(this, event);'>Add Widget</a>";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutStyleBlock(this, event);'>Style Block</a>";

		if (!_layoutPreviewJQ(this).find("#xpagecontent").length) {
			strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutDeleteXBlock(this, event);'>Delete XBlock</a>";
		}

		_layoutPreviewJQ(this).prepend("<p class='xblockactions'>" + strActions + "</p>");

		if  (_layoutPreviewJQ(this).find(".xWidgetNoOverflow").length) {
			_layoutPreviewJQ(this).css("overflow", "visible");
		}
	});

	_layoutPreviewJQ(".xwidget").each(function(i) {
		_layoutPreviewJQ(this).find("p.xwidgetactions").remove();

		strActions = "";
		strActions += "<a href='#' class='move' onclick='return top.parent.cancelEvent(event);'>Move</a>";
		strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutEditWidget(this, event);'>Edit</a>";

		if (_layoutPreviewJQ(this).attr("id") != "xpagecontent") {
			strActions += "<a href='#' onclick='return top.parent.ecommerce_designLayoutDeleteWidget(this, event);'>Delete</a>";
		}

		_layoutPreviewJQ(this).prepend("<p class='xwidgetactions'>" + strActions + "</p>");
	});
}

function ecommerce_designLayoutInitUploader(sField, fnSuccessCb) {
	$("#" + sField + "Btn").after("<img id=\"" + sField + "Btn_uploading\" src=\"" + xopieBaseRootUrl + "modules/ecommerce/images/uploading.gif\" style=\"display:none;\" />");

	$.ajax_upload("#" + sField + "Btn", {
		action: "ajax.php",
		name: "upload_image",
		data: {
			action: "modules/ecommerce/ajax/admin/ecommerce_imageUpload"
		},
		onSubmit: function(file, extension) {
			$("#" + sField + "Btn").hide();
			$("#" + sField + "Btn_uploading").show();
		},
		onComplete: function(file, response) {
			$("#" + sField + "Btn_uploading").hide();
			$("#" + sField + "Btn").show();
		},
		onError: function(file, response){
			if (response.indexOf("success:") == 0) {
				fnSuccessCb("/userFiles/ecommerce/" + response.substr(8));
			} else {
				alert(response);
			}
		}
	});
}

function ecommerce_designLayoutAddXBlockWrap(e) {
	var uid = "uibw" + Math.floor(Math.random() * (999 - 111 + 1) + 111);

	while (_layoutPreviewJQ("#" + uid).length > 0) {
		uid = "uibw" + Math.floor(Math.random() * (999 - 111 + 1) + 111)
	}

	_layoutPreviewJQ(".xlayout").append("<div id='" + uid + "' class='xblockwrap'><div class='xblockwrapinner container_12'><div class='clear'>&nbsp;</div></div></div>");

	ecommerce_designLayoutInitSortables();
	ecommerce_designLayoutInitResizables();
	ecommerce_designLayoutInitControls();
	ecommerce_designLayoutUpdate();

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutDeleteXBlockWrap(oSrc, e) {
	if (confirm("sure?")) {
		_layoutPreviewJQ(oSrc).parents("div.xblockwrap").slideUp(400, function() {
			_layoutPreviewJQ(this).remove();
			ecommerce_designLayoutInitSortables();
			ecommerce_designLayoutUpdate();
		});
	}

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutAddXBlock(oSrc, e) {
	var uid = "uib" + Math.floor(Math.random() * (999 - 111 + 1) + 111);

	while (_layoutPreviewJQ("#" + uid).length > 0) {
		uid = "uib" + Math.floor(Math.random() * (999 - 111 + 1) + 111)
	}

	_layoutPreviewJQ(oSrc).parents("div.xblockwrapinner").find("div.clear").before("<div id='" + uid + "' class='grid_12 xblock'><div class='xblockinner'><div class='xblocwidgets'></div></div></div>");

	ecommerce_designLayoutInitSortables();
	ecommerce_designLayoutInitResizables();
	ecommerce_designLayoutInitControls();
	ecommerce_designLayoutUpdate();

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutDeleteXBlock(oSrc, e) {
	if (confirm("sure?")) {
		_layoutPreviewJQ(oSrc).parents(".xblock").slideUp(400, function() {
			_layoutPreviewJQ(this).remove();
			ecommerce_designLayoutInitSortables();
			ecommerce_designLayoutUpdate();
		});
	}

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutAddWidget(oSrc, e) {
	var uid = "uib" + Math.floor(Math.random() * (999 - 111 + 1) + 111);

	while (_layoutPreviewJQ("#" + uid).length > 0) {
		uid = "uib" + Math.floor(Math.random() * (999 - 111 + 1) + 111)
	}

	_layoutCurBlock = _layoutPreviewJQ(oSrc).parents(".xblock");;

	$.blockUI({ 
		message: "<iframe id='widgetAdd' frameborder='0' src='ajax.php?action=modules/ecommerce/ajax/admin/ecommerce_settingsWidget&add=1&id=" + uid + "'></iframe>",
		css: { width: '600px', height: '300px', top: '15%', opacity: '.9', backgroundColor: '#ffffff', border: '2px solid #999999' },
		overlayCSS: { backgroundColor: '#aaaaaa' }
	});

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutAddWidgetSave(strId, strXopieCode, strHtmlCode) {
	if (_layoutCurBlock) {
		_layoutCurBlock.find(".xblocwidgets").append("<div class=\"xwidget\">" + strHtmlCode + "</div>");
		$("textarea#ecommerce_layout_general").val($("textarea#ecommerce_layout_general").val() + strXopieCode);

		ecommerce_designLayoutInitSortables();
		ecommerce_designLayoutInitResizables();
		ecommerce_designLayoutInitControls();
		ecommerce_designLayoutUpdate();
	}

	ecommerce_designLayoutEditWidgetClose(false);
}

function ecommerce_designLayoutEditWidget(oSrc, e) {
	var re = new RegExp("<xwidget:(\\S+) id=\"" + _layoutPreviewJQ(oSrc).parents(".xwidget").children(":last").attr("id") + "\">[\\s\\S]*?</xwidget:\\1>", "im");
	var match = false;

	$("#settingsDesignLayoutFrm").find("textarea").each(function(i) {
		match = (!match ? $(this).text().match(re) : match);
	});

	$.blockUI({ 
		message: "<iframe id='widgetEdit' frameborder='0' src='ajax.php?action=modules/ecommerce/ajax/admin/ecommerce_settingsWidget&widget=" + _layoutPreviewJQ(oSrc).parents(".xwidget").children(":last").attr("rel") + "&id=" + _layoutPreviewJQ(oSrc).parents(".xwidget").children(":last").attr("id") + "&xopieCode=" + (match ? encodeURI(match[0]) : "") + "'></iframe>",
		css: { width: '600px', height: '300px', top: '15%', opacity: '.9', backgroundColor: '#ffffff', border: '2px solid #999999' },
		overlayCSS: { backgroundColor: '#aaaaaa' }
	});

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutEditWidgetSave(strId, strXopieCode, strHtmlCode) {
	var re = new RegExp("<xwidget:(\\S+) id=\"" + strId + "\">[\\s\\S]*?</xwidget:\\1>", "im");

	$("#settingsDesignLayoutFrm").find("textarea").each(function(i) {
		$(this).text($(this).text().replace(re, strXopieCode));
	});

	_layoutPreviewJQ("#" + strId).parents(".xwidget").html(strHtmlCode);
	ecommerce_designLayoutInitControls();

	ecommerce_designLayoutEditWidgetClose(false);
}

function ecommerce_designLayoutEditWidgetClose(e) {
	$(this).unblock();
	_layoutCurBlock = false;

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutDeleteWidget(oSrc, e) {
	if (confirm("sure?")) {
		_layoutPreviewJQ(oSrc).parents(".xwidget").slideUp(400, function() {
			_layoutPreviewJQ(this).remove();
			ecommerce_designLayoutInitSortables();
			ecommerce_designLayoutUpdate();
		});
	}

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutSetStyle(sId, sSelector, sValue, bNoApply) {
	if (!_layoutStyles[sId]) {
		_layoutStyles[sId] = {};
	}

	_layoutStyles[sId][sSelector] = sValue;

	if (!bNoApply) {
		_layoutPreviewJQ("#" + sId).css(sSelector, sValue);
	}
}

function ecommerce_designLayoutGetStyle(sId, sSelector) {
	if (_layoutStyles[sId] && _layoutStyles[sId][sSelector]) {
		return _layoutStyles[sId][sSelector];
	} else {
		return "";
	}
}

function ecommerce_designLayoutStyleBlockWrap(oSrc, e) {
	ecommerce_designLayoutStylePopupsHide();

	_layoutCurWrap = _layoutPreviewJQ(oSrc).parents(".xblockwrap");

	iColorPickerSetValue("psbwBgColor", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id"), "background-color").replace("#", ""));
	$("#psbwBgImageRepeat").val(ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id"), "background-repeat"));
	$("#psbwHeight").slider("value", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id"), "height").replace("px", ""));

	$("#popupStyleBlockWrap").css("position", "absolute");
	$("#popupStyleBlockWrap").css("top", ($(oSrc).offset().top + $(oSrc).height()) + "px");
	$("#popupStyleBlockWrap").css("left", ($(oSrc).offset().left + $(oSrc).width()) + "px");
	$("#popupStyleBlockWrap").show();

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStyleBlockWrapHide(e) {
	$("#popupStyleBlockWrap").hide();
	_layoutCurWrap = false;
	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStyleBlockWrapInner(oSrc, e) {
	ecommerce_designLayoutStylePopupsHide();

	_layoutCurWrapInner = _layoutPreviewJQ(oSrc).parents(".xblockwrapinner");
	_layoutCurWrap = _layoutCurWrapInner.parents(".xblockwrap");

	iColorPickerSetValue("psbwiBgColor", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "background-color").replace("#", ""));
	$("#psbwiBgImageRepeat").val(ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "background-repeat"));
	$("#psbwiHeight").slider("value", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "height").replace("px", ""));

	$("#psbwiTextFontFamily").val(ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "font-family"));
	iColorPickerSetValue("psbwiTextColor", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "color").replace("#", ""));
	$("#psbwiTextFontSize").slider("value", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "font-size").replace("%", ""));
	$("#psbwiTextFontWeight").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "font-weight") == "bold" ? true : false));
	$("#psbwiTextFontStyle").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "font-style") == "italic" ? true : false));
	$("#psbwiTextFontDecoration").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner", "text-decoration") == "underline" ? true : false));

	$("#psbwiLinkFontFamily").val(ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "font-family"));
	iColorPickerSetValue("psbwiLinkColor", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "color").replace("#", ""));
	$("#psbwiLinkFontSize").slider("value", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "font-size").replace("%", ""));
	$("#psbwiLinkFontWeight").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "font-weight") == "bold" ? true : false));
	$("#psbwiLinkFontStyle").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "font-style") == "italic" ? true : false));
	$("#psbwiLinkFontDecoration").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a", "text-decoration") == "underline" ? true : false));

	$("#psbwiLinkHoverFontFamily").val(ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "font-family"));
	iColorPickerSetValue("psbwiLinkHoverColor", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "color").replace("#", ""));
	$("#psbwiLinkHoverFontSize").slider("value", ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "font-size").replace("%", ""));
	$("#psbwiLinkHoverFontWeight").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "font-weight") == "bold" ? true : false));
	$("#psbwiLinkHoverFontStyle").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "font-style") == "italic" ? true : false));
	$("#psbwiLinkHoverFontDecoration").attr("checked", (ecommerce_designLayoutGetStyle(_layoutCurWrap.attr("id") + ">.xblockwrapinner a:hover", "text-decoration") == "underline" ? true : false));

	$("#popupStyleBlockWrapInner").css("position", "absolute");
	$("#popupStyleBlockWrapInner").css("top", ($(oSrc).offset().top + $(oSrc).height()) + "px");
	$("#popupStyleBlockWrapInner").css("left", ($(oSrc).offset().left + $(oSrc).width()) + "px");
	$("#popupStyleBlockWrapInner").show();

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStyleBlockWrapInnerHide(e) {
	$("#popupStyleBlockWrapInner").hide();
	_layoutCurWrapInner = false;
	_layoutCurWrap = false;
	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStyleBlock(oSrc, e) {
	ecommerce_designLayoutStylePopupsHide();

	_layoutCurBlock = _layoutPreviewJQ(oSrc).parents(".xblock");

	iColorPickerSetValue("psbBgColor", ecommerce_designLayoutGetStyle(_layoutCurBlock.attr("id") + ">.xblockinner", "background-color").replace("#", ""));
	$("#psbBgImageRepeat").val(ecommerce_designLayoutGetStyle(_layoutCurBlock.attr("id") + ">.xblockinner", "background-repeat"));
	$("#psbHeight").slider("value", ecommerce_designLayoutGetStyle(_layoutCurBlock.attr("id") + ">.xblockinner", "height").replace("px", ""));
	$("#psbPaddingTop").slider("value", ecommerce_designLayoutGetStyle(_layoutCurBlock.attr("id") + ">.xblockinner", "padding-top").replace("px", ""));
	$("#psbPaddingLeft").slider("value", ecommerce_designLayoutGetStyle(_layoutCurBlock.attr("id") + ">.xblockinner", "padding-left").replace("px", ""));

	$("#popupStyleBlock").css("position", "absolute");
	$("#popupStyleBlock").css("top", ($(oSrc).offset().top + $(oSrc).height()) + "px");
	$("#popupStyleBlock").css("left", ($(oSrc).offset().left + $(oSrc).width()) + "px");
	$("#popupStyleBlock").show();

	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStyleBlockHide(e) {
	$("#popupStyleBlock").hide();
	_layoutCurBlock = false;
	return (e ? cancelEvent(e) : false);
}

function ecommerce_designLayoutStylePopupsHide() {
	if (_layoutCurWrap) {
		ecommerce_designLayoutStyleBlockWrapHide(false);
	}

	if (_layoutCurWrapInner) {
		ecommerce_designLayoutStyleBlockWrapInnerHide(false);
	}

	if (_layoutCurBlock) {
		ecommerce_designLayoutStyleBlockHide(false);
	}
}

function ecommerce_designLayoutUpdate() {
	var xLayout, xBlockWrap, xBlockWrapInner, xBlock, xBlockInner, xBlockWidgets, xWidget, xPageContent, tmp;
	var isPageContent = false, containsPageContent = false;

	xLayout = '<div id="xlayout" class="xlayout">';
	xPageContent = '';

	_layoutPreviewJQ("#xlayout").find(".xblockwrap").each(function(bw) {
		xBlockWrap = '<div id="' + _layoutPreviewJQ(this).attr("id") + '" class="' + _layoutPreviewJQ(this).attr("class") + '">';

		_layoutPreviewJQ(this).find(".xblockwrapinner").each(function(bwi) {
			xBlockWrapInner = '<div class="' + _layoutPreviewJQ(this).attr("class").replace("ui-sortable", "") + '">';

			_layoutPreviewJQ(this).find(".xblock").each(function(b) {
				xBlock = '<div id="' + _layoutPreviewJQ(this).attr("id") + '" class="' + _layoutPreviewJQ(this).attr("class").replace("ui-resizable", "") + '">';

				_layoutPreviewJQ(this).find(".xblockinner").each(function(bi) {
					xBlockInner = '<div class="' + _layoutPreviewJQ(this).attr("class") + '">';

					_layoutPreviewJQ(this).find(".xblocwidgets").each(function(bw) {
						containsPageContent = false;

						xBlockWidgets = '<div class="' + _layoutPreviewJQ(this).attr("class").replace("ui-sortable", "") + '">';
						tmp = '';
						
						_layoutPreviewJQ(this).find(".xwidget").each(function(xw) {
							isPageContent = (_layoutPreviewJQ(this).attr("id") == "xpagecontent" ? true : false);

							xWidget = '<div ' + (_layoutPreviewJQ(this).attr("id") ? 'id="' + _layoutPreviewJQ(this).attr("id") + '"' : '') + ' class="' + _layoutPreviewJQ(this).attr("class") + '">';

							if (isPageContent) {
								containsPageContent = true;
								xWidget += '<xlayout:content></xlayout:content>';
							} else {
								var re = new RegExp("<xwidget:(\\S+) id=\"" + _layoutPreviewJQ(this).children(":last").attr("id") + "\">[\\s\\S]*?</xwidget:\\1>", "im");
								var match = false;

								$("#settingsDesignLayoutFrm").find("textarea").each(function(i) {
									if (!match) {
										match = $(this).val().match(re);

										if (match) {
											xWidget += match[0];
										}
									}
								});
							}

							xWidget += '</div>';

							tmp += xWidget;
						});		

						if (containsPageContent) {
							xBlockWidgets += '<xlayout:contentLayout></xlayout:contentLayout>';
							xPageContent = tmp;
						} else {
							xBlockWidgets += tmp;
						}
						
						xBlockWidgets += '</div>';

						xBlockInner += xBlockWidgets
					});

					xBlockInner += '<div class="xblockinnerclear">&nbsp;</div>';
					xBlockInner += '</div>';

					xBlock += xBlockInner;
				});

				xBlock += '</div>';

				xBlockWrapInner += xBlock;
			});

			xBlockWrapInner += '<div class="clear">&nbsp;</div>';
			xBlockWrapInner += '</div>';

			xBlockWrap += xBlockWrapInner;
		});

		xBlockWrap += '</div>';

		xLayout += xBlockWrap;
	});

	xLayout += '</div>';

	if (xLayout && xPageContent) {
		$("textarea#ecommerce_layout_general").val(xLayout);
		//[] cal adaptar-ho segons el action actual, creant el textarea si fos necessari
		$("textarea#ecommerce_layoutContent_general").val(xPageContent);
	} else {
		alert("Error parsing xLayout");
	}
}

function ecommerce_designLayoutPreSave() {
	var sStyles = "";

	//layoutStyles
	for (var uid in _layoutStyles) {
		sStyles += "#" + uid + " {";

		for (var selector in _layoutStyles[uid]) {
			sStyles += selector + ":" + _layoutStyles[uid][selector] + ";";
		}

		sStyles += "}\n";
	}

	$("textarea#ecommerce_layoutStyles").val(sStyles);
}

/* labels */
function ecommerce_labelHelp(strBase, strArea) {
	$(".labelImage img").attr("src", strBase + "modules/ecommerce/images/misc/label_" + strArea + ".gif");
}

function ecommerce_labelPreview(strBlock, blnShow) {
	if (blnShow) {
		$("." + strBlock).show();
	} else {
		$("." + strBlock).hide();
	}
}

function ecommerce_toggleLabelsContacts() {
    if ($("#ecommerce_labelsShopContacts").attr("checked")) {
        $("#contacts_cnt").slideDown(200);
    } else {
        $("#contacts_cnt").slideUp(100);
    }
}

/* locales */
function ecommerce_initLocales(intLimit) {
	for (i = 0; i < intLimit; i++) {
		ecommerce_refreshLocale(i);
	}
}

function ecommerce_refreshLocale(intIndex) {
	if ($("#lc_id_" + intIndex).val() && $("#lc_status_" + intIndex).val() == 2) {
		if ($("#lc_review_" + intIndex + " a").attr("href").substring($("#lc_review_" + intIndex + " a").attr("href").length - 1, $("#lc_review_" + intIndex + " a").attr("href").length) == "/") {
			url = $("#lc_review_" + intIndex + " a").attr("href") + $("#lc_id_" + intIndex).val();
		} else {
			url = $("#lc_review_" + intIndex + " a").attr("href").substring(0, $("#lc_review_" + intIndex + " a").attr("href").length - 5) + $("#lc_id_" + intIndex).val();
		}

		$("#lc_review_" + intIndex + " a").attr("href", url);
		$("#lc_review_" + intIndex + " a").html(url);
		$("#lc_review_" + intIndex).show();
	} else {
		$("#lc_review_" + intIndex).hide();
	}
}

function ecommerce_checkDefaultLocale(intIndex) {
	$("#locales").find("select").each(function(i) {
		if ($(this).attr("id") != "lc_id_" + intIndex && $(this).attr("id") != "lc_status_" + intIndex) {
			$(this).attr("disabled", false);
		} else {
			if ($(this).attr("id") == "lc_status_" + intIndex) {
				$(this).val("1");
				ecommerce_refreshLocale(intIndex);
			}
			$(this).attr("disabled", true);
		}
	});
}

/* paymethods */
function ecommerce_togglePayMethodType() {
	if ($("#costType").val() == "ECOMMERCE_PAYMETHOD_COST_TYPE_PERCENT") {
		$("#minmax_cnt").slideDown(200);
	} else {
		$("#minmax_cnt").slideUp(100);
	}
}

/* promoCodes */
function ecommerce_togglePromoCodeType() {
	if ($("#discountType").val() == "ECOMMERCE_PROMOCODE_TYPE_FREE") {
		$("#promoCodeAmount").hide();
	} else {
		$("#promoCodeAmount").show();
	}
}

/* discounts */
function ecommerce_toggleDiscountApplyTo() {
	$("#applyToOptions").children().hide();
	if ($("#applyTo").val()) {
		$("#" + $("#applyTo").val() + "Cnt").slideDown(300);
	}
}

function ecommerce_toggleShowDiscount(el) {
	if ($(el).val()>0) {
		$('#showDiscountDiv').slideUp();
	} else {
		$('#showDiscountDiv').slideDown();
	}
}

/* homeMessage */
function ecommerce_homeMessageShow(objEvent) {
	$("#homeMessageShopStart").fadeIn(400);

	return cancelEvent(objEvent);
}

function ecommerce_homeMessageHide(objEvent) {
	$("#homeMessageShopStart").fadeOut(400);

	return cancelEvent(objEvent);
}

/* export */
function ecommerce_toggleExportFormat(blnPdfDisabled) {
    if ($("#format").val() == "ECOMMERCE_EXPORT_FORMAT_PDF") {
        $("#pdf_params_cnt").slideDown(200);

		if (blnPdfDisabled) {
			$("#commandExportConfirm").attr("disabled", "disabled");
			$("#commandExportConfirm").addClass("disabledButton");
		}
    } else {
        if ($("#pdf_params_cnt").css("display") == "block") { $("#pdf_params_cnt").slideUp(100); }
		$("#commandExportConfirm").attr("disabled", "");
		$("#commandExportConfirm").removeClass("disabledButton");
    }
}

function ecommerce_checkExportTarget(objForm) {
	$(objForm).attr("target", ($("#format").val() == "ECOMMERCE_EXPORT_FORMAT_HTML" ? "_blank" : ""));
}

/* webmasters */
function ecommerce_GAGetSites(sErrorMsg, sNoneMsg, sValue) {
	if ($("#ecommerce_gaUser").val() && $("#ecommerce_gaPass").val()) {
		$("#fieldEcomerceGASites_cnt").slideUp();
		$("#fieldEcomerceGAGetSites_cnt input").hide();
		$("#fieldEcomerceGAGetSites_cnt img").show();
		$("#ecommerce_gaSite").empty();

		$.ajax({
			type: "GET",
			url: "ajax.php?action=modules/ecommerce/ajax/admin/gaSites",
			data: "ga_email=" + encodeURIComponent($("#ecommerce_gaUser").val()) + "&ga_password=" + encodeURIComponent($("#ecommerce_gaPass").val()),
			async: true,
			dataType: "text",
			success: function (data, textStatus) {
				if (data != "error") {
					eval(data);

					$("#ecommerce_gaSite").append('<option value="">' + sNoneMsg + '</option>');

					jQuery.each(gaAccountData, function(accountId, accountData) {
						if (accountData.profilesCount > 1) {
							$("#ecommerce_gaSite").append('<optgroup label="' + accountData.accountName + '">');
							jQuery.each(accountData.profiles, function(profileId, profileData) {
								$("#ecommerce_gaSite").append('<option value="' + accountId + '|' + profileId + '|' + profileData.webPropertyId + '|' + profileData.title + '" ' + (sValue && sValue == accountId + '|' + profileId + '|' + profileData.webPropertyId + '|' + profileData.title ? 'selected="selected"' : '') + '>&nbsp;&nbsp;' + profileData.title + '</option>');
							});
							$("#ecommerce_gaSite").append('</optgroup>');
						} else {
							jQuery.each(accountData.profiles, function(profileId, profileData) {
								$("#ecommerce_gaSite").append('<option value="' + accountId + '|' + profileId + '|' + profileData.webPropertyId + '|' + profileData.title + '" ' + (sValue && sValue == accountId + '|' + profileId + '|' + profileData.webPropertyId + '|' + profileData.title ? 'selected="selected"' : '') + '>' + profileData.title + '</option>');
							});
						}
						$("#fieldEcomerceGASites_cnt").slideDown();
					});
				} else {
					alert(sErrorMsg);
				}

				$("#fieldEcomerceGAGetSites_cnt input").show();
				$("#fieldEcomerceGAGetSites_cnt img").hide();
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#fieldEcomerceGAGetSites_cnt input").show();
				$("#fieldEcomerceGAGetSites_cnt img").hide();
				alert(sErrorMsg);
			}
		});
	}
}

/* wizzard */
function toggleTimezone() {
    if ($("#country").val()) {
        var options = $("#country").attr("options");

        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: "action=modules/ecommerce/ajax/countryTimezones&country=" + options[$("#country").attr("selectedIndex")].getAttribute("rel"),
            async: true,
            dataType: "text",
            success: function (data, textStatus) {
                eval("data=" + data);
                $("#timezone").empty();

                jQuery.each(data, function(timezone, diff) {
                    $("#timezone").append($("<option value='" + diff + "'>" + timezone + "</option>"));
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error en la petición AJAX (" + errorThrown + "): " + textStatus);
            }
        });
    }
}

/* newsletter */
function ecommerce_newsletterListBriefPreview(sIdDest, freeAddressesCount) {
	$("#" + sIdDest).html("Loading...");
	ecommerce_newsletterListBrief(sIdDest, $("#clientsLocale").val(), $("#clientsCountry").val(), $("#clientsSignupIni").val(), $("#clientsSignupEnd").val(), $("#clientsNewsletter").val(), $("#clientsBuyed").val(), freeAddressesCount, true, false, false);
}

function ecommerce_newsletterListBriefPreviewNL(sIdDest, freeAddressesCount) {
	$("#" + sIdDest).html("Loading...");
	ecommerce_newsletterListBrief(sIdDest, $("#nl_clientsLocale").val(), $("#nl_clientsCountry").val(), $("#nl_clientsSignupIni").val(), $("#nl_clientsSignupEnd").val(), $("#nl_clientsNewsletter").val(), $("#nl_clientsBuyed").val(), freeAddressesCount, true, false, false);
}

function ecommerce_newsletterListBriefPreviewById(sIdDest, iId) {
	$("#" + sIdDest).html("Loading...");
	ecommerce_newsletterListBrief(sIdDest, false, false, false, false, false, false, false, true, iId, false);
}

function ecommerce_newsletterListBrief(sIdDest, clientsLocale, clientsCountry, clientsSignupIni, clientsSignupEnd, clientsNewsletter, clientsBuyed, freeAddressesCount, unformatDates, idNewsletterList, event) {
	var data = "action=modules/ecommerce/ajax/admin/newsletterListsBrief";

	if (idNewsletterList) {
		data += "&idNewsletterList=" + idNewsletterList;
	} else {
		data += (clientsLocale ? "&clientsLocale=" + clientsLocale : "");
		data += (clientsCountry ? "&clientsCountry=" + clientsCountry : "");
		data += (clientsSignupIni ? "&clientsSignupIni=" + clientsSignupIni : "");
		data += (clientsSignupEnd ? "&clientsSignupEnd=" + clientsSignupEnd : "");
		data += (clientsNewsletter ? "&clientsNewsletter=" + clientsNewsletter : "");
		data += (clientsBuyed ? "&clientsBuyed=" + clientsBuyed : "");
		data += (freeAddressesCount ? "&freeAddressesCount=" + freeAddressesCount : "");
		data += (unformatDates ? "&unformatDates=1" : "");
	}

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: data,
        async: true,
        dataType: "html",
        success: function (data, textStatus) {
            $("#" + sIdDest).html(data);
        }
    });

    return (event ? cancelEvent(event) : false);
}

function ecommerce_setCampaignList(oSrc) {
    if ($("#newsletterListMode_exists").attr("checked")) {
        $(".addNewsletterList_new").slideUp(200);
		$("#newsletterListStats").html("&nbsp;");
    } else {
        $(".addNewsletterList_new").slideDown(200);
        $("#idNewsletterList").val("");
		$("#newsletterListStats").html("&nbsp;");
    }
}

function ecommerce_campaignInitUploader(sId, sSize) {
	var params = {
		action: "ajax.php",
		name: "upload_image",
		data: {
			action: "modules/ecommerce/ajax/admin/ecommerce_newsletterUpload",
			size: sSize
		},
		onSubmit: function(file, extension) {
			$("#" + sId + " div.load").hide();
			$("#" + sId + " div.loaded").hide();
			$("#" + sId + " div.upload").show();
		},
		onComplete: function(file, response) {
			$("#" + sId + " div.upload").hide();
		},
		onError: function(file, response){
			if (response.indexOf("success:") == 0) {
				$("#" + sId + " div.loaded input").val("/userFiles/ecommerce/newsletter/" + response.substr(8));
				$("#" + sId + " div.loaded img").attr("src", "/userFiles/ecommerce/newsletter/" + response.substr(8));
				$("#" + sId + " div.loaded").show();
			} else {
				alert(response);
			}
		}
	};

	$.ajax_upload("#" + sId + " div.load a", params);
	$.ajax_upload("#" + sId + "_edit", params);
}

function ecommerce_campaignShowImageLink(oSrc, event) {
	$(oSrc).parents(".imageActions").find("div.imgLink").slideDown(300);
	return (event ? cancelEvent(event) : false);
}

function ecommerce_campaignAddBlock(sType, event) {
	var d = new Date;
	var rand = d.getTime();
	var content = $("#" + sType + "_template > div.emailBox").html();
	content = content.replace(/#RAND#/g, rand);

	$("#NLBody").prepend("<div id='emailBox_" + rand + "' class='emailBox' style='display:none;'>" + content + "</div>");
	$("#emailBox_" + rand).slideDown(400, function() {
		if (sType == "ECOMMERCE_CAMPAIGN_CONTENT_TYPE_I") {
			ecommerce_campaignInitUploader("image1_" + rand, "big");
		} else {
			if ($("#image1_" + rand).attr("id")) {
				ecommerce_campaignInitUploader("image1_" + rand, "small");
			}

			if ($("#image2_" + rand).attr("id")) {
				ecommerce_campaignInitUploader("image2_" + rand, "small");
			}

			if ($("#text1_" + rand).attr("id")) {
				tinyMCE.execCommand("mceAddControl", true, "text1_" + rand);
			}

			if ($("#text2_" + rand).attr("id")) {
				tinyMCE.execCommand("mceAddControl", true, "text2_" + rand);
			}
		}

		$("div.NLBody").sortable("refresh");
	});

	return (event ? cancelEvent(event) : false);
}

function ecommerce_campaignDeleteBlock(oSrc, event) {
	$(oSrc).parents(".emailBox").slideUp(200, function() {
		$(this).empty();
	});

	return (event ? cancelEvent(event) : false);
}

function ecommerce_campaignToggleInfo(event) {
	if ($(".NLhelppInfo").css("display") == "block") {
		$(".NLhelppInfo").slideUp(200);
	} else {
		$(".NLhelppInfo").slideDown(400);
	}

	return (event ? cancelEvent(event) : false);
}

function ecommerce_sendCampaignConfirm(sConfirm, event) {
	if (confirm(sConfirm)) {
		return true;
	}

	return cancelEvent(event);
}

/* products import */
function ecommerce_productsImportUploadValidate(sErrorMsg, sWarningImagesMsg, sDataExtensionError, sImagesExtensionError, event, token) {
	var fileData = ($("#fileData").val().substring($("#fileData").val().lastIndexOf(".")+1)).toLowerCase();
	var fileData2 = ($("#fileData2").val().substring($("#fileData2").val().lastIndexOf(".")+1)).toLowerCase();
	var fileImages = ($("#fileImages").val().substring($("#fileImages").val().lastIndexOf(".")+1)).toLowerCase();
	
	if ($("#importData:checked").length&&fileData || $("#importDataImages:checked").length&&fileData2) {
		if (($("#importData:checked").length&&!(fileData=="csv"||fileData=="xls"||fileData=="xlsx")) || ($("#importDataImages:checked").length&&!(fileData2=="csv"||fileData2=="xls"||fileData2=="xlsx"))) {
			alert(sDataExtensionError);
			return cancelEvent(event);
		}
		if ($("#importDataImages:checked").length&&!fileImages) {
			if (!confirm(sWarningImagesMsg)) {
				return cancelEvent(event);
			}
		} else {
			if ($("#importDataImages:checked").length&&fileImages!="zip") {
				alert(sImagesExtensionError);
				return cancelEvent(event);
			}
		}
		//$("#localFrm").submit();
		var timer;
		timer = setTimeout(function() { ecommerce_productsImportUploadTimer(timer, token); }, 3000);
		$("#mainContent").hide();
		$("#uploading").show();
		return true;
	} else {
		alert(sErrorMsg);
		return cancelEvent(event);
	}
}

function ecommerce_productsImportUploadTimer(oTimer, sToken) {
	var data = "action=modules/ecommerce/ajax/admin/productsImportInfo&token=" + sToken;

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: data,
        async: true,
        dataType: "text",
        success: function (data, textStatus) {
			if (data == "uploading") {
				if (oTimer) {
					oTimer = setTimeout(function() { ecommerce_productsImportUploadTimer(oTimer, sToken); }, 3000);
				}
			} else {
				if (oTimer) {
					clearTimeout(oTimer);
				}

				$("#localFrm").submit();
			}
        }
    });
}

function ecommerce_productsImportConfirmSelectedUpdate(event, sErrorDuplicatedField) {
	var val = $(event.target).val();
	var id = parseInt($(event.target).attr("id").substr(7))+1;
	if (val=="") {
		$("table.dataTable1>tbody>tr:gt(0)>td:nth-child(" + id + ")").removeClass("selected");
	} else {
		if (val=="image" || $("table.dataTable1>tbody>tr:eq(0)>th>select>option[value='" + val + "']:selected").length==1) {
			$("table.dataTable1>tbody>tr:gt(0)>td:nth-child(" + id + ")").addClass("selected");
		} else {
			$("table.dataTable1>tbody>tr:gt(0)>td:nth-child(" + id + ")").removeClass("selected");
			$(event.target).val("");
			alert(sErrorDuplicatedField + " " + $(".dataTable1 tbody tr[:1] th select option[value='" + val + "']").html());
		}
	}
}

function ecommerce_productsImportConfirmValidate(sErrorMissingFields, sWarningUpdateOnly, sErrorDuplicatedField, sWarningNoImagesSelected, sIdLocale, event) {
	var internalReference = false;
	var name = false;
	var category_name = false;
	var other_field = false;
	var error = false;
	var image = !($("option[value='image']").length);
	
	$(".dataTable1 tbody tr[:1] th select").each(function(index, element) {

		if (element.value != "" && element.value != "image") {
			if ($(".dataTable1 tbody tr[:1] th select[value='" + element.value + "']").length > 1) {
				alert(sErrorDuplicatedField + " " + $(".dataTable1 tbody tr[:1] th select option[value='" + element.value + "']").html());
				error = true;
				return cancelEvent(event);
			}
		}
		
		if (element.value == "image") {
			image = true;
		}

		if (element.value == "internalReference") {
			internalReference = true;
		} else {
			if (element.value == "name_" + sIdLocale) {
				name = true;
			} else if (element.value == "category_name_" + sIdLocale) {
				category_name = true;
			}
			if (element.value) {
				other_field = true;
			}
		}
	});
	
	if (error) {
		return cancelEvent(event);
	}
	if (!internalReference || !other_field) {
		alert(sErrorMissingFields);
		return cancelEvent(event);
	} else {
		if (!name || !category_name) {
			if (!confirm(sWarningUpdateOnly)) {
				return cancelEvent(event);
			}
		} else {
			if (!image) {
				if (!confirm(sWarningNoImagesSelected)) {
					return cancelEvent(event);
				}
			}
		}
	}

	return true;
}

function ecommerce_productsImportGetInfo(oTimer, sToken, bOptions) {
	var data = "action=modules/ecommerce/ajax/admin/productsImportInfo&token=" + sToken;
	$("#loadingImport").show();
	$("#preview").hide();

	if (bOptions) {
		data += $("#" + bOptions).serialize();
	}

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: data,
        async: true,
        dataType: "text",
        success: function (data, textStatus) {
			if (data.split("##")[0] == "error") {
				if (oTimer) {
					clearTimeout(oTimer);
				}

				$("#uploading").hide();
				$("#options").hide();
				$("#" + data.split("##")[1]).show();
				$("#options-error").show();

			} else if (data == "uploading") {
				if (oTimer) {
					oTimer = setTimeout(function() { ecommerce_productsImportGetInfo(oTimer, sToken, bOptions); }, 3000);
				}
			} else {
				if (oTimer) {
					clearTimeout(oTimer);
				}

				$("#uploading").hide();
				$("#loadingImport").hide();
				$("#preview").show();
				$("#preview").html(data);
				ecommerce_productsImportFirstRow();

				$("#options").show();
			}
        }
    });
}

function ecommerce_productsImportFirstRow() {
	if ($("#cpi_importFirstRow").val() == "1") {
		$("#productsImportPreview").find("tr:eq(1)").show();
	} else {
		$("#productsImportPreview").find("tr:eq(1)").hide();
	}
}

function ecommerce_productsImportSetFormat(sFormat) {
	if (sFormat == "CPI_TYPE_CSV") {
		$("#options_csv").show();
	} else {
		$("#options_csv").hide();
	}
}

/* social networks */
function ecommerce_marketingSocialNetworksShowOptions(selector, event) {
	if (event.value>0) {
		$(selector).slideDown();
	} else {
		$(selector).slideUp();
	}
}

function ecommerce_marketingSocialNetworksCustomizeText(selector, selectorTxt, selectorExample, event, text) {
	if ($(event)[0].checked) {
		$(selector).slideDown();
		$(selectorExample).slideUp();
	} else {
		$(selector).slideUp();
		$(selectorExample).slideDown();
		ecommerce_marketingSocialNetworksRestore(selectorTxt, text);
	}
}

function ecommerce_marketingSocialNetworksRestore(selector, text) {
	$(selector).val(text);
}

function ecommerce_marketingSocialNetworksFacebookLogin(mywallText, token, name) {
	$("#facebookNotConfigured").hide();
	$("#facebookConfigured").show();

	$("#facebookMasterToken").val(token);
	if (name) {
		$("#facebookMasterName").html(name);
		$("#ecommerce_socialNetworksFacebookToken").html('<option value="'+token+'" selected="selected">'+name+' ('+mywallText+')</option>');
	} else {
		$("#facebookMasterName").html("-");
		$("#ecommerce_socialNetworksFacebookToken").html('');
	}
}

function ecommerce_marketingSocialNetworksTwitterLogin(mywallText, token, token_secret, name) {
	$("#twitterNotConfigured").hide();
	$("#twitterConfigured").show();
	
	$("#twitterMasterName").html(name);
	$("#twitterName").val(name);
	$("#twitterToken").val(token);
	$("#twitterTokenSecret").val(token_secret);
}

function ecommerce_marketingSocialNetworksFacebookAddPage(token, name) {
	$("#ecommerce_socialNetworksFacebookToken").append('<option value="'+token+'">'+name+'</option>');
}

function ecommerce_marketingSocialNetworksFacebookLogout(message) {
	if (confirm(message)) {
		$("#facebookNotConfigured").show();
		$("#facebookConfigured").hide();

		$("#facebookMasterToken").val("");
	}
}

function ecommerce_marketingSocialNetworksTwitterLogout(message) {
	if (confirm(message)) {
		$("#twitterNotConfigured").show();
		$("#twitterConfigured").hide();

		$("#twitterToken").val("");
	}
}

function ecommerce_marketingSocialNetworksShowEditButton() {
	if ($("#facebookConfigured").is(":visible") || $("#twitterConfigured").is(":visible")) {
		$('#globalButton').show();
	} else {
		$('#globalButton').hide();
	}
}

function ecommerce_marketingSocialNetworksNotPublish(event) {
	$(event.target).siblings().siblings(".optionNo").addClass("optionActive");
	$(event.target).siblings().siblings(".optionYes").removeClass("optionActive");
	$(event.target).siblings().siblings("input[name^='publishToSNUser_']").val("0");
	
	return cancelEvent(event);
}

function ecommerce_marketingSocialNetworksPublish(event) {
	$(event.target).siblings().siblings(".optionNo").removeClass("optionActive");
	$(event.target).siblings().siblings(".optionYes").addClass("optionActive");
	$(event.target).siblings().siblings("input[name^='publishToSNUser_']").val("1");
	
	return cancelEvent(event);
}

function ecommerce_marketingSocialNetworksCheckStock(event) {
	if (($("#stockType_original").val() == "ECOMMERCE_PRODUCTS_STOCK_NEVER" ||
		$("#stockType_original").val() == "ECOMMERCE_PRODUCTS_STOCK_SOON" ||
		$("#stockType_original").val() == "ECOMMERCE_PRODUCTS_STOCK_ONDEMAND" ||
		(($("#stockType_original").val() == "ECOMMERCE_PRODUCTS_STOCK_UNITS" || $("#stockType_original").val() == "") && $("#stock_original").val()==0)) &&
		($("#stockType").val() == "ECOMMERCE_PRODUCTS_STOCK_ALWAYS" ||
		(($("#stockType").val() == "ECOMMERCE_PRODUCTS_STOCK_UNITS" || $("#stockType").val() == "") && $("#stock").val()>0))) {
			$("#ECOMMERCE_SNG_NEW_STOCKGlobalDiv").show();
			$("input[name='publishToSN_ECOMMERCE_SNG_NEW_STOCK']").val("1");
	} else {
		$("#ECOMMERCE_SNG_NEW_STOCKGlobalDiv").hide();
		$("input[name='publishToSN_ECOMMERCE_SNG_NEW_STOCK']").val("0");
	}
}

function ecommerce_marketingSocialNetworksCheckPrice(event) {
	var newPrice = $("#price").val();
	if (newPrice == "") {
		newPrice = "0";
	}
	newPrice = parseFloat(newPrice.replace(",", ""));
	var oldPrice = $("#price_original").val();
	if (oldPrice == "") {
		oldPrice = "0";
	}

	if (newPrice < oldPrice) {
			$("#ECOMMERCE_SNG_DECREASE_PRICEGlobalDiv").show();
			$("input[name='publishToSN_ECOMMERCE_SNG_DECREASE_PRICE']").val("1");
	} else {
		$("#ECOMMERCE_SNG_DECREASE_PRICEGlobalDiv").hide();
		$("input[name='publishToSN_ECOMMERCE_SNG_DECREASE_PRICE']").val("0");
	}
}

function ecommerce_marketingSocialNetworksCheckOffer(event) {
	if (($("#ECOMMERCE_PRODUCTS_OPTION_BARGAIN")[0].checked) && ($("#options_original").val().indexOf("ECOMMERCE_PRODUCTS_OPTION_BARGAIN")==-1)) {
			$("#ECOMMERCE_SNG_NEW_OFFERGlobalDiv").show();
			$("input[name='publishToSN_ECOMMERCE_SNG_NEW_OFFER']").val("1");
	} else {
		$("#ECOMMERCE_SNG_NEW_OFFERGlobalDiv").hide();
		$("input[name='publishToSN_ECOMMERCE_SNG_NEW_OFFER']").val("0");
	}
}

function ecommerce_marketingSocialNetworksCheckClosed(event) {
	if (($("#ecommerceClosed").val()==""||$("#ecommerceClosed").val()=="0")&&$("#ecommerceClosed_original").val()=="1") {
		$("#ECOMMERCE_SNG_SHOP_ONLINEGlobalDiv").show();
		$("input[name='publishToSN_ECOMMERCE_SNG_SHOP_ONLINE']").val("1");
	} else {
		$("#ECOMMERCE_SNG_SHOP_ONLINEGlobalDiv").hide();
		$("input[name='publishToSN_ECOMMERCE_SNG_SHOP_ONLINE']").val("0");
	}
	
	if (($("#ecommerceClosed_original").val()==""||$("#ecommerceClosed_original").val()=="0")&&$("#ecommerceClosed").val()=="1") {
		$("#ECOMMERCE_SNG_SHOP_OFFLINEGlobalDiv").show();
		$("input[name='publishToSN_ECOMMERCE_SNG_SHOP_OFFLINE']").val("1");
	} else {
		$("#ECOMMERCE_SNG_SHOP_OFFLINEGlobalDiv").hide();
		$("input[name='publishToSN_ECOMMERCE_SNG_SHOP_OFFLINE']").val("0");
	}
}

//orders
function ecommerce_addOrderDetail(event) {
    var oTemplate = $("#ordersDetailTemplate");
    var sTemplate = "<tr>" + oTemplate.html() + "</tr>";

    oTemplate.before($(sTemplate));
	initDetails();
	
    return cancelEvent(event);
}

function ecommerce_deleteOrderDetail(event) {
	$(event.target).parents("tr").remove();

	if ($("form#ordersDetailsFrm>table>tbody>tr").length<=3) {
		return ecommerce_addOrderDetail(event);
	}
	
	return cancelEvent(event);
}

function ecommerce_deleteOrderDetailPromoCode(event) {
	$(event.target).parents("table").remove();

	return cancelEvent(event);
}
