function ecShopAddLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}
// Start: background image height change
function getPageHeight(){
	var bodyContainer = document.getElementById('body_container');
    if(bodyContainer){
    	bodyContainer.style.height = '';
    	var h=getPageSize();
    	if(h[1] < 1200)
    		document.getElementById('body_container').style.height = h[1] + 'px';
    }
}
ecShopAddLoadEvent(getPageHeight);
// End: background image height change

function ecShopGetFrameContent(id, html) {
    var divObj = document.getElementById(id);

    if (divObj) {
        ReplaceContent(id, html);
    }
}

function ecShopReturnHost() {
    return _ecshopHost;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(cookieName) {
    var cookieVal = "";

    if (document.cookie.length > 0) {
        cookieStart = document.cookie.indexOf(cookieName + "=");

        if (cookieStart != -1) {
            cookieStart = cookieStart + cookieName.length + 1;
            cookieEnd = document.cookie.indexOf(";", cookieStart);
            if (cookieEnd == -1) cookieEnd = document.cookie.length;

            cookieVal = unescape(document.cookie.substring(cookieStart, cookieEnd));
        }
    }

    if (cookieVal == null || cookieVal == "null")
        cookieVal = "";

    return cookieVal;
}

function emulateAttachEvent() {
    HTMLDocument.prototype.attachEvent = HTMLElement.prototype.attachEvent = function(eventName, eventHandler) {
        var shortTypeName = eventName.replace(/on/, "");
        eventHandler._ieEmuEventHandler = function(e) {
            window.event = e;
            return eventHandler();
        };
        this.addEventListener(shortTypeName, eventHandler._ieEmuEventHandler, false);
    };
    HTMLDocument.prototype.detachEvent = HTMLElement.prototype.detachEvent = function(eventName, eventHandler) {
        var shortTypeName = eventName.replace(/on/, "");
        if (typeof eventHandler._ieEmuEventHandler == "function")
            this.removeEventListener(shortTypeName, eventHandler._ieEmuEventHandler, false);
        else
            this.removeEventListener(shortTypeName, eventHandler, true);
    };
}

function formatNumber(number) {
    var isCulture = Sys.CultureInfo._parse('{"name":"","numberFormat":{"CurrencyDecimalDigits":0,"CurrencyDecimalSeparator":",","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":".","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":0,"NumberDecimalSeparator":",","NumberGroupSeparator":".","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":",","PercentGroupSeparator":".","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}');

    return Math.round(number)._toFormattedString('n0', isCulture)
}

function HtmlEncode(text) {
    return text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
}



function ecShopHideAndShow(objName, pos) {
    var obj;
    var clsName;

    for (var i = 1; document.getElementById(objName + i) != null; i++) {
        obj = document.getElementById(objName + i);

        if (pos == i) {
            showObject(obj);
        }
        else {
            hideObject(obj)
        }
    }
}

function getSelectedValue(a){
    /*This function returns the value of the radio button checked, if nothing is checked then returns -1*/
    var b = document.getElementsByName(a);
    var r = "";
    for(i=0;i<b.length;i++){
        if(b[i].checked){
            return b[i].value;
        } else if(b[i].defaultChecked) {
            r = b[i].value;
        }
    }
    if(r.length > 0)
        return r;
    else
        return-1;
}
function getSelectedObj(a){
    /*This function returns the value of the radio button checked, if nothing is checked then returns -1*/
    var b = document.getElementsByName(a);
    var r = "";
    for(i=0;i<b.length;i++){
        if(b[i].checked) {
            return b[i];
        } else if(b[i].defaultChecked) {
            r = b[i];
        }
    }
    if(typeof(r) == "object")
        return r;
    else
        return-1;
}

function replaceBreaks(str) {
    var regExpLt = /(&lt;)/g;
    var regExpGt = /(&gt;)/g;

    return str.replace(regExpGt, ">").replace(regExpLt, "<");
}


function ReplaceHtml(containerId, html, pos) {
    var container = document.getElementById(containerId);

    if (pos == undefined) {
        pos = 0;
    }

    if (container) {
        var parent = container.parentNode;

        var tempElement = document.createElement("div");
        tempElement.setAttribute("id", "temp_replacement_" + pos);
        tempElement.style.display = "none";

        tempElement.innerHTML = html.replace(containerId, containerId + "_temp_" + pos);
        parent.appendChild(tempElement);

        var cleanHtml = document.getElementById(containerId + "_temp_" + pos).innerHTML;

        container.innerHTML = cleanHtml;
        parent.removeChild(tempElement);
    }
}

function ecShopGetStyle(el, styleProp) {
    var x = document.getElementById(el);

    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);

    return y;
}

function LoadCaptcha() {
    ecShop.Web.Soap.ecShopWS.GetCaptcha(OnSuccessCaptcha);
}

function OnSuccessCaptcha(results) {
    var s1 = results[0];
    var s2 = results[1];
    var s3 = results[2];

    var captcha = document.getElementById("captchaimg");

    if (captcha) {
        captcha.src = s3 + '/upload/files/templates/controls/CaptchaImage.aspx?height=100&width=200&text=' + s1;
        document.getElementById("captchahash").value = s2;
    }
}

function OnError(error) {
    if (error.get_message().indexOf("ecshop-error:") > -1) {
        var word = error.get_message().replace("ecshop-error:", "");

        CreateError(ecTranslate(word));
    } else {
        CreateError(error.get_message());
    }
    DeleteUpdate();
}

function ecTranslate(word) {
    var lang = readCookie(_ecshopLangCookie);

    if (lang == "" || lang == null)
        lang = _ecshopDefaultLang;

   
    try {
        return _ecTranslate(word + "." + lang);
    } catch (err) {
        return word + "[JSERR]";
    }
}

function ecShopGetCurrentLang() {
    var lang = readCookie(_ecshopLangCookie);

    if (lang == "" || lang == null)
        lang = _ecshopDefaultLang;

    return lang;
}

function disable(id) {
    hideObject(id);
}

function enable(id) {
    showObject(id);
}

function ReplaceContent(elementId, html) {
    var container = document.getElementById(elementId);

    if (container != null) {
        container.innerHTML = html;
    }
}

function LoadPartialRender() {
    var render = readCookie("ecshoppartialrender" + _ecshopWebsiteId);

    if (render != null && render.length > 0) {
        var rendering = render.split("|");

        if (rendering.length > 2) {
            var anchors = document.getElementsByTagName("a");

            var currentUrl = document.location.href;
            var currentLang = ecShopGetCurrentLang();

            var href = rendering[1];

            
            var languageIndex = href.indexOf("lang=");

            var startIndex = languageIndex + 5;
            var endIndex = languageIndex + 7;

            if (href.length < endIndex) {
                endIndex = href.length;
            }

            var selectedLang = href.substring(startIndex, endIndex);

            if (selectedLang != currentLang) {
                href = href.replace("lang=" + selectedLang, "lang=" + currentLang);
            }
           
            var previousUrl = "";

            if (rendering[2].indexOf("&category_name=") > -1 || currentUrl.indexOf("&category_name=") > -1) {
                var removeCatNamePrev = rendering[2].split("&category_name=");
                var removeCatNameCrnt = currentUrl.split("&category_name=");
                previousUrl = removeCatNamePrev[0];
                currentUrl = removeCatNameCrnt[0];
            } else {
                var previousUrl = rendering[2];
            }

            if (currentUrl == previousUrl) {
                var divId = "pr_225_130_" + rendering[0];
                var divObj = document.getElementById(divId);
                webSite = divObj.getAttribute("webSite");
                siteName = divObj.getAttribute("siteName");
                handlerPage = "/" + siteName + staticHandlerPath;
                tagId = divId;

                getContent("", href, divId, "");
            } else {
                createCookie("ecshoppartialrender" + _ecshopWebsiteId, "", 0);
                showObject("ecshop_product_container");
            }
        } else {
            showObject("ecshop_product_container");
        }
    } else {
        showObject("ecshop_product_container");
    }
}

function PrePartialRender(anchor, modulePosition) {
    var ahref = anchor.href;
    createCookie("ecshoppartialrender" + _ecshopWebsiteId, modulePosition + "|" + ahref + "|" + document.location.href, 1);
}

function partialRenderLoading() {
    if (!_ecshopPreLoading) {
        CreateUpdate(ecTranslate("product-messages.product-updating-list"));
        _ecshopPreLoading = false;
    }
}

function partialRenderLoaded() {
    DeleteUpdate();

    var lastOpenedProduct = readCookie("ecshoptable" + _ecshopWebsiteId);

    if (lastOpenedProduct != "") {
        oldContainer = document.getElementById("ecshopfx_detail_" + lastOpenedProduct);
        lineContainer = document.getElementById("ecshopfx_table_line_" + lastOpenedProduct);

        if (oldContainer) {
            showObject(oldContainer);
            lineContainer.className = "line with_bkg";
        }

        _ecshopLastOpenedProduct = lastOpenedProduct;
        createCookie("ecshoptable" + _ecshopWebsiteId, "", 0);
    }

    showObject("ecshop_product_container");
    // Start: background image height change
    getPageHeight();
    // End: background image height change
}


function trim(text) {
    return text.replace(/^\s*|\s*$/g, "");
}



var _zIndex = 500;

function createPopup_new(html, nameOfClass, id) {
    var container = document.getElementById("ecshop-hover_" + id);

    if (container == null) {
        container = document.createElement("div");
    } else {
        container.innerHTML = "";
    }

    container.className = "ecshop_hover_window";
    container.setAttribute("id", "ecshop-hover_" + id);
    container.style.zIndex = _zIndex++;

    var popup = document.createElement("div");
    popup.className = "ecshop_hover_content " + nameOfClass;
    popup.setAttribute("id", "ecshop-content_" + id);


    var closeWindow = document.createElement("div");
    closeWindow.className = "ecshop_hover_close";
    closeWindow.innerHTML = '<a href="javascript:removePopup(\'' + id + '\')" class="dd_close pop_up" title="' + _esClose + '"><span>' + _esClose + '</span></a>';

    var content = document.createElement("div");
    content.className = "pop_content";
    content.innerHTML = html;

    var pop_top = document.createElement("div");
    pop_top.className = "pop_top";

    var pop_bot = document.createElement("div");
    pop_bot.className = "pop_bot";

    var pop_cover = document.createElement("div");
    pop_cover.className = "pop_cover";

    popup.appendChild(pop_top);
    pop_cover.appendChild(content);
    popup.appendChild(pop_cover);
    popup.appendChild(closeWindow);
    popup.appendChild(pop_bot);


    container.appendChild(popup);

    var parent = document.body;
    parent.insertBefore(container, parent.firstChild);
}

function removePopup(id) {
    var popup = document.getElementById("ecshop-hover_" + id);

    if (popup) {
        popup.parentNode.removeChild(popup);
    }
}



function CreateError(error, heading) {
	var head ="";
	if(heading == undefined || heading == null)
		head = ecTranslate("common-headings.common-error");
	else
		head = heading;
    var html = '<h2>' + head + '</h2><p>' + error + '</p>';
    createPopup(html, "ecshop_error", "ecshoperror");
}

function CreateConfirmation(header, content, id) {
    var html = '<h2>' + header + '</h2>' + content;

    createPopup(html, "ecshop_confirmation", id);
}

function CreateMessage(header, text, id) {
    var html = '<h2>' + header + '</h2><p>' + text + '</p>';

    createPopup(html, "ecshop_message", id);

    
    setTimeout("FadeItem('ecshop-content_" + id + "','out',1000)", 3000, true);

    
    setTimeout("removePopup('" + id + "')", 5000);
}

function FadeItem(id, direction, speed, deleteItem) {

    if (speed == undefined)
        speed = 1000;

    if (direction == undefined)
        direction = "out";

    if (direction == "in") {
        $("#" + id).fadeIn(speed);
    } else if (direction == "out") {

        if (id == "ecshopfx_dropdown_basket") {
            $("#" + id).fadeOut(speed, function() {
                if (browserName == "Microsoft Internet Explorer") {
                    $('#ecshopfx_dropdown_basket > div:first').removeClass("png_out");
                    $('#ecshopfx_dropdown_basket > div:first').addClass("png_in");
                    $('#ecshopfx_dropdown_basket > div:last').removeClass("png_bottom_out");
                    $('#ecshopfx_dropdown_basket > div:last').addClass("png_bottom_in");
                }
            });
        } else {
            $("#" + id).fadeOut(speed);
        }
    }

  
}

function CreateUpdate(text) {
    var html = '<p>' + text + '</p>';

    createPopup(html, "ecshop_update", "ecshop_update");
}

function DeleteUpdate() {
    removePopup("ecshop_update");
}

function showObject(elementId) {
    var object = null;

    if (typeof (elementId) == "string") {
        object = document.getElementById(elementId);
    } else {
        object = elementId;
    }

    if (object) {
        if (object.className.indexOf(" ecshop_hide") > -1) {
            object.className = object.className.replace(" ecshop_hide", "");
        } else if (object.className.indexOf("ecshop_hide") > -1) {
            object.className = object.className.replace("ecshop_hide", "");
        } else if (object.className.indexOf(" ecshop_obscure") > -1) {
            object.className = object.className.replace(" ecshop_obscure", "");
        } else if (object.className.indexOf("ecshop_obscure") > -1) {
            object.className = object.className.replace("ecshop_obscure", "");
        }

        if (object.style.display == 'none') {
            object.style.display = '';
        }

        if (object.style.visibility == 'hidden') {
            object.style.visibility = '';
        }
    }
}

function obscureObject(elementId) {
    var object = null;

    if (typeof (elementId) == "string") {
        object = document.getElementById(elementId);
    } else {
        object = elementId;
    }

    if (object) {
        if (object.className.indexOf("ecshop_obscure") == -1) {
            if (object.className.length > 0) {
                object.className += " ecshop_obscure";
            } else {
                object.className = "ecshop_obscure";
            }
        }
    }
}

function hideObject(elementId) {
    var object = null;

    if (typeof (elementId) == "string") {
        object = document.getElementById(elementId);
    } else {
        object = elementId;
    }

    if (object) {
        if (object.className.indexOf("ecshop_hide") == -1) {
            if (object.className.length > 0) {
                object.className += " ecshop_hide";
            } else {
                object.className = "ecshop_hide";
            }
        }
    }
}

function deleteObject(elementId) {
    var object = document.getElementById(elementId);

    if (object) {
        var parent = object.parentNode;

        if (parent) {
            object.parentNode.removeChild(object);
        }
    }
}

function toggleObject(elementId) {
    var object = document.getElementById(elementId);

    if (object) {
        if (object.className.indexOf("ecshop_hide") == -1) {
            hideObject(elementId);
        } else {
            showObject(elementId);
        }
    }
}

function overwriteInnerHTML(elementObj, oldText, newText) {

    if (elementObj) {
        if (elementObj.innerHTML.indexOf(oldText) > -1) {
            elementObj.innerHTML = newText;
        } else {
            elementObj.innerHTML = oldText;
        }
    }

}

function ecShopCaptureMouse(e) {
    if (!document.all) {
        _ecshopTempX = e.pageX
        _ecshopTempY = e.pageY
    }
}

function ecShopCaptureHistory(e) {
    if (document.all) { 
        _ecshopTempX = event.clientX
        _ecshopTempY = event.clientY
    }

    if (_ecshopTempY < 1) {
        return ecTranslate("checkout-errors.checkout-navigate-back");
    }
}
