/* Copyright (c) 2003-2011, SearchFit, Inc. All Rights Reserved. */
if (typeof SFUI === "undefined" || !SFUI) { var SFUI = {}; }

// define global variables
var WS_MULTIPART_RESULT_WRAPPER = "ws-multipart-result";
var WS_MULTIPART_RESULT_WRAPPER_IE = "WS-MULTIPART-RESULT";

// invoke the function that has to be executed on every page
executeOnEveryPage_header();

// invoked on every generated webpage (in the <header> section)
function executeOnEveryPage_header() {
    // get an associative array of URL key/value pairs
    var urlArgs = getUrlArguments(window.location);
    // if no referrer then take the referrer of this page and save it as cookie
    var newReferrer = urlArgs["referrer"];
    var referrer = newReferrer ? newReferrer : document.referrer;
    if (referrer != "") {
        referrer_current = getCookie("cookie_scart_referrer");
        if (referrer_current == null) { setCookieAdvanced("cookie_scart_referrer", referrer, 7, '/', null, null); }
    }
    // save scart_affiliate_id url arguments as cookie
    var cookieScartAffiliateId = urlArgs["scart_affiliate_id"];
    if (cookieScartAffiliateId) { setCookieAdvanced("cookie_scart_affiliate_id", cookieScartAffiliateId, 365, '/', null, null); }
    // save referralMemberId url arguments as cookie
    var cookieReferralMemberId = urlArgs["referralMemberId"];
    if (cookieReferralMemberId) { setCookieAdvanced("cookie_referralMemberId", cookieReferralMemberId, 7, '/', null, null); }
    // save pSearchQueryId url arguments as cookie
    var cookiePowerSearchQueryId = urlArgs["pSearchQueryId"];
    if (cookiePowerSearchQueryId) { setCookieAdvanced("cookie_pSearchQueryId", cookiePowerSearchQueryId, 1, '/', null, null); }
    // put all url args into a cookie to pass to the checkout/dynamic pages
    if (urlArgs["length"] > 0) {
        delete urlArgs['referrer'];
        var newCookieUrlArgsStr = "", oldCookieUrlArgsStr = getCookie("cookie_scart_urlArgs");
        var newCookieUrlArgs = getUrlArguments(oldCookieUrlArgsStr);
        for (urlArg in urlArgs) { newCookieUrlArgs[urlArg] = urlArgs[urlArg]; }
        for (newCookieUrlArg in newCookieUrlArgs) { newCookieUrlArgsStr += (newCookieUrlArgsStr != "" ? "&" : "") + newCookieUrlArg + "=" + newCookieUrlArgs[newCookieUrlArg]; }
        if (newCookieUrlArgsStr != "") { setCookieAdvanced("cookie_scart_urlArgs", newCookieUrlArgsStr, 1, '/', null, null); }
    }
}

// invoked on every generated webpage (before the </body> tag)
function executeOnEveryPage_bottom(wsWebsiteEndpoint, wsSCartEndpoint, progressContent) {
    if (document.getElementsByName) {

        // find all select fields for "search by category" and select the appropriate option
        searchby_category_fields = document.getElementsByName("searchby_category");
        if (searchby_category_fields) {
            for (var i = 0; i < searchby_category_fields.length; i++) {
                var searchby_category_field = searchby_category_fields[i];
                if (searchby_category_field.form.searchby_category_defaultIndex) {
                    searchby_category_field.selectedIndex = searchby_category_field.form.searchby_category_defaultIndex.value;
                    continue;
                }
                for (var j = 1; j < searchby_category_field.length; j++) {
                    if (searchby_category_field.options[j].value == current_category_ids_path) {
                        searchby_category_field.options[j].selected = true;
                        break;
                    }
                }
            }
        }

        // handle dynamic include tags
        processDynamicIncludes(wsWebsiteEndpoint, progressContent);
    }
}

function processDynamicIncludes(wsWebsiteEndpoint, progressContent, onAsyncResponseCallback, args) {
    if (typeof args === 'undefined' || args == null) { args = {}; }
    if (wsWebsiteEndpoint == null || typeof wsWebsiteEndpoint == "undefined") { wsWebsiteEndpoint = typeof SFUI != "undefined" && typeof SFUI.ThisAdmin != "undefined" ? SFUI.ThisAdmin.websiteServicesUrl : SFUI.ThisWebsite.getPublicWebsiteService(); }
    var wsSCartEndpoint = typeof SFUI != "undefined" && typeof SFUI.ThisAdmin != "undefined" ? SFUI.ThisAdmin.scartServicesUrl : SFUI.ThisWebsite.getPublicSCartService();

    // find dynamic include tags
    if (progressContent != null) { progressContent = unescapePhp2JavaScriptArgument(progressContent); }
    var dynamic_include_fields = [];
    if (args.targetIncludeId != null) {
        dynamic_include_field = document.getElementById(args.targetIncludeId);
        if (dynamic_include_field != null) { dynamic_include_field.setAttribute("isProcessed", 0); dynamic_include_fields.push(dynamic_include_field); }
    } else {
        dynamic_include_fields = getElementsByTagAndName("div", "dynamic_include");
    }

    // handle dynamic include tags
    if (dynamic_include_fields && dynamic_include_fields.length > 0) {

        // construct web service requests
        var countIncludesToProcessWebsite = 0; var countIncludesToProcessSCart = 0;
        var wsRequest = "action=dynamicInclude"; if (location.hash != "") { wsRequest += "&locationHash=" + location.hash.replace(/^#/, ""); }
        var wsRequestWebsite = wsRequest; var wsRequestSCart = wsRequest + (typeof(scart_session_id) != 'undefined' ? "&targetSessionId=" + scart_session_id : "");
        var targetFieldByIdMapWebsite = new Array(); var targetFieldByIdMapSCart = new Array();
        for (var i = 0; i < dynamic_include_fields.length; i++) {
            var isProcessed = dynamic_include_fields[i].getAttribute("isProcessed");
            if ( ! isProcessed || isProcessed == "0" || args.processAny) {
                var targetService = dynamic_include_fields[i].getAttribute("targetService");
                if (targetService != null && targetService == "cart") {
                    if (args.targetService == null || args.targetService == "cart") {
                        if (progressContent) { dynamic_include_fields[i].innerHTML = progressContent; } else { YAHOO.util.Dom.setStyle(dynamic_include_fields[i], 'opacity', 0.35); }
                        targetFieldByIdMapSCart[dynamic_include_fields[i].id] = dynamic_include_fields[i];
                        wsRequestSCart += "&wsParams[" + dynamic_include_fields[i].id + "]=" + dynamic_include_fields[i].getAttribute("ajaxParams");
                        countIncludesToProcessSCart++;
                    }
                } else if (args.targetService == null || args.targetService == "website") {
                    if (progressContent) { dynamic_include_fields[i].innerHTML = progressContent; }
                    targetFieldByIdMapWebsite[dynamic_include_fields[i].id] = dynamic_include_fields[i];
                    wsRequestWebsite += "&wsParams[" + dynamic_include_fields[i].id + "]=" + dynamic_include_fields[i].getAttribute("ajaxParams");
                    countIncludesToProcessWebsite++;
                }
                dynamic_include_fields[i].setAttribute("isProcessed", "1");
            }
        }

        // make AJAX calls
        if (countIncludesToProcessWebsite > 0 || countIncludesToProcessSCart > 0) {
            if (args.form != null) { YAHOO.util.Connect.setForm(args.form); }
            if (countIncludesToProcessWebsite > 0) {
                var asyncResponseCallback_dynamicInclude = {
                    success: function(o) {
                        var targetFieldByIdMap = o.argument.targetFields;
                        for (var fieldId in targetFieldByIdMap) { setInnerHtmlByMultipartResult(o.responseText, targetFieldByIdMap[fieldId], null, true); }
                        if (onAsyncResponseCallback) { onAsyncResponseCallback(true, o.responseText); }
                        launchJavascript(o.responseText);
                        processDynamicIncludes(wsWebsiteEndpoint);
                    },
                    failure: function(o) {
                        var targetFieldByIdMap = o.argument.targetFields;
                        for (var fieldId in targetFieldByIdMap) { targetFieldByIdMap[fieldId].innerHTML = "Failed dynamicInclude (" + o.status + " " + o.statusText + ")"; }
                        if (onAsyncResponseCallback) { onAsyncResponseCallback(false); }
                    },
                    argument: { targetFields: targetFieldByIdMapWebsite }
                }
                YAHOO.util.Connect.asyncRequest('POST', wsWebsiteEndpoint, asyncResponseCallback_dynamicInclude, wsRequestWebsite);
            }
            if (countIncludesToProcessSCart > 0) {
                var asyncResponseCallback_dynamicInclude = {
                    success: function(o) {
                        var targetFieldByIdMap = o.argument.targetFields;
                        for (var fieldId in targetFieldByIdMap) { setInnerHtmlByMultipartResult(o.responseText, targetFieldByIdMap[fieldId], null, true); YAHOO.util.Dom.setStyle(targetFieldByIdMap[fieldId], 'opacity', 1); }
                        if (onAsyncResponseCallback) { onAsyncResponseCallback(true, o.responseText); }
                        launchJavascript(o.responseText);
                        processDynamicIncludes(wsWebsiteEndpoint);
                    },
                    failure: function(o) {
                        var targetFieldByIdMap = o.argument.targetFields;
                        for (var fieldId in targetFieldByIdMap) { targetFieldByIdMap[fieldId].innerHTML = "Failed dynamicInclude (" + o.status + " " + o.statusText + ")"; YAHOO.util.Dom.setStyle(targetFieldByIdMap[fieldId], 'opacity', 1); }
                        if (onAsyncResponseCallback) { onAsyncResponseCallback(false); }
                    },
                    argument: { targetFields: targetFieldByIdMapSCart }
                }
                YAHOO.util.Connect.asyncRequest('POST', wsSCartEndpoint, asyncResponseCallback_dynamicInclude, wsRequestSCart);
            }
        }
    }
}

function onBeforeWebpageContentBodyTempElement() {
    if (location.hash.indexOf("loadContent.") != -1) {
        document.write('<style type="text/css">#webpage_content_body_temp { display:none; }</style>');
        document.write(unescapePhp2JavaScriptArgument(SFUI.ThisWebsite.msgLoadingContent));
    } else {
        document.write('<style type="text/css">.dynamic_include_staticContent { display:none; }</style>');
    }
}

// invoked when adding a product to the wishlist
function f_add2wishlist_form(pid) { return f_add2wishlist_form_alias1(pid, '0', false, ''); }
function f_add2wishlist_form_alias1(pid, rpid, isCheckOptions, msgSelectOption) {
    var targetForm = document.forms["add2cart_form_" + pid];
    if (isCheckOptions && (SFUI.ThisWebsite.isDisableRequiredOptionsOnAddToWishList == null || SFUI.ThisWebsite.isDisableRequiredOptionsOnAddToWishList == 0)) {
        // check if no option is selected and show appropriate message
        eval("form = this.document.add2cart_form_" + pid + ";");
        objectProductTotals = rpid > 0 ? recalculate_product_price_total_2(form, "_arr[" + rpid + "]") : recalculate_product_price_total(form);
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrderRequired()) { alert(msgSelectOption + objectProductTotals.getMissingRequiredOptionsAsString("\n\n")); return false; }
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrder()) { alert(msgSelectOption); return false; }
    }
    // get some meta info
    add2cartForm = document.forms["add2cart_form_" + pid];
    scart_referrer = getCookie("cookie_scart_referrer");
    scart_affiliate_id = getCookie("cookie_scart_affiliate_id");
    referralMemberId = getCookie("cookie_referralMemberId");
    pSearchQueryId = getCookie("cookie_pSearchQueryId");
    scartUrlArgs = getCookie("cookie_scart_urlArgs");
    // submit the form
    eval("this.document.add2cart_form_" + pid + ".target = '';");
    if (scart_referrer != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_referrer"); newField.setAttribute("value", scart_referrer); targetForm.appendChild(newField); }
    if (scart_affiliate_id != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_affiliate_id"); newField.setAttribute("value", scart_affiliate_id); targetForm.appendChild(newField); }
    if (location.hash != null && location.hash != "") { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_url_hash"); newField.setAttribute("value", location.hash); targetForm.appendChild(newField); }
    if (referralMemberId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "referralMemberId"); newField.setAttribute("value", referralMemberId); targetForm.appendChild(newField); }
    if (pSearchQueryId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "pSearchQueryId"); newField.setAttribute("value", pSearchQueryId); targetForm.appendChild(newField); }
    if (scartUrlArgs != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scartUrlArgs"); newField.setAttribute("value", scartUrlArgs); targetForm.appendChild(newField); }
    eval("this.document.add2cart_form_" + pid + ".form_action_value.value = 'add2wishlist';");
    if (rpid > 0) { eval("this.document.add2cart_form_" + pid + ".rpid.value = '" + rpid + "';"); }
    eval("this.document.add2cart_form_" + pid + ".submit();");
    return true;
}

// invoked when moving a product to the cart
function f_move2cart_form(pid) { return f_move2cart_form_alias1(pid, '0', false, ''); }
function f_move2cart_form_alias1(pid, rpid, isCheckOptions, msgSelectOption) {
    var targetForm = document.forms["add2cart_form_" + pid];
    if (isCheckOptions) {
        // check if no option is selected and show appropriate message
        eval("form = this.document.add2cart_form_" + pid + ";");
        objectProductTotals = rpid > 0 ? recalculate_product_price_total_2(form, "_arr[" + rpid + "]") : recalculate_product_price_total(form);
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrderRequired()) { alert(msgSelectOption + objectProductTotals.getMissingRequiredOptionsAsString("\n\n")); return false; }
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrder()) { alert(msgSelectOption); return false; }
    }
    // get the form and execute the onsubmit
    add2cartForm = document.forms["add2cart_form_" + pid];
    onsubmitResult = add2cartForm.onsubmit();
    if ((typeof(onsubmitResult) == 'undefined') || onsubmitResult) {
        // open window
        window_move2cart = window.open('', 'win_move2cart', 'left=50,screenX=50,top=50,screenY=50,width=500,height=150,scrollbars=0,resizable=1');
        if (window.focus) { window_move2cart.focus(); }
        // show progress animated gif
        //window_move2cart.document.write('<html><body><br><p align="center"><img src="images_website/anim_progress.gif" border="0"></p></body></html>');
        // get some meta info
        add2cartForm = document.forms["add2cart_form_" + pid];
        scart_referrer = getCookie("cookie_scart_referrer");
        scart_affiliate_id = getCookie("cookie_scart_affiliate_id");
        referralMemberId = getCookie("cookie_referralMemberId");
        pSearchQueryId = getCookie("cookie_pSearchQueryId");
        scartUrlArgs = getCookie("cookie_scart_urlArgs");
        // submit the form
        eval("this.document.add2cart_form_" + pid + ".target = 'win_move2cart';");
        if (scart_referrer != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_referrer"); newField.setAttribute("value", scart_referrer); targetForm.appendChild(newField); }
        if (scart_affiliate_id != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_affiliate_id"); newField.setAttribute("value", scart_affiliate_id); targetForm.appendChild(newField); }
        if (location.hash != null && location.hash != "") { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_url_hash"); newField.setAttribute("value", location.hash); targetForm.appendChild(newField); }
        if (referralMemberId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "referralMemberId"); newField.setAttribute("value", referralMemberId); targetForm.appendChild(newField); }
        if (pSearchQueryId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "pSearchQueryId"); newField.setAttribute("value", pSearchQueryId); targetForm.appendChild(newField); }
        if (scartUrlArgs != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scartUrlArgs"); newField.setAttribute("value", scartUrlArgs); targetForm.appendChild(newField); }
        eval("this.document.add2cart_form_" + pid + ".form_action_value.value = 'buy_only';");
        if (rpid > 0) { eval("this.document.add2cart_form_" + pid + ".rpid.value = '" + rpid + "';"); }
        add2cartForm.submit();
    }
    return true;
}

// invoked when adding a product to the cart
function f_add2cart_form(pid) { return f_add2cart_form_alias1(pid, '0', false, ''); }
function f_add2cart_form_alias1(pid, rpid, isCheckOptions, msgSelectOption) {
    var targetForm = document.forms["add2cart_form_" + pid];
    if (isCheckOptions) {
        // check if no option is selected and show appropriate message
        eval("form = this.document.add2cart_form_" + pid + ";");
        objectProductTotals = rpid > 0 ? recalculate_product_price_total_2(form, "_arr[" + rpid + "]") : recalculate_product_price_total(form);
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrderRequired()) { alert(msgSelectOption + objectProductTotals.getMissingRequiredOptionsAsString("\n\n")); return false; }
        if (objectProductTotals && ! objectProductTotals.isProductReadyToOrder()) { alert(msgSelectOption); return false; }
    }
    // get some meta info
    add2cartForm = document.forms["add2cart_form_" + pid];
    scart_referrer = getCookie("cookie_scart_referrer");
    scart_affiliate_id = getCookie("cookie_scart_affiliate_id");
    referralMemberId = getCookie("cookie_referralMemberId");
    pSearchQueryId = getCookie("cookie_pSearchQueryId");
    scartUrlArgs = getCookie("cookie_scart_urlArgs");
    // submit the form
    eval("this.document.add2cart_form_" + pid + ".target = '';");
    if (scart_referrer != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_referrer"); newField.setAttribute("value", scart_referrer); targetForm.appendChild(newField); }
    if (scart_affiliate_id != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_affiliate_id"); newField.setAttribute("value", scart_affiliate_id); targetForm.appendChild(newField); }
    if (location.hash != null && location.hash != "") { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scart_url_hash"); newField.setAttribute("value", location.hash); targetForm.appendChild(newField); }
    if (referralMemberId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "referralMemberId"); newField.setAttribute("value", referralMemberId); targetForm.appendChild(newField); }
    if (pSearchQueryId != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "pSearchQueryId"); newField.setAttribute("value", pSearchQueryId); targetForm.appendChild(newField); }
    if (scartUrlArgs != null) { var newField = document.createElement("input"); newField.setAttribute("type", "hidden"); newField.setAttribute("name", "scartUrlArgs"); newField.setAttribute("value", scartUrlArgs); targetForm.appendChild(newField); }
    eval("this.document.add2cart_form_" + pid + ".form_action_value.value = 'buy';");
    if (rpid > 0) { eval("this.document.add2cart_form_" + pid + ".rpid.value = '" + rpid + "';"); }
    onsubmitResult = add2cartForm.onsubmit();
    if ((typeof(onsubmitResult) == 'undefined') || onsubmitResult) { add2cartForm.submit(); }
    return true;
}

// onsubmit of the add2cart form
function onsubmit_add2cart_form(aForm) { 
    if (typeof(onsubmit_add2cart) == 'function') {
        onsubmitResult = onsubmit_add2cart(aForm);
        if (typeof(onsubmitResult) == 'undefined') { return true; } else { return onsubmitResult; }
    }
    return true;
}

// forward to location
function form_jumpbylocation(_location) {
    if (_location != '') { eval("document.location='" + _location + "'"); }
}

// Removes leading and trailing spaces from the passed string. Also removes consecutive spaces and replaces it with one space.
function trim(inputString) {
    if (typeof inputString != "string") { return inputString; }
    var retValue = inputString;
    var ch = retValue.substring(0, 1);
    while (ch == " ") { // Check for spaces at the beginning of the string
        retValue = retValue.substring(1, retValue.length);
        ch = retValue.substring(0, 1);
    }
    ch = retValue.substring(retValue.length-1, retValue.length);
    while (ch == " ") { // Check for spaces at the end of the string
        retValue = retValue.substring(0, retValue.length-1);
        ch = retValue.substring(retValue.length-1, retValue.length);
    }
    while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
        retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
    }
    return retValue; // Return the trimmed string back to the user
}

// window functions
function getWinProps(_width, _height, _scroll, _resizable) {
    var winl = (screen.width - _width) / 2; var wint = (screen.height - _height) / 2;
    winprops = 'left='+winl+',screenX='+winl+',top='+wint+',screenY='+wint+',width='+_width+',height='+_height+',scrollbars='+_scroll+',resizable='+_resizable;
    return winprops;
}

// --- DOM helper functions ---

function getElementsByTagAndName(tag, name) {
     var allAlements = document.getElementsByTagName(tag);
     var resultElements = new Array();
     for (i = 0,iarr = 0; i < allAlements.length; i++) {
          if (allAlements[i].getAttribute("name") == name) { resultElements[iarr] = allAlements[i]; iarr++; }
     }
     return resultElements;
}

function getElementsByTagAndClass(tag, className) {
     var allAlements = document.getElementsByTagName(tag);
     var resultElements = new Array();
     for (i = 0,iarr = 0; i < allAlements.length; i++) {
          if (YAHOO.util.Dom.hasClass(allAlements[i], className)) { resultElements[iarr] = allAlements[i]; iarr++; }
     }
     return resultElements;
}

function getElementsByName(name) {
    var targetField = this.document.getElementById(name);
    var targetField_arr = this.document.getElementsByName(name);
    return targetField_arr && targetField_arr.length > 0 ? targetField_arr : (targetField != null ? [targetField] : null);
}

// set the style.display of an element
function setStyleDisplay(id_element, isShow) { setStyleDisplayMode(id_element, isShow, "block", "none"); }
function setStyleDisplayMode(id_element, isShow, showDisplayMode, hideDisplayMode) {
    var targetField = this.document.getElementById(id_element);
    var targetField_arr = document.getElementsByName(id_element);
    if (targetField_arr && targetField_arr.length > 0) {
        for (var i = 0; i < targetField_arr.length; i++) { targetField_arr[i].style.display = isShow ? showDisplayMode : hideDisplayMode; }
    } else if (targetField) {
        targetField.style.display = isShow ? showDisplayMode : hideDisplayMode;
    }
}
function switchShowById(id_element, showDisplayMode) {
    if ( ! showDisplayMode) { showDisplayMode = "block"; }
    var targetField = this.document.getElementById(id_element);
    if (targetField.style.display == "none") { showByIdAndMode(id_element, showDisplayMode); return true; } else { hideById(id_element); return false; }
}
function hideById(id_element) { setStyleDisplay(id_element, false); }
function showById(id_element) { setStyleDisplay(id_element, true); }
function showByIdAndMode(id_element, showDisplayMode) { setStyleDisplayMode(id_element, true, showDisplayMode, "none"); }

// --- javascript helper functions ---

function launchJavascript(responseText) {
    if (responseText && responseText != "") {
        var ScriptFragment = '(?:<' + 'script.*?>)((\\s|.)*?)(?:</' + 'script>)';
        var match = new RegExp(ScriptFragment, 'gim');
        var scripts = responseText.match(match);
        if (scripts) {
            var js = '';
            for (var s = 0; s < scripts.length; s++) {
                var match = new RegExp(ScriptFragment, 'im');
                js += scripts[s].match(match)[1];
            }
            eval(js);
        }
    }
}

// --- cookies ---

function getCookie(name) {
    if (document.cookie.length > 0) {
        begin = document.cookie.indexOf(name + "=");
        if (begin != -1) {
            begin += name.length + 1;
            end = document.cookie.indexOf(";", begin);
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(begin, end));
        }
    }
    return null;
}
function setCookie(name, value, expiredays) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + (expiredays * 24 * 3600 * 1000));
    document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + expireDate.toGMTString());
}
function setCookieAdvanced(name, value, expiredays, path, domain, secure) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + (expiredays * 24 * 3600 * 1000));
    var curCookie = name + "=" + escape(value) +
        ((expiredays != null) ? "; expires=" + expireDate.toGMTString() : "") +
        ((path != null) ? "; path=" + path : "") +
        ((domain != null) ? "; domain=" + domain : "") +
        ((secure != null) ? "; secure" : "");
    document.cookie = curCookie;
}
function delCookie(name) {
    if (getCookie(name)) { document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; }
}
function checkCookiesEnabled(msgDisabled) {
    setCookie("scart_cookies_enabled", "yes", 1);
    if (getCookie("scart_cookies_enabled") == "yes") {
        delCookie("scart_cookies_enabled");
        return true;
    } else {
        if (msgDisabled != "") { alert(msgDisabled); }
    }
    return false;
}

// --- toggles ---

function PartWrapperToggle(elementName, cancelBubble) {
    var BodyElement = null;
    if (document.getElementsByName) {
        BodyElement = document.getElementsByName(elementName + "Body");
        var UpImage = document.getElementsByName(elementName + "Up");
        var DownImage = document.getElementsByName(elementName + "Down");
        if (BodyElement && BodyElement.length > 0) {
            for (var i = 0; i < BodyElement.length; i++) {
                if (BodyElement[i].style.display == "none") {
                    BodyElement[i].style.display = "";
                    DownImage[i].style.display = "none";
                    UpImage[i].style.display = "";
                    setCookieAdvanced("cookie_scart_" + elementName, 1, 5*365, '/', null, null);
                } else {
                    BodyElement[i].style.display = "none";
                    DownImage[i].style.display = "";
                    UpImage[i].style.display = "none";
                    setCookieAdvanced("cookie_scart_" + elementName, 1, -5*365, '/', null, null);
                }
            }
        }
    }
    if (cancelBubble && window.event) { window.event.cancelBubble = true; }
    return false;
}
function ToggleByCookie(elementName) {
    if (getCookie("cookie_scart_" + elementName) != 1) { PartWrapperToggle(elementName, false); }
}

// --- product prices ---

function recalculate_product_price_total_qty(form, qty_field) {
    return recalculate_product_price_total_qty_2(form, qty_field, '');
}
function recalculate_product_price_total_qty_2(form, qty_field, field_suffix) {
    if ( ! form) { return null; }
    form['temp_qty_field_value' + field_suffix] = qty_field.value;
    return recalculate_product_price_total_2(form, field_suffix);
}
function recalculate_product_price_total(form) {
    return recalculate_product_price_total_2(form, '');
}
function recalculate_product_price_total_2(form, field_suffix) {
    var objectProductTotals = null;

    // validate
    if ( ! document.getElementById) { return objectProductTotals; }
    if ( ! form) { return objectProductTotals; }

    // get the product's id
    if ( ! form['product_id' + field_suffix]) { return objectProductTotals; }
    var id_product = form['product_id' + field_suffix].value;

    // some inits
    var product_qty = 1;
    var price_total = 0;
    var price_list_total = 0;
    var price_total_related = 0;
    var price_list_total_related = 0;
    var count_group_options_selected = 0;
    var count_required = 0;
    var count_required_selected = 0;
    var missingRequiredOptions = [];
    var count_checkboxes = 0;
    var count_checkboxes_selected = 0;
    var count_radiobuttons = 0;
    var count_radiobuttons_selected = 0;
    var count_dropdowns = 0;
    var count_dropdowns_selected = 0;

    // get the product's currency digits
    var currency_digits = form['product_currency_digits' + field_suffix] ? parseInt(form['product_currency_digits' + field_suffix].value) : 2;

    // get the price_total based on id_product
    var price_total_field = document.getElementById("product_price_total_" + id_product);
    var price_total_field_arr = document.getElementsByName("product_price_total_" + id_product);

    // get the price_tax_total based on id_product
    var price_tax_total_field = document.getElementById("product_price_tax_total_" + id_product);
    var price_tax_total_field_arr = document.getElementsByName("product_price_tax_total_" + id_product);

    // get the price_list based on id_product
    var price_list_total_field = document.getElementById("product_price_list_total_" + id_product);
    var price_list_total_field_arr = document.getElementsByName("product_price_list_total_" + id_product);

    // get the base prices
    var price_base = form['product_price_base' + field_suffix] ? parseFloat(form['product_price_base' + field_suffix].value): 0;
    var price_list_base = form['product_price_list_base' + field_suffix] ? parseFloat(form['product_price_list_base' + field_suffix].value): 0;

    // include base price ?
    var include_base_price = form['include_base_price' + field_suffix] ? form['include_base_price' + field_suffix].value : "yes";
    if (form['product_price_base' + field_suffix]) { price_total = include_base_price == "yes" ? price_base : 0; }
    price_list_total = price_total;
    if (form['product_price_list_base' + field_suffix]) { price_list_total = include_base_price == "yes" ? price_list_base : 0; }

    // get the quantity, check for multiple qty fields, check for NaN
    if (typeof SFUI.ThisWebsite == "undefined" || typeof SFUI.ThisWebsite.isShowProductSingleQtyPrice == "undefined" || SFUI.ThisWebsite.isShowProductSingleQtyPrice == 0) {
        var product_qty_field = form['product_add_qty' + field_suffix];
        if (product_qty_field && product_qty_field.type == "select-one") {
            product_qty = product_qty_field.options[product_qty_field.selectedIndex].value;
        } else {
            if (product_qty_field && product_qty_field.length && form['temp_qty_field_value' + field_suffix]) {
                for (var i = 0; i < product_qty_field.length; i++) { product_qty_field[i].value = form['temp_qty_field_value' + field_suffix]; }
            }
            product_qty = product_qty_field ? parseInt(product_qty_field.length ? product_qty_field[0].value : product_qty_field.value) : 1;
        }
        product_qty = isNaN(product_qty) || product_qty <= 0 ? 1 : product_qty;
    }

    // create regular expression if necessary
    if (field_suffix != "") {
        // prepare the field_suffix to be used as a regular expression create the regular expression
        var fieldSuffixRegExprStr = field_suffix.replace("[", "\\["); fieldSuffixRegExprStr = fieldSuffixRegExprStr.replace("]", "\\]");
        var fieldSuffixRegExpr = new RegExp(fieldSuffixRegExprStr + "$");
    }

    // go through all form elements
    var radio_index = 0; var radio_name_old = "";
    for (var i = 0; i < form.elements.length; i++) {
        if (fieldSuffixRegExpr && ! fieldSuffixRegExpr.test(form.elements[i].name)) { continue; }
        var field_type = form.elements[i].type;
        if (field_type != "hidden") {

            // --- handle selected related items ---

            if (field_type == "checkbox" && field_suffix == "") {
                if (form.elements[i].checked) {
                    var regexprRelated = new RegExp("^related_add2cart(_arr\[[0-9]+\])$");
                    var related_suffix_arr = regexprRelated.exec(form.elements[i].name);
                    if (related_suffix_arr) { 
                        var objectRelatedProductTotals = recalculate_product_price_total_2(form, related_suffix_arr[1]);
                        if (objectRelatedProductTotals != null) {
                            price_total_related += objectRelatedProductTotals.qty * objectRelatedProductTotals.total;
                            price_list_total_related += objectRelatedProductTotals.qty * objectRelatedProductTotals.total_list;
                        }
                    }
                }
            }

            // --- handle options ---

            // check the name of the form's field and grab the option index
            var regexpr = new RegExp("^option_([0-9]+)_value" + (field_suffix != "" ? "_arr" : "$"));
            var option_index_arr = regexpr.exec(form.elements[i].name);
            if ( ! option_index_arr) { continue; }

            // get the option's quantity
            var option_qty = form['option_' + option_index_arr[1] + '_qty' + field_suffix] ? parseInt(form['option_' + option_index_arr[1] + '_qty' + field_suffix].value) : 1;
            option_qty = isNaN(option_qty) ? 1 : option_qty;

            // go by the field type
            if (field_type == "checkbox") {
                count_checkboxes++;
                if ( ! form.elements[i].checked) { continue; }
                count_checkboxes_selected++;
            } else if (field_type == "radio") {
                if (radio_name_old != form.elements[i].name) { radio_index = 0; radio_name_old = form.elements[i].name; }
                count_radiobuttons++; radio_index++;
                if ( ! form.elements[i].checked) { continue; }
                count_radiobuttons_selected++;
                // get the radio button's quantity
                var option_qty_fields = form['option_' + option_index_arr[1] + '_qty' + field_suffix];
                if (option_qty_fields && option_qty_fields.length) {
                    option_qty = parseInt(option_qty_fields[radio_index - 1].value);
                    option_qty = isNaN(option_qty) ? 1 : option_qty;
                }
            } else if (field_type == "select-one") {
                count_dropdowns++;
                var dropdown_value = form.elements[i].selectedIndex != -1 ? unescape(form.elements[i].options[form.elements[i].selectedIndex].value) : "";
                if (dropdown_value == "") { continue; }
                if (dropdown_value == "<required/>") { continue; }
                count_dropdowns_selected++;
            } else if (field_type == "text") {
                if (trim(form.elements[i].value) == "") { continue; }
            }

            // count the selected options in a group
            count_group_options_selected++;

            // unescape first
            var value = unescape(form.elements[i].value);
            // accumulate the price of the option
            var price_option = /<price>(\-?[0-9\.]+)<\/price>/i.exec(value);
            if (price_option) { price_total += option_qty * parseFloat(price_option[1]); }
            price_option = /<price value=.?(\-?[0-9\.]+).?\/>/i.exec(value);
            if (price_option) { price_total += option_qty * parseFloat(price_option[1]); }

            // accumulate the price_list of the option
            var price_list_option = /<price_list value=.?(\-?[0-9\.]+).?\/>/i.exec(value);
            if (price_list_option) { price_list_total += option_qty * parseFloat(price_list_option[1]); }
        }
        // hidden field
        else {
            // count required vs empty options
            var regexpr = new RegExp("^group_[0-9]+_required" + (field_suffix != "" ? "" : "$"));
            if ( ! regexpr.test(form.elements[i].name)) { continue; }
            if (form.elements[i].value != "yes") { count_group_options_selected = 0; continue; }
            count_required++;
            if (count_group_options_selected > 0) { count_group_options_selected = 0; count_required_selected++; }
            else if (form.elements[i].getAttribute("groupName") != null) { missingRequiredOptions.push(form.elements[i].getAttribute("groupName")); }
        }
    }

    // the grand total is the sum of the totals of the main and selected related products
    var price_grand_total = product_qty*price_total + price_total_related;
    var price_list_grand_total = product_qty*price_list_total + price_list_total_related;

    // change the price on the page
    var price_total_new = price_grand_total.toFixed(currency_digits);
    if (price_total_field_arr && price_total_field_arr.length > 0) {
        for (var i = 0; i < price_total_field_arr.length; i++) { price_total_field_arr[i].innerHTML = price_total_new; }
    } else if (price_total_field) {
        price_total_field.innerHTML = price_total_new;
    }

    // change the price_list on the page if necessary
    var price_list_total_new = price_list_grand_total.toFixed(currency_digits);
    if (price_list_total_field_arr && price_list_total_field_arr.length > 0) {
        for (var i = 0; i < price_list_total_field_arr.length; i++) { price_list_total_field_arr[i].innerHTML = price_list_total_new; }
    } else if (price_list_total_field) {
        price_list_total_field.innerHTML = price_list_total_new;
    }

    // change the price_tax on the page
    var taxinter_percent = form['product_taxinter_percent' + field_suffix] ? parseInt(form['product_taxinter_percent' + field_suffix].value) : 0;
    var price_tax_total_new = (price_grand_total + price_grand_total*(taxinter_percent/100)).toFixed(currency_digits);
    if (price_tax_total_field_arr && price_tax_total_field_arr.length > 0) {
        for (var i = 0; i < price_tax_total_field_arr.length; i++) { price_tax_total_field_arr[i].innerHTML = price_tax_total_new; }
    } else if (price_tax_total_field) {
        price_tax_total_field.innerHTML = price_tax_total_new;
    }

    // change the list-price difference on the page
    if (price_list_grand_total > price_grand_total) {
        var price_diff_amount_new = (price_list_grand_total - price_grand_total).toFixed(currency_digits);
        setInnerHTMLById("product_price_diff_amount_" + id_product, price_diff_amount_new);
    }

    // change the list-price percentage difference on the page
    if (price_list_grand_total > 0) {
        var price_diff_percent_new = ((price_list_grand_total - price_grand_total)/price_list_grand_total*100).toFixed(0) + "%";
        setInnerHTMLById("product_price_diff_percent_" + id_product, price_diff_percent_new);
    }

    // create the return object
    objectProductTotals = new ObjectProductTotals();
    objectProductTotals.setTotals(product_qty, price_total, price_list_total);
    objectProductTotals.setCountRequired(count_required, count_required_selected, missingRequiredOptions);
    objectProductTotals.setCountCheckboxes(count_checkboxes, count_checkboxes_selected);
    objectProductTotals.setCountRadiobuttons(count_radiobuttons, count_radiobuttons_selected);
    objectProductTotals.setCountDropdowns(count_dropdowns, count_dropdowns_selected);
    //alert(objectProductTotals.toString());

    return objectProductTotals;
}

// --- product options ---

function onDependencyOptionChanged(productId, changedField, dynamicIncludeId, args) {
    if (typeof args === 'undefined' || args == null) { args = {}; }
    var productForm = changedField.form != null ? changedField.form : document.forms["add2cart_form_" + productId];

    // get all selected product option ids, quantities, and textFields
    var selectedOptionIds = ""; var enteredQuantities = ""; var enteredTexts = "";
    for (var i = 0; i < productForm.elements.length; i++) {
        var productField = productForm.elements[i];
        var selectedOptionId = productField.getAttribute("optionId");
        if (selectedOptionId != null) {
            var productFieldType = productForm.elements[i].type;
            if (productFieldType == "checkbox" || productFieldType == "radio") {
                if ( ! productField.checked) { continue; }
            } else if (productFieldType == "select-one") {
                selectedOptionId = productField.selectedIndex != -1 ? productField.options[productField.selectedIndex].getAttribute("optionId") : null;
            } else if (productFieldType == "text") {
                var textValue = trim(productField.value);
                if (textValue == "") { continue; }
                enteredTexts += ",optTexts[" + selectedOptionId + "]=" + textValue.replace(/&/g, "%26").replace(/,/g, "%2C");
            }
            if (selectedOptionId != null) { selectedOptionIds += (selectedOptionIds != "" ? "|" : ",selOptIds=") + selectedOptionId; }
        } else {
            var selectedOptionIdQty = productField.getAttribute("optionIdQty");
            if (selectedOptionIdQty != null) {
                var origValueQty = productField.getAttribute("origValue");
                if (origValueQty == null || productField.value != origValueQty) {
                    enteredQuantities += ",optQuantities[" + selectedOptionIdQty + "]=" + productField.value;
                }
            }
        }
    }

    // re-process the dynamic include
    var dynamicIncludeField = this.document.getElementById(dynamicIncludeId);
    if (dynamicIncludeField) {
        changedField.disabled = true;
        var ajaxParams = dynamicIncludeField.getAttribute("ajaxParamsOrig");
        if (ajaxParams == null) { ajaxParams = dynamicIncludeField.getAttribute("ajaxParams"); }
        dynamicIncludeField.setAttribute("ajaxParamsOrig", ajaxParams);
        ajaxParams += encodeURIComponent(",currOptId=" + changedField.getAttribute("optionId") + selectedOptionIds + enteredQuantities + enteredTexts);
        dynamicIncludeField.setAttribute("ajaxParams", ajaxParams);
        dynamicIncludeField.setAttribute("isProcessed", "0");
        var onAsyncResponseCallback = function(isSuccess, responseText) {
            var changedFieldId = changedField.id;
            for (var i = 0; i < productForm.elements.length; i++) {
                if (productForm.elements[i].id == changedFieldId) {
                    try { productForm.elements[i].focus(); } catch (e) {}
                    break;
                }
            }
        };
        processDynamicIncludes(args.wsEndpoint, null, onAsyncResponseCallback);
    }
}

function onMouseOverOptionRadioButtonAsImage(targetVisualGroupElemId, targetVisualElem, optionName) {
    targetVisualElem.className += " optionAsImage_hover";
    var targetElemSelectedOptionNames = document.getElementById(targetVisualGroupElemId);
    if (targetElemSelectedOptionNames) {
        targetElemSelectedOptionNames.setAttribute("oldInnerHTML", escape(targetElemSelectedOptionNames.innerHTML));
        targetElemSelectedOptionNames.innerHTML = optionName;
    }
}
function onMouseOutOptionRadioButtonAsImage(targetVisualGroupElemId, targetVisualElem) {
    targetVisualElem.className = targetVisualElem.className.replace(" optionAsImage_hover", "");
    var targetElemSelectedOptionNames = document.getElementById(targetVisualGroupElemId);
    if (targetVisualGroupElemId) { 
        targetElemSelectedOptionNames.innerHTML = unescape(targetElemSelectedOptionNames.getAttribute("oldInnerHTML"));
    }
}
function onClickOptionRadioButtonAsImage(targetVisualGroupElemId, targetVisualElem, targetInputId, targetInputName, optionName) {
    var targetInput = document.getElementById(targetInputId);
    targetInput.click();
    toggleRadioAndStyleTargetElement(targetInput.form[targetInputName], "optionAsImage_selected");
    var targetElemSelectedOptionNames = document.getElementById(targetVisualGroupElemId);
    if (targetElemSelectedOptionNames) {
        targetElemSelectedOptionNames.innerHTML = optionName;
        targetElemSelectedOptionNames.setAttribute("oldInnerHTML", escape(targetElemSelectedOptionNames.innerHTML));
    }
}

function onMouseOverOptionCheckBoxAsImage(targetVisualGroupElemId, targetVisualElem, optionId, optionName) {
    targetVisualElem.className += " optionAsImage_hover";
    toggleValueInGroupAndVisualize(targetVisualGroupElemId, optionId, optionName, true);
}
function onMouseOutOptionCheckBoxAsImage(targetVisualGroupElemId, targetVisualElem) {
    targetVisualElem.className = targetVisualElem.className.replace(" optionAsImage_hover", "");
    toggleValueInGroupAndVisualize(targetVisualGroupElemId, null);
}
function onClickOptionCheckBoxAsImage(targetVisualGroupElemId, targetVisualElem, targetInputId, optionId, optionName) {
    var targetInput = document.getElementById(targetInputId);
    targetInput.click();
    toggleValueInGroupAndVisualize(targetVisualGroupElemId, optionId, optionName, false);
    if (targetInput.checked) { targetVisualElem.className += " optionAsImage_selected"; } else { targetVisualElem.className = targetVisualElem.className.replace(" optionAsImage_selected", ""); }
}

function toggleRadioAndStyleTargetElement(radioGroup, classNameSelected) {
    if (radioGroup.length) {
        for (var i = 0; i < radioGroup.length; i++) {
            var targetVisualElemId = radioGroup[i].getAttribute("targetVisualElementId");
            if (targetVisualElemId) {
                var targetElemClassName = document.getElementById(targetVisualElemId).className;
                if (radioGroup[i].checked) {
                    if (targetElemClassName.indexOf(classNameSelected) == -1) {
                        document.getElementById(targetVisualElemId).className = targetElemClassName + " " + classNameSelected;
                    }
                } else {
                    document.getElementById(targetVisualElemId).className = targetElemClassName.replace(" " + classNameSelected, "");
                }
            }
        }
    } else {
        var targetVisualElemId = radioGroup.getAttribute("targetVisualElementId");
        if (targetVisualElemId) {
            var targetElemClassName = document.getElementById(targetVisualElemId).className;
            if (radioGroup.checked) {
                if (targetElemClassName.indexOf(classNameSelected) == -1) {
                    document.getElementById(targetVisualElemId).className = targetElemClassName + " " + classNameSelected;
                }
            } else {
                document.getElementById(targetVisualElemId).className = targetElemClassName.replace(" " + classNameSelected, "");
            }
        }
    }
}
function toggleValueInGroupAndVisualize(targetVisualElemId, key, value, isSuppressToggle) {
    var targetVisualElem = document.getElementById(targetVisualElemId);
    if (targetVisualElem) {
        var groupPairs = targetVisualElem.getAttribute("groupPairs");
        if (groupPairs == null) { groupPairs = ""; }
        if (key != null) {
            var targetPair = key + "=" + escape(value);
            if (groupPairs.indexOf(targetPair) != -1) {
                if ( ! isSuppressToggle) { groupPairs = groupPairs.replace(targetPair, ""); }
            } else {
                groupPairs += "|" + targetPair;
            }
            if ( ! isSuppressToggle) { targetVisualElem.setAttribute("groupPairs", groupPairs); }
        }
        var groupPairsArr = groupPairs.split("|");
        var groupValuesStr = "";
        for (var i = 0; i < groupPairsArr.length; i++) {
            if (trim(groupPairsArr[i]) == "") { continue; }
            var pairArr = groupPairsArr[i].split("=", 2);
            groupValuesStr += (groupValuesStr != "" ? ", " : "") + unescape(pairArr[1]);
        }
        targetVisualElem.innerHTML = groupValuesStr;
    }
}

function radio_toggle(group_radio) {
    if (group_radio.length) {
        for (var i = 0; i < group_radio.length; i++) { option_toggle(group_radio[i]); }
    } else {
        option_toggle(group_radio);
    }
}
function option_toggle(e) {
    if (e.checked) { option_highlight(e); } else { option_unhighlight(e); }
}
function option_highlight(e) {
    var r = null;
    if (e.parentNode && e.parentNode.parentNode) {
        r = e.parentNode.parentNode;
    } else if (e.parentElement && e.parentElement.parentElement) {
        r = e.parentElement.parentElement;
    }
    if (r) { if (r.className == "product_options_body") { r.className = "product_options_selected"; } }
}
function option_unhighlight(e) {
    var r = null;
    if (e.parentNode && e.parentNode.parentNode) {
        r = e.parentNode.parentNode;
    } else if (e.parentElement && e.parentElement.parentElement) {
        r = e.parentElement.parentElement;
    }
    if (r) { if (r.className == "product_options_selected") { r.className = "product_options_body"; } }
}
function setAllFormFieldsWithSameNames(field_src) {
    if (field_src && field_src.form) {
        fields = field_src.form[field_src.name];
        if (fields && fields.length) {
            for (var i = 0; i < fields.length; i++) { fields[i].value = field_src.value; }
        }
    }
}

function styleRadioButtons(radioGroup, classNameSelected, classNameUnselected) {
    if (radioGroup.length) {
        for (var i = 0; i < radioGroup.length; i++) {
            var targetVisualElemId = radioGroup[i].getAttribute("targetVisualElementId");
            document.getElementById(targetVisualElemId).className = radioGroup[i].checked ? classNameSelected : classNameUnselected;
        }
    } else {
        var targetVisualElemId = radioGroup.getAttribute("targetVisualElementId");
        document.getElementById(targetVisualElemId).className = radioGroup.checked ? classNameSelected : classNameUnselected;
    }
}

// populate field based on the type of the field
function populate_field_bytype(field_current, field_value) {
    if (field_current.type == "file" || field_current.type == "text" || field_current.type == "password" || field_current.type == "textarea") {
        field_current.value = field_value;
    } else if (field_current.type == "select-one") {
        for (var i = 0; i < field_current.length; i++) {
            if (field_current[i].value == field_value) { field_current[i].selected = true; break; }
        }
    } else if (field_current.type == "checkbox" || field_current.type == "radio") {
        field_current.checked = field_value != "" && field_value != "0" ? 1 : 0;
    } else {
        if (field_current.length) {
            for (var i = 0; i < field_current.length; i++) {
                if (field_current[i].value == field_value) { field_current[i].checked = true; break; }
            }
        }
    }
}

// return the value of the given form field
function get_field_value_bytype(field_current, defaultCheckboxValue) {
    field_value = "";
    if (field_current.type == "file" || field_current.type == "text" || field_current.type == "password" || field_current.type == "textarea") {
        field_value = field_current.value;
    } else if (field_current.type == "select-one") {
        field_value = field_current.value;
    } else if (field_current.type == "checkbox" || field_current.type == "radio") {
        field_value = field_current.checked ? field_current.value : defaultCheckboxValue;
    } else {
        if (field_current.length) {
            for (var i = 0; i < field_current.length; i++) {
                if (field_current.type == "select-multiple") {
                    field_value = field_current[0].value; break;
                } else {
                    if (field_current[i].checked) { field_value = field_current[i].value; break; }
                }
            }
        }
    }
    return field_value;
}

// set focus to the given form field
function set_focus_bytype(field_current) {
    if (field_current.type == "text" || field_current.type == "textarea") {
        field_current.focus();
    } else if (field_current.type == "checkbox") {
        field_current.focus();
    } else if (field_current.type == "select-one") {
        field_current.focus();
    } else if (field_current.type == "radio") {
        field_current.focus();
    } else {
        if (field_current.length) {
            for (var i = 0; i < field_current.length; i++) {
                if (field_current[i].checked) { field_current[i].focus(); break; }
            }
        }
    }
    return field_value;
}

// onmouseover and onmouseout of the menu items
function onmouseover_categorytype(id_categorytype, name_categorytype, image_name) {}
function onmouseout_categorytype(id_categorytype, name_categorytype, image_name) {}
function onmouseover_category(id_category, name_category, image_name) {}
function onmouseout_category(id_category, name_category, image_name) {}
function onmouseover_subcategory(id_subcategory, name_subcategory, image_name) {}
function onmouseout_subcategory(id_subcategory, name_subcategory, image_name) {}

// onimageload
function onimageload_categorytype(image_name) {}
function onimageload_category(image_name) {}
function onimageload_subcategory(image_name) {}

// --- select tag functions ---

function selectOptionByCurrentPage(workingForm, selectFieldName) {
    currentPath = window.location.pathname;
    currentPath = currentPath.substring(currentPath.lastIndexOf("/") + 1);

    if (currentPath != '') {
        if (workingForm[0][selectFieldName]) {
            for (j = 0; j < workingForm.length; j++) {
                var selectField = workingForm[j][selectFieldName];
                for (i = 1; i < selectField.length; i++) {
                    if (selectField.options[i].value.indexOf(currentPath) == 0) {
                        selectField.options[i].selected = true; break;
                    }
                }
            }
        } else if (workingForm[selectFieldName]) {
            for (i = 1; i < workingForm[selectFieldName].length; i++) {
                if (workingForm[selectFieldName].options[i].value.indexOf(currentPath) == 0) {
                    workingForm[selectFieldName].options[i].selected = true; break;
                }
            }
        }
    }
}

// --- innerHTML helper functions ---

function setInnerHTMLById(elementId, innerHTMLValue) {
    targetField = document.getElementById(elementId);
    targetField_arr = document.getElementsByName(elementId);
    if (targetField_arr && targetField_arr.length > 0) {
        for (var i = 0; i < targetField_arr.length; i++) { targetField_arr[i].innerHTML = innerHTMLValue; }
    } else if (targetField) {
        targetField.innerHTML = innerHTMLValue;
    }
}

function unescapePhp2JavaScriptArgument(argValue) {
    if (argValue) { 
        argValue = argValue.replace(/&quot;/g, '"');
        argValue = argValue.replace(/&#39;/g, "'");
    }
    return argValue;
}

function setInnerHtmlByMultipartResult(resultStr, targetFields, multiPartWrapperId, alwaysUseResultStr) {
    if ( ! targetFields || targetFields == null) { return ""; }
    if ( ! targetFields.length) { targetFields = [targetFields]; }
    if (multiPartWrapperId == null) { multiPartWrapperId = targetFields[0].id ? targetFields[0].id : targetFields[0].name; }
    if ( ! multiPartWrapperId) { return ""; }
    var resultResponse = getMultipartResultById(resultStr, multiPartWrapperId);
    if (resultResponse == "") { resultResponse = geWsErrorDescription(resultStr, alwaysUseResultStr); }
    if (resultResponse != "" || alwaysUseResultStr) {
        var attrDelimiterPos = multiPartWrapperId.indexOf(".");
        for (var i = 0; i < targetFields.length; i++) {
            if (attrDelimiterPos != -1) { // must be idName.attrName
                var targetFieldAttr = multiPartWrapperId.substr(attrDelimiterPos + 1);
                targetFields[i].setAttribute(targetFieldAttr, resultResponse);
            } else {
                targetFields[i].innerHTML = resultResponse;
            }
        }
    }
    return resultResponse;
}

function setInnerHtmlByAllMultipartResults(resultStr) {
    var countAppliedMultipartResults = 0;
    var regExp = new RegExp('<ws-multipart-result id="([^"]+)">', 'gi'); 
    while (regExpMatch = regExp.exec(resultStr)) {
        var targetFields = getElementsByName(regExpMatch[1]);
        countAppliedMultipartResults += setInnerHtmlByMultipartResult(resultStr, targetFields) != "" ? 1 : 0;
    }
    return countAppliedMultipartResults;
}

function getMultipartResultById(resultStr, multiPartWrapperId) {
    var resultResponse = "";
    var resultWrapperBegin = '<' + WS_MULTIPART_RESULT_WRAPPER + ' id="' + multiPartWrapperId + '">';
    var resultWrapperBegin_IE = '<' + WS_MULTIPART_RESULT_WRAPPER_IE + ' id=' + multiPartWrapperId + '>';
    var resultWrapperEnd = '</' + WS_MULTIPART_RESULT_WRAPPER + '>';
    var resultWrapperEnd_IE = '</' + WS_MULTIPART_RESULT_WRAPPER_IE + '>';
    var resultBeginIndex = resultStr.indexOf(resultWrapperBegin);
    if (resultBeginIndex == -1) { resultBeginIndex = resultStr.indexOf(resultWrapperBegin_IE); }
    if (resultBeginIndex != -1) {
        var resultEndIndex = resultStr.indexOf(resultWrapperEnd, resultBeginIndex);
        if (resultEndIndex == -1) { resultEndIndex = resultStr.indexOf(resultWrapperEnd_IE, resultBeginIndex); }
        resultResponse = resultStr.substring(resultBeginIndex + resultWrapperBegin.length, resultEndIndex);
    }
    return resultResponse;
}

function geWsErrorDescription(resultStr, alwaysUseResultStr) {
    var resultResponse = "";
    var lowerResultStr = resultStr.toLowerCase();
    var errWrapperBegin = "<error_descr>"; var errWrapperEnd = "</error_descr>";
    var errBeginIndex = lowerResultStr.indexOf(errWrapperBegin);
    if (errBeginIndex != -1) {
        var errEndIndex = lowerResultStr.indexOf(errWrapperEnd, errBeginIndex);
        resultResponse = resultStr.substring(errBeginIndex + errWrapperBegin.length, errEndIndex);
    } else if (alwaysUseResultStr) {
        // clear all WS_MULTIPART_RESULT_WRAPPER content
        resultResponse = resultStr.replace(/<ws-multipart-result.*>[\s\S]*<\/ws-multipart-result>/gi, "");
    }
    return resultResponse;
}

// --- navigation bar help functions ---

var navTabNameSelected = new Array();
function setSelectedNavTabName(id_navbar, navTabName) {
    navTabNameSelected[id_navbar] = navTabName;
}
function selectNavTabByName(id_navbar, navTabName) {
    return selectNavTabByNameWithSelectionClassNames(id_navbar, navTabName, "navtab_selected", "navtab_notselected");
}
function selectNavTabByNameWithSelectionClassNames(id_navbar, navTabName, classSelected, classNotSelected) {
    if (document.getElementById) {
        if (navTabNameSelected[id_navbar] && navTabNameSelected[id_navbar] != "") {
            field_arr = document.getElementsByName(navTabNameSelected[id_navbar]);
            if (field_arr && field_arr.length > 0) {
                for (var i = 0; i < field_arr.length; i++) { field_arr[i].style.display = "none"; }
            } else {
                field = document.getElementById(navTabNameSelected[id_navbar]);
                if (field) { field.style.display = "none"; }
            }
            
            field_arr = document.getElementsByName("a_" + navTabNameSelected[id_navbar]);
            if (field_arr && field_arr.length > 0) {
                for (var i = 0; i < field_arr.length; i++) { field_arr[i].className = classNotSelected; }
            } else {
                field = document.getElementById("a_" + navTabNameSelected[id_navbar]);
                if (field) { field.className = classNotSelected; }
            }
        }
        
        field_arr = document.getElementsByName(navTabName);
        if (field_arr && field_arr.length > 0) {
            for (var i = 0; i < field_arr.length; i++) { field_arr[i].style.display = "block"; }
        } else {
            field = document.getElementById(navTabName);
            if (field) { field.style.display = "block"; }
        }
        
        field_arr = document.getElementsByName("a_" + navTabName);
        if (field_arr && field_arr.length > 0) {
            for (var i = 0; i < field_arr.length; i++) { field_arr[i].className = classSelected; }
        } else {
            field = document.getElementById("a_" + navTabName);
            if (field) { field.className = classSelected; }
        }
        
        setCookieAdvanced("cookie_scart_" + id_navbar, navTabName, 1*365, '/', null, null);
        navTabNameSelected[id_navbar] = navTabName;
    }
    return false;
}

// --- OBJECT : product totals ---

ObjectProductTotals = function() {
    this.qty = 1;
    this.total = 0;
    this.total_list = 0;
    this.count_required = 0;
    this.count_required_selected = 0;
    this.missingRequiredOptions = [];
    this.count_checkboxes = 0;
    this.count_checkboxes_selected = 0;
    this.count_radiobuttons = 0;
    this.count_radiobuttons_selected = 0;
    this.count_dropdowns = 0;
    this.count_dropdowns_selected = 0;
};
ObjectProductTotals.prototype.setTotals = function obj_pt_setTotals(qty, total, total_list) {
    this.qty = qty;
    this.total = total;
    this.total_list = total_list;
};
ObjectProductTotals.prototype.setCountRequired = function obj_pt_setRequired(count_required, count_required_selected, missingRequiredOptions) {
    this.count_required = count_required;
    this.count_required_selected = count_required_selected;
    this.missingRequiredOptions = missingRequiredOptions;
};
ObjectProductTotals.prototype.setCountCheckboxes = function obj_pt_setCountCheckboxes(count_checkboxes, count_checkboxes_selected) {
    this.count_checkboxes = count_checkboxes;
    this.count_checkboxes_selected = count_checkboxes_selected;
};
ObjectProductTotals.prototype.setCountRadiobuttons = function obj_pt_setCountRadiobuttons(count_radiobuttons, count_radiobuttons_selected) {
    this.count_radiobuttons = count_radiobuttons;
    this.count_radiobuttons_selected = count_radiobuttons_selected;
};
ObjectProductTotals.prototype.setCountDropdowns = function obj_pt_setCountDropdowns(count_dropdowns, count_dropdowns_selected) {
    this.count_dropdowns = count_dropdowns;
    this.count_dropdowns_selected = count_dropdowns_selected;
};
ObjectProductTotals.prototype.isProductReadyToOrder = function obj_pt_isProductReadyToOrder() {
    var isReady = (this.total != 0);
    if (this.count_checkboxes > 0) { isReady = isReady || (this.count_checkboxes_selected > 0); }
    if (this.count_radiobuttons > 0) { isReady = isReady || (this.count_radiobuttons_selected > 0); }
    if (this.count_dropdowns > 0) { isReady = isReady || (this.count_dropdowns_selected > 0); }
    isReady = isReady || ((this.count_checkboxes == 0) && (this.count_radiobuttons == 0) && (this.count_dropdowns == 0));
    return isReady;
};
ObjectProductTotals.prototype.isProductReadyToOrderRequired = function obj_pt_isProductReadyToOrderRequired() {
    return this.count_required <= this.count_required_selected;
};
ObjectProductTotals.prototype.getMissingRequiredOptionsAsString = function obj_pt_getMissingRequiredOptionsAsString(prefix) {
    var msgMissingOptions = "";
    for (var i = 0; i < this.missingRequiredOptions.length; i++) { msgMissingOptions += (msgMissingOptions != "" ? ", " : "") + this.missingRequiredOptions[i]; }
    return msgMissingOptions != "" ? prefix + msgMissingOptions : "";
};
/* for debug purposes only
ObjectProductTotals.prototype.toString = function obj_pt_toString() {
    var resultStr  = "qty = " + this.qty + "\n";
    resultStr += "total = " + this.total + "\n";
    resultStr += "total_list = " + this.total_list + "\n";
    resultStr += "count_required = " + this.count_required + "\n";
    resultStr += "count_required_selected = " + this.count_required_selected + "\n";
    resultStr += "missingRequiredOptions = " + this.missingRequiredOptions + "\n";
    resultStr += "count_checkboxes = " + this.count_checkboxes + "\n";
    resultStr += "count_checkboxes_selected = " + this.count_checkboxes_selected + "\n";
    resultStr += "count_radiobuttons = " + this.count_radiobuttons + "\n";
    resultStr += "count_radiobuttons_selected = " + this.count_radiobuttons_selected + "\n";
    resultStr += "count_dropdowns = " + this.count_dropdowns + "\n";
    resultStr += "count_dropdowns_selected = " + this.count_dropdowns_selected + "\n";
    return resultStr;
};*/

// --- string helper functions ---

function startsWith(str, substr) { var reg = new RegExp("^" + substr); return reg.test(str); }
function endsWith(str, substr) { var reg = new RegExp(substr + "$"); return reg.test(str); }
function prepareFileName(str) { return trim(str.replace(/\s+/g, "_").replace(/[^0-9a-zA-Z_\.\-]+/g, "")); }
function strip_tags(str) { return str.replace(/<\/?[^>]+>/gi, ""); }

// --- css helper functions ---

function setClassNameByElementId(fieldId, className) {
    if (document.getElementsByName) {
        var field = document.getElementById(fieldId);
        if (field) { field.className = className; }
    }
}

function setClassNameByElementName(fieldName, className) {
    var fields = document.getElementsByName(fieldName);
    if (fields && fields.length > 0) {
        for (var i = 0; i < fields.length; i++) { fields[i].className = className; }
    } else {
        setClassNameByElementId(fieldName, className);
    }
}

// --- windows helper functions ---

function openNewWindow(url, winName) {
    openNewWindowWithAttr(url, winName, "left=100,top=100,width=500,height=100,scrollbars=no,resizable=yes,toolbar=no");
}
function openNewWindowWithAttr(url, winName, winAttributes) {
    newWindow = window.open(url, winName, winAttributes);
    if (window.focus) { newWindow.focus(); }
}

// returns an associative array of URL key/value pairs
function getUrlArguments(urlValue) {
    var urlArgs = new Array();
    urlValue += "";
    if (urlValue) {
        urlParts = urlValue.indexOf('?') != -1 ? urlValue.split('?') : ['', urlValue];
        if (urlParts[1]) {
            arguments = urlParts[1].split('&');
            if (arguments[0]) {
                for (i in arguments) {
                    pair = arguments[i].split('=');
                    if (pair[1]) {
                        urlArgs[pair[0]] = pair[1];
                        urlArgs["length"]++;
                    }
                }
            }
        }
    }
    return urlArgs;
}

function getUrlBaseName(urlValue) {
    baseName = ""; urlValue += "";
    if (urlValue) {
        urlParts = urlValue.split('?');
        baseName = urlParts[0];
    }
    return baseName;
}

function linkAddReferrerAndForwardToOriginalLink(aLink) {
    cookieReferrer = getCookie("cookie_scart_referrer");
    if (cookieReferrer != null && cookieReferrer != "" && aLink.href) {
        urlArgs = getUrlArguments(aLink.href);
        urlArgs["referrer"] = cookieReferrer;
        urlArgsStr = "";
        for (argKey in urlArgs) { urlArgsStr += (urlArgsStr != "" ? "&" : "") + argKey + "=" + escape(urlArgs[argKey]); }
        if (urlArgsStr != "") { urlArgsStr = getUrlBaseName(window.location) + "?" + urlArgsStr; window.location = urlArgsStr; }
        return false;
    }
    return true;
}

var waitPanel = null;
function showLoadingWindow(loadingMessage, panelPropsObj) {
    if (waitPanel == null) {
        var defaultPanelPropsObj = { width:175, fixedcenter:true, close:false, draggable:true, zindex:9999, modal:true, visible:false };
        if (panelPropsObj != null) { for (var panelProp in panelPropsObj) { defaultPanelPropsObj[panelProp] = panelPropsObj[panelProp]; } }
        var localLoadingImgSrc = typeof(loadingImgSrc) != "undefined" && loadingImgSrc != null ? loadingImgSrc : "http://www.searchfit.com/scart/public/images/anim_indicator_big.gif";
        waitPanel = new YAHOO.widget.Panel("waitPanel", defaultPanelPropsObj);
        waitPanel.setHeader(loadingMessage);
        waitPanel.setBody('<table border="0" align="center" cellspacing="0" cellpadding="20"><tr><td align="center"><img src="' + localLoadingImgSrc + '" border="0" /></td></tr></table>');
        waitPanel.render(document.body);
    }
    waitPanel.show();
    waitPanel.bringToTop();
    return waitPanel;
}
function hideLoadingWindow() {
    if (waitPanel != null) { waitPanel.hide(); waitPanel.destroy(); waitPanel = null; }
}

function resizeWindowByElement(element) {
    if (element) {
        var container = document.getElementById(element);
        if (container) {
            var containerRegion = YAHOO.util.Region.getRegion(container);
            var iHeight = (window.innerWidth) ? window.innerHeight : document.body.clientHeight;
            iHeight = containerRegion.bottom - iHeight;
            window.resizeBy(0, iHeight);
        }
    }
}

// --- validations ---

function isEmailCorrect(email) { return email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.int)|(\.biz)|(\.info)|(\.name)|(\..{2,2}))$)\b/gi); }
function isIPCorrect(ip) { return ip.match(/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/gi); }

function validateRequiredFormFields(aForm, args) {
    if (typeof args === 'undefined') { args = {}; }
    if (typeof args.requiredFieldMsg === 'undefined') { args.requiredFieldMsg = "%s is a Required Field" }
    if (typeof args.invalidEmailMsg === 'undefined') { args.invalidEmailMsg = "%s field has an Invalid Email" }
    if (typeof args.invalidIpMsg === 'undefined') { args.invalidIpMsg = "%s field has an Invalid IP" }
    for (var i = 0; i < aForm.length; i++) {
        var fieldValue = trim(get_field_value_bytype(aForm[i], ""));
        if (fieldValue == "") {
            var isRequired = aForm[i].getAttribute("isRequired");
            if (isRequired != null && isRequired == "1") {
                alert(args.requiredFieldMsg.replace('%s', getLabelForField(aForm[i])));
                try { aForm[i].focus(); } catch (e) {}
                return false;
            }
        } else if (aForm[i].getAttribute("requiredType") != null) {
            var requiredType = aForm[i].getAttribute("requiredType");
            if (requiredType != null) {
                var invalidValueMsg = null;
                if (requiredType == "email") {
                    if ( ! isEmailCorrect(fieldValue)) { invalidValueMsg = args.invalidEmailMsg.replace('%s', getLabelForField(aForm[i])); }
                } else if (requiredType == "ip") {
                    if ( ! isIPCorrect(fieldValue)) { invalidValueMsg = args.invalidIpMsg.replace('%s', getLabelForField(aForm[i])); }
                }
                if (invalidValueMsg != null) { alert(invalidValueMsg); try { aForm[i].focus(); } catch (e) {} return false; }
            }
        }
    }
    return true;
}

function getLabelForField(field) {
    var fieldLabel = field.getAttribute("label");
    if (fieldLabel == null) {
        var parentNode = field.parentNode;
        var labelField = parentNode.getElementsByTagName('label')[0];
        if (labelField == null) { parentNode = parentNode.parentNode; labelField = parentNode.getElementsByTagName('label')[0]; }
        fieldLabel = labelField != null ? labelField.innerHTML : "Unknown";
    }
    return fieldLabel;
}

function mergeDynamicPricesWithStatic(tagName) {
    var priceDisplaySpans = getElementsByTagAndName('span', tagName);
    if (priceDisplaySpans.length > 1) {
        var dynamicPriceDisplayIndex = -1;
        for (var dpif=0; dpif < priceDisplaySpans.length; dpif++) {
            if (YAHOO.util.Dom.hasClass(priceDisplaySpans[dpif].parentNode.parentNode, 'dynamic_include_PRODUCT_PRICE')) {
                if (dynamicPriceDisplayIndex > -1) {
                    priceDisplaySpans[dpif].parentNode.parentNode.removeChild(priceDisplaySpans[dpif].parentNode);
                } else {
                    dynamicPriceDisplayIndex = dpif;
                }
            }
        }
        if (dynamicPriceDisplayIndex > -1) {
            for (var dpif=0; dpif < priceDisplaySpans.length; dpif++) {
                if (dpif!=dynamicPriceDisplayIndex) {
                    priceDisplaySpans[dpif].innerHTML = priceDisplaySpans[dynamicPriceDisplayIndex].innerHTML;
                }
            }
            priceDisplaySpans[dynamicPriceDisplayIndex].parentNode.parentNode.removeChild(priceDisplaySpans[dynamicPriceDisplayIndex].parentNode);
        }
    }
}
