var Page_Validators = [];

function foreach(arr, handler) {

    var k, it, pair;
    if (arr && typeof arr === 'object' && arr.change_key_case) {
        return arr.foreach(handler);
    }
    if (typeof this.Iterator !== 'undefined') {
        var it = this.Iterator(arr);
        if (handler.length === 1) {
            for (pair in it) {
                handler(pair[1]);
            }
        }
        else {
            for (pair in it) {
                handler(pair[0], pair[1]);
            }
        }
    }
    else if (handler.length === 1) {
        for (k in arr) {
            if (!arr.hasOwnProperty || arr.hasOwnProperty(k)) {
                handler(arr[k]);
            }
        }
    }
    else {
        for (k in arr) {
            if (!arr.hasOwnProperty || arr.hasOwnProperty(k)) {
                handler(k, arr[k]);
            }
        }
    }
}

var isNS = (navigator.appName.indexOf("Netscape") != -1);
var _inputsList = new Array();
var _spanList = new Array();

var isIE = false;
var ue = navigator.userAgent;
if (ue.indexOf("MSIE") > -1) {
    isIE = true;
}
else {
    isIE = false;
}


// n: id of object(string)
// d: document which will be searched for
// Examples:
// 1. FindObject('txtName');
// 2. FindObject('txtName',window.opener.document);

function FindObject(n, d) {
    var p, i, x; if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
        x = FindObject(n, d.layers[i].document);
    if (!x && document.getElementById)
        x = document.getElementById(n);
    return x;
}

(function () { /*Use Object Detection to detect IE6*/
    var m = document.uniqueID /*IE*/
&& document.compatMode /*>=IE6*/
&& !window.XMLHttpRequest /*<=IE6*/
&& document.execCommand;
    try {
        if (!!m) { m("BackgroundImageCache", false, true) /* = IE6 only */ }
    }

    catch (oh) { };

})();

function checkHtmlTags(control) {
    var invalidControls = "";

    if (control.value.indexOf('<') > -1) {
        invalidControls = "< ";
        control.value = control.value.replace("<", '')
    }
    else if (control.value.indexOf('/>') > -1) {
        invalidControls += "/> "
        control.value = control.value.replace("/>", '')
    }
    else if (control.value.indexOf('>') > -1) {
        invalidControls += "> "
        control.value = control.value.replace(">", '')
    }

    if (invalidControls.length != 0) {
        //alert("Please dont use characters like " + invalidControls);
        return;
    }
}

function Trim(s) {
    // Remove leading spaces and carriage returns
    while ((s.substring(0, 1) == ' ') || (s.substring(0, 1) == '\n') || (s.substring(0, 1) == '\r'))
    { s = s.substring(1, s.length); }

    // Remove trailing spaces and carriage returns
    while ((s.substring(s.length - 1, s.length) == ' ') || (s.substring(s.length - 1, s.length) == '\n') || (s.substring(s.length - 1, s.length) == '\r'))
    { s = s.substring(0, s.length - 1); }

    return s;
}



function IsAlphanumeric(alphane) {
    var numaric = alphane;
    for (var j = 0; j < numaric.length; j++) {
        var alphaa = numaric.charAt(j);
        var hh = alphaa.charCodeAt(0);
        if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || (hh == 32)) {
        }
        else {
            return false;
        }
    }
    return true;
}

function AutoRedirectToFrame() {
    var url = top.location.href.substring(top.location.href.toLowerCase().indexOf('admin/') + 6);

    if (top.location.href.toLowerCase().lastIndexOf("frames.aspx") < 0) {
        if (top.location.href.toLowerCase().lastIndexOf("mediamanagement") < 0)
            top.location.href = "Frames.aspx?ReturnUrl=" + url;
        else
            top.location.href = url;
    }
}


function leapYear(Year) {
    return (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) ? 1 : 0;
}

function getDaysInMonth(month, year) {
    var days;
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
        days = 31;
    else if (month == 4 || month == 6 || month == 9 || month == 11)
        days = 30;
    else if (month == 2) {
        if (leapYear(year) == 1)
            days = 29;
        else
            days = 28;
    }
    return (days);
}

function validateDate(d, m, y, errorMsg, changedOne) {
    var day = FindObject(d);
    var month = FindObject(m);
    var year = FindObject(y);
    var changed = FindObject(changedOne);

    var myDate = day.value;
    var myMonth = month.selectedIndex + 1;
    var myYear = year.value;

    if (parseInt(myDate) > getDaysInMonth(myMonth, myYear)) {
        alert(errorMsg);
        changed.selectedIndex = 0;
        return false;
    }
    return true;
}


// w: dialog width
// h: dialogheight
// rs:1/0 resizable
// sc:1/0 scrollable
// mn:1/0 menuvisible
// Examples:
// <a href="myUrl" onclick="return Popup(this.href,400,300,0,0,0);">click to popup</a>
function Popup(url, w, h, rs, sc, mn, wn) {
    if (wn == undefined) {
        wn = 'bsh';
    }


    t = (screen.height / 2) - (h / 2);
    l = (screen.width / 2) - (w / 2);
    newwindow = window.open(url, wn, 'toolbar=0, status=1, menubar=' + mn + ', location=0, resizable=' + rs + ', scrollbars=' + sc + ', width=' + w + ', height=' + h + ', top=' + t + ', left=' + l);
    if (window.focus) { newwindow.focus() }
    return false;
}

function Popup1(url, rs, sc, mn) {
    // return Popup(url,600,400,rs,sc,mn);
    w = 600;
    h = 400;
    t = (screen.height / 2) - (h / 2);
    l = (screen.width / 2) - (w / 2);
    newwindow = window.open(url, 'bsh', 'toolbar=0, status=1, menubar=' + mn + ', location=0, resizable=' + rs + ', scrollbars=' + sc + ', width=' + w + ', height=' + h + ', top=' + t + ', left=' + l);
    if (window.focus) { newwindow.focus() }
    return false;
}


function Popup2(url, target, properties) {
    if (target == '_self') {
        window.open(url, '_self');
    }
    else if (target == '_blank_') {
        window.open(url, '_blank');
    }
    else {
        var strwidth = 'width';
        var strheight = 'height';
        var strStatus = 'status';
        var startIndex;
        var endIndex;
        var width;
        var height;


        startIndex = properties.indexOf(strheight);
        strheight = strheight + '=';
        startIndex = startIndex + strheight.length;
        endIndex = properties.indexOf(strwidth);
        height = properties.substring(startIndex, endIndex - 1);


        startIndex = properties.indexOf(strwidth);
        strwidth = strwidth + '=';
        startIndex = startIndex + strwidth.length;
        endIndex = properties.indexOf(strStatus);
        width = properties.substring(startIndex, endIndex - 1);

        var leftDim = (screen.width - width) / 2;
        var topDim = (screen.height - height) / 2;
        var hwString = 'left=' + leftDim + ',top=' + topDim + ',' + properties;
        window.open(url, '_blank', hwString);
    }
    return false;
}


function OpenPopup(url, target, properties) {
    if (target == '_self') {
        window.open(url, '_self');
    }
    else if (target == '_blank_') {
        window.open(url, '_blank');
    }
    else {
        var strwidth = 'width';
        var strheight = 'height';
        var strStatus = 'status';
        var startIndex;
        var endIndex;
        var width;
        var height;


        startIndex = properties.indexOf(strheight);
        strheight = strheight + '=';
        startIndex = startIndex + strheight.length;
        endIndex = properties.indexOf(strwidth);
        height = properties.substring(startIndex, endIndex - 1);


        startIndex = properties.indexOf(strwidth);
        strwidth = strwidth + '=';
        startIndex = startIndex + strwidth.length;
        endIndex = properties.indexOf(strStatus);
        width = properties.substring(startIndex, endIndex - 1);

        var leftDim = (screen.width - width) / 2;
        var topDim = (screen.height - height) / 2;
        var hwString = 'left=' + leftDim + ',top=' + topDim + ',' + properties;
        window.open(url, '_blank', hwString);
    }
}

function Popup3(w, h, url, rs, sc, mn) {
    t = (screen.height / 2) - (h / 2);
    l = (screen.width / 2) - (w / 2);
    newwindow = window.open(url, 'bsh', 'toolbar=0, status=1, menubar=' + mn + ', location=0, resizable=' + rs + ', scrollbars=' + sc + ', width=' + w + ', height=' + h + ', top=' + t + ', left=' + l);
    if (window.focus) { newwindow.focus() }
    return false;
}


// base page function for Admin
function AvoidHistoryBack__() {
    if (window.history.length > 0)
        window.history.forward();
}

function emailCheck(emailStr) {
    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (matchArray == null) {
        return false;
    }

    var user = matchArray[1];
    var domain = matchArray[2];

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            return false;
        }
    }

    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            return false;
        }
    }

    if (user.match(userPat) == null) {
        return false;
    }

    var IPArray = domain.match(ipDomainPat);

    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false;
            }
        }
        return true;
    }

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;

    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            return false;
        }
    }

    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
	domArr[domArr.length - 1].search(knownDomsPat) == -1) {
        return false;
    }

    if (len < 2) {
        return false;
    }

    return true;
}

//PROGRESS LAYER CODES START
///////////////////////////////////////////////////////////////////////////////////////
function ActivateProgressArea() {
    if (gloDisplayProgress) {
        for (i = 0; i < document.forms[0].elements.length; i++) {
            elm = document.forms[0].elements[i];
            if (elm.type == 'select-one' || elm.type == 'select-multiple') {
                elm.style.visibility = "HIDDEN";
            }
        }

        var progressBar = 'progressBar';
        var progressBarUnSeen = 'progressBarUnSeen';

        if (document.getElementById(progressBar) == null) return;
        document.getElementById(progressBar).style.visibility = '';
        document.getElementById(progressBar).style.zIndex = 1001;
        document.getElementById(progressBarUnSeen).style.visibility = '';
        document.getElementById(progressBarUnSeen).style.zIndex = 1000;
        document.getElementById(progressBarUnSeen).style.height = document.body.scrollHeight;
        document.getElementById(progressBarUnSeen).style.width = document.body.scrollWidth;
    }
    gloDisplayProgress = true;
}

function getPageScrollTop() {
    var yScrolltop;
    if (self.pageYOffset) {
        yScrolltop = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        yScrolltop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        yScrolltop = document.body.scrollTop;
    }
    arrayPageScroll = new Array('', yScrolltop)
    return arrayPageScroll;
}

function getPageSize() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;

    arrayPageSize = new Array(w, h)
    return arrayPageSize;
}
///////////////////////////////////////////////////////////////////////////////////////
//PROGRESS LAYER CODES END


//Copyrights Management Crosscut, used in news
function linkClick(width, height, pageId) {
    x = (640 - width) / 2, y = (480 - height) / 2;

    if (screen) {
        y = (screen.availHeight - height) / 2;
        x = (screen.availWidth - width) / 2;
    }

    window.open('ExpiredPage.aspx?pageId=' + pageId, 'newWin', 'width=' + width + ',height=' + height + ',screenX=' + x + ',screenY=' + y + ',top=' + y + ',left=' + x);
}
///Copyrights Management Crosscut, used in news

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

// For country selection dropdownlist
function RedirectToCountry(elem) {
    if (document.forms[0].elements['myCountries_ddCountry']) {
        var strSelection;
        strSelection = document.forms[0].elements['myCountries_ddCountry'].options[document.forms[0].elements['myCountries_ddCountry'].selectedIndex].value;
        if (strSelection != "") {
            document.location.href = strSelection;
        }
    }
}
//For Ajax
function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}
// remove special characters like "$" and "," etc...
function filterSpecialChars(str) {
    /* HTML Replaces */
    str = str.replace('&amp;', " "); // html -> &
    str = str.replace('&lt;', " ");  // html -> <
    str = str.replace('&gt;', " ");  // html -> >

    /* Unicode Character Replace */
    var newStr = '';
    for (var i = 0; i <= str.length - 1; i++)
        if (escape(str.charAt(i)) != '%AE' /* ® */
				&& escape(str.charAt(i)) != '%A9' /* © */
				&& escape(str.charAt(i)) != '%BD' /* ½ */) {
            //DEBUG ::: alert('in : ' + str.charAt(i) + ' --> ' + escape(str.charAt(i)));
            newStr += str.charAt(i);
        }
    /* Ascii Character Replace */
    re = /\$|,|\/|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
    newStr = newStr.replace(re, " ");
    return newStr.replace("  ", " ").replace("  ", " ").replace("  ", " ").replace("  ", " ");
}

//moved from BasicSearch.ascx
function GenerateSearch(url, msg) {
    var expressionString = "";
    var q = FindObject('txtConditionText').value;
    q = Trim(q);

    q = filterSpecialChars(q);

    if (q != "") {
        if (q == "A++") {
            q = "APlusPlus";
        }
        if (q == "a++") {
            q = "APlusPlus";
        }
        searchText = q.split(" ");
        for (i = 0; i < searchText.length; i++) {
            if (Trim(searchText[i]) != "") {
                if (i < searchText.length - 1)
                    expressionString += "0|2|" + searchText[i].replace("'", "''") + "|0|1|";
                else
                    expressionString += "0|2|" + searchText[i].replace("'", "''") + "|0|";
            }
        }
        top.location.href = url + expressionString;
    }
    else {
        alert(msg);
    }

    return false;
}
function Del(Word) {
    a = Word.indexOf("<");
    b = Word.indexOf(">");
    len = Word.length;
    c = Word.substring(0, a);
    if (b == -1)
        b = a;
    d = Word.substring((b + 1), len);
    Word = c + d;
    tagCheck = Word.indexOf("<");
    if (tagCheck != -1)
        Word = Del(Word);
    return Word;
}


var FTS = {
    SiteMapId: jsbase + '/',
    Q: jsbq,
    S: jsbs,
    P: "",
    ExternalFrameName: '',
    ArticleCategoryKey: 'category',
    ArticleCategoryId: function () { return ''; },
    ProductNavigationAlert: '',
    Search: function (e, func) {
        if (e == 1) {
            func(keywords); return false;
        }
        var keyCode = e.keyCode ? e.keyCode : e.which;

        if (keyCode == 13) {
            eval(func);
            return false;
            // func(keywords);return false;
        }
        return true;
    },
    Article: function (keywords) {
        top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords)) + "&" + FTS.ArticleCategoryKey + "=" + FTS.ArticleCategoryId();
    },
    Site: function (keywords) {
        if (FTS.ExternalFrameName != '') {
            top.frames[FTS.ExternalFrameName].location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords));
        } else {
            top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords));
        }
        return false;
    },
    Site2: function (and, exact, any, none, near) {
        top.location.href = FTS.SiteMapId + FTS.P + (and == '' ? '' : (FTS.Q + '=' + Url.encode(FTS.Escape(and)))) + (exact == '' ? '' : ('&95=' + Url.encode(FTS.Escape(exact)))) + (any == '' ? '' : ('&97=' + Url.encode(FTS.Escape(any)))) + (none == '' ? '' : ('&98=' + Url.encode(FTS.Escape(none)))) + (near == '' ? '' : ('&99=' + Url.encode(FTS.Escape(near))));
    },
    Site3: function (keywords, query) {
        top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords)) + query;
    },
    Site4: function (keywords, query) {
        top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords)) + "&fgroup=" + Url.encode(FTS.Escape(query));
    },
    Product: function (keywords) {
        top.location.href = jsbase + '/' + FTS.S + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords));
    },
    Product2: function (keywords, catalogue, category, family) {
        top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords)) + (catalogue == '' ? '' : '&' + catalogue) + (category == '' ? '' : '&' + category) + (family == '' ? '' : '&' + family);
    },
    ProductBoschNewCI: function (keywords, catalogue, category, family) {
        top.location.href = FTS.SiteMapId + FTS.P + FTS.Q + '=' + Url.encode(FTS.Escape(keywords)) + (catalogue == '' ? '' : '&' + catalogue) + (category == '' ? '' : '&' + category) + (family == '' ? '' : '&' + family) + (jsproductStr == '' ? '' : '&' + jsproductStr);
    },
    ProductNavigation: function (optionValue) {
        if (optionValue == "") {
            if (FTS.ProductNavigationAlert != '') alert(FTS.ProductNavigationAlert);
        } else
            top.location.href = optionValue;

    },
    Feature: function (keywords) {
        top.location.href = jsbase + '/' + FTS.S + FTS.P + '95=' + Url.encode(FTS.Escape(keywords));
    },
    Escape: function (word) {
        if (word == "A++") word = "APlusPlus";
        if (word == "a++") word = "APlusPlus";

        word = word.replace(/<strong>/g, "__l__").replace(/<\/strong>/g, "__r__");
        word = word.replace(/<b>/g, "__bl__").replace(/<\/b>/g, "__br__");
        word = word.replace(/,/g, "+");
        word = word.replace(/&amp;/g, "+");
        word = word.replace(/&/g, "+");
        word = word.replace(/ /g, "+");
        word = word.replace(/</g, "+");
        word = word.replace(/>/g, "+");

        return word;
    }
}
FTS.P = typeof (window["jsbp"]) == "undefined" ? "" : jsbp;

function ProductSearchFor(q) {
    if (q == "A++") {
        q = "APlusPlus";
    }
    if (q == "a++") {
        q = "APlusPlus";
    }
    FTS.Feature(q);
}


function BaseGenerateProductSearch(i, exactSearch, urlForRedirect, alertEnterConditionText, ddlClientId, alertlblSelectAProductCategory, redirectForItem1, redirectForItem2, redirectForItem3, isJSActiveLocaleIsNull) {
    expressionString = "";

    var q = FindObject('txtProductQuery').value;
    q = Trim(q);
    q = Del(q);
    if (exactSearch == false)
        q = filterSpecialChars(q);

    if (i == 1) {
        if (q != "") {
            if (exactSearch) {
                expressionString += "0|2|" + q + "|0|";
            }
            else {
                searchText = q.split(" ");
                for (i = 0; i < searchText.length; i++) {
                    if (Trim(searchText[i]) != "") {
                        if (i < searchText.length - 1)
                            expressionString += "0|2|" + searchText[i].replace("'", "''") + "|0|2|";
                        else
                            expressionString += "0|2|" + searchText[i].replace("'", "''") + "|0|";
                    }
                }
            }
            top.location.href = urlForRedirect + expressionString;
        }
        else {
            alert(alertEnterConditionText);
        }
    }
    else {
        if (!isJSActiveLocaleIsNull) {
            itemId = FindObject(ddlClientId).value.split("~");
            if (itemId[0] == 0)
                alert(alertlblSelectAProductCategory);
            if (itemId[0] == 1)
                top.location.href = redirectForItem1 + itemId[1];
            else if (itemId[0] == 2)
                top.location.href = redirectForItem2 + itemId[1];
            else if (itemId[0] == 3)
                top.location.href = redirectForItem3 + itemId[1];
        }
    }

    return false;
}



function clearColumnDiv(pID, sVisible) {
    var el = window.document.getElementById(pID);
    if (el) if (sVisible == '') el.style.display = 'none';
}

// Only Use Bosch Style
function fixColumnDiv(pID, sVisible) {
    var el = window.document.getElementById(pID);
    if (el) if (sVisible == '') el.className = 'HeaderFixDiv';
}

function makeTableOrderable(objCell) {
    if (objCell.onclick.toString().indexOf("makeTableOrderable") > -1) {
        var objTable = objCell
        while (objTable.tagName.toLowerCase() != "table") {
            objTable = objTable.parentNode;
        }
        var sortType = 0;
        var tableId = "#" + objTable.id;
        if (objTable.id == 'tblMediaFiles') {
            JQ(tableId).tablesorter(
			{
			    headers:
				{
				    0: { sorter: false },
				    4: { sorter: false }
				},
			    sortList: [[objCell.cellIndex, sortType]]
			});
        }
        else if (objTable.id == 'tblDefaultPageSettings') {
            JQ(tableId).tablesorter(
			{
			    headers:
				{
				    1: { sorter: false },
				    2: { sorter: false }
				},
			    sortList: [[objCell.cellIndex, sortType]]
			});
        }
        else if (objTable.id == 'tblProductCodes') {
            JQ(tableId).tablesorter({
                sortList: [[objCell.cellIndex, sortType]]
            });
        }
        else {
            JQ(tableId).tablesorter(
						{
						    headers:
							{
							    4: { sorter: false },
							    5: { sorter: false },
							    6: { sorter: false }
							},
						    sortList: [[objCell.cellIndex, sortType]]
						});
        }
        objCell.click();
    }
}

function ExpandNode(NodeId) {

    var objDiv = document.getElementById("Exp" + NodeId);

    var objChild = document.getElementById("Child" + NodeId);

    if (objChild != null & objDiv != null) {
        if (objChild.style.display == 'none') {
            objChild.style.display = 'block';
            objDiv.innerHTML = "<span>-</span>";
        }
        else {
            objChild.style.display = 'none';
            objDiv.innerHTML = "<span>+</span>";
        }
    }

}

function linkCode(RSID, obj, linkName) {
    var s = s_gi(RSID);
    s.tl(obj, 'o', linkName);
}

// DomValidation.js.
//<script>
var Page_DomValidationVer = "2";
var Page_IsValid = true;
var Page_BlockSubmit = false;
var Invisible_Text_Value = "______________________";

function ValidatorUpdateDisplay(val) {
    //if (typeof(val.display) == "string") {    
    if (val.display == "None") {
        return;
    }


    if (val.display == "Dynamic" || val.display == null) {
        val.style.display = val.isvalid ? "none" : "inline";
        if (typeof (UpdateNewCIValidatorDisplay) == 'function') {
            UpdateNewCIValidatorDisplay(val);
        }
        return;
    }
    // }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
    if (typeof (UpdateNewCIValidatorDisplay) == 'function') {
        UpdateNewCIValidatorDisplay(val);
    }
}

function ValidatorUpdateIsValid() {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (!Page_Validators[i].isvalid) {
            Page_IsValid = false;
            return;
        }
    }
    Page_IsValid = true;
}

function ValidatorHookupControl(control, val) {
    if (control != null) {
        if (typeof (control.Validators) == "undefined") {
            control.Validators = new Array;
            var ev = control.onchange;
            var func = new Function("ValidatorOnChange('" + control.id + "');");
            control.onchange = func;
        }
        control.Validators[control.Validators.length] = val;
    }
}

function ValidatorGetValue(id) {
    var control;
    control = document.getElementById(id);
    if (control == null)
        return "";

    //HACK
    if (control.style.display == 'none')
        return Invisible_Text_Value;

    if (typeof (control.value) == "string") {
        return control.value;
    }
    var j;
    if (typeof (control.tagName) == "undefined" && typeof (control.length) == "number") {
        var j;
        for (j = 0; j < control.length; j++) {
            var inner = control[j];
            if (typeof (inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    for (j = 0; j < 1000; j++) {
        var inner = document.getElementById(id + '_' + j);
        if (inner == null) break;
        if (typeof (inner.value) == "string" && inner.type == "radio" && inner.checked) {
            return inner.value;
        }
    }
    return "";
}

function Page_ClientValidate() {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i]);
    }
    ValidatorUpdateIsValid();
    requiredForCheckList();
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}

function ValidatorCommonOnSubmit() {
    var returnValue = !Page_BlockSubmit;
    Page_BlockSubmit = false;
    return returnValue;
}

function ValidatorEnable(val, enable) {
    val.enabled = (enable != false);
    ValidatorValidate(val);
    ValidatorUpdateIsValid();
}

function ValidatorOnChange(controlID) {
    var cont = document.getElementById(controlID);
    var vals = cont.Validators;
    var i;

    if (vals != null) {
        for (i = 0; i < vals.length; i++) {
            ValidatorValidate(vals[i]);
        }
    }
    ValidatorUpdateIsValid();
}

function ValidatorValidate(val) {
    val.isvalid = true;
    if (val.enabled != false) {
        if (typeof (val.evalfunc) == "function") {
            val.isvalid = val.evalfunc(val);
        }
    }
    ValidatorUpdateDisplay(val);
}

function ValidatorOnLoad() {
    if (typeof (Page_Validators) == "undefined")
        return;

    var i, val;
    for (i = 0; i < Page_Validators.length; i++) {
        val = Page_Validators[i];
        var evalFunction = val.getAttribute("evaluationfunction");
        if (typeof (evalFunction) == "string") {
            eval("val.evalfunc = " + evalFunction + ";");
        }
        var isValidAttribute = val.getAttribute("isvalid");
        if (typeof (isValidAttribute) == "string") {
            if (isValidAttribute == "False") {
                val.isvalid = false;
                Page_IsValid = false;
            }
            else {
                val.isvalid = true;
            }
        } else {
            val.isvalid = true;
        }
        var controlToValidate = val.getAttribute("controltovalidate");
        if (typeof (controlToValidate) == "string" && controlToValidate != "") {
            ValidatorHookupControl(document.getElementById(controlToValidate), val);
        }
        var controlToHookup = val.getAttribute("controlhookup");
        if (typeof (controlToHookup) == "string") {
            ValidatorHookupControl(document.getElementById(controlToHookup), val);
        }
    }
    Page_ValidationActive = true;
}

function RegularExpressionValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.getAttribute("controltovalidate"));
    var childs = val.parentNode.childNodes;
    var doublecheckforvalid = false;

    foreach(childs, function (a) {
        if (a.tagName == "SPAN") {
            if (a.getAttribute("evaluationfunction") == "RequiredFieldValidatorEvaluateIsValid")
                doublecheckforvalid = true;
        }
    })

    if (doublecheckforvalid) {
        if (val == "") {
            return false;
        }
        if (val.getAttribute("validationexpression") == null || val.getAttribute("validationexpression") == "")
            return true;
    } else {
        if (value == "" || val.getAttribute("validationexpression") == null || val.getAttribute("validationexpression") == "")
            return true;
    }
    var rx = new RegExp(val.getAttribute("validationexpression"));
    var matches = rx.exec(value);
    return (matches != null && value == matches[0]);
}

function ValidatorTrim(s) {
    s = s.replace(/^\s+/, '');

    for (var i = s.length - 1; i >= 0; i--) {
        if (/\S/.test(s.charAt(i))) {
            s = s.substring(0, i + 1);
            break;
        }
    }

    return s;

    /*
    var m = s.match(/^\s*(.*\S)\s*$/);alert(m);
    return (m == null) ? "" : m[1];
    */
}

function RequiredFieldValidatorEvaluateIsValid(val) {
    return (ValidatorTrim(ValidatorGetValue(val.getAttribute("controltovalidate"))) != ValidatorTrim(val.getAttribute("initialvalue")));
}

function requiredForCheckList() {
    var SpanList = [];
    _inputsList = [];
    _spanList = [];
    var SpanList = document.getElementsByTagName("SPAN");

    foreach(SpanList, function (a) {
        if (typeof (a) == "object") {
            if (typeof (a.getAttribute) != "undefined") {
                if (a.getAttribute("customvalidation") != "undefined") {
                    var customattr = a.getAttribute("customvalidation");
                    if (customattr != "" && customattr != "undefined" && customattr) {
                        _inputsList = [];
                        var _parentNode = document.getElementById(customattr);
                        getChildNodesByInput(_parentNode);
                        controlCheckOrNot(_inputsList, a);
                    }
                }
            }
        }
    });
}

function getChildNodesByInput(_parentNode) {
    var _childNodes = _parentNode.childNodes;
    var _childNodesLength = _childNodes.length;
    if (_childNodesLength > 0) {
        for (var i = 0; i < _childNodesLength; i++) {
            var _childNode = _childNodes[i];
            if (_childNode.tagName == "INPUT") {
                _inputsList.push(_childNode);
            }

            if (_childNode.childNodes.length > 0) {
                getChildNodesByInput(_childNode);
            }
        }

    }
}

function controlCheckOrNot(_inputsList, a) {
    var checkSpan = true;
    var i = 0;
    foreach(_inputsList, function (element) {
        if (!element.checked)
            i++;
    });

    if (i == _inputsList.length) {
        a.style.display = "inline";
        checkSpan = false;
        Page_IsValid = false;
    }

    if (!checkSpan) {
        _spanList.push(a);
    }
}

function ValidatorConvert(op, dataType, val) {
    function GetFullYear(year) {
        return (year + parseInt(val.century)) - ((year < val.cutoffyear) ? 0 : 100);
    }
    var num, cleanInput, m, exp;
    if (dataType == "Integer") {
        exp = /^\s*[-\+]?\d+\s*$/;
        if (op.match(exp) == null)
            return null;
        num = parseInt(op, 10);
        return (isNaN(num) ? null : num);
    }
    else if (dataType == "Double") {
        exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.decimalchar + "(\\d+))?\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        cleanInput = m[1] + (m[2].length > 0 ? m[2] : "0") + "." + m[4];
        num = parseFloat(cleanInput);
        return (isNaN(num) ? null : num);
    }
    else if (dataType == "Currency") {
        exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar + ")*)(\\d+)"
                        + ((val.digits > 0) ? "(\\" + val.decimalchar + "(\\d{1," + val.digits + "}))?" : "")
                        + "\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        var intermed = m[2] + m[5];
        cleanInput = m[1] + intermed.replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
        num = parseFloat(cleanInput);
        return (isNaN(num) ? null : num);
    }
    else if (dataType == "Date") {
        var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\s*$");
        m = op.match(yearFirstExp);
        var day, month, year;
        if (m != null && (m[2].length == 4 || val.dateorder == "ymd")) {
            day = m[6];
            month = m[5];
            year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
        }
        else {
            if (val.dateorder == "ymd") {
                return null;
            }
            var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
            m = op.match(yearLastExp);
            if (m == null) {
                return null;
            }
            if (val.dateorder == "mdy") {
                day = m[3];
                month = m[1];
            }
            else {
                day = m[1];
                month = m[3];
            }
            year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
        }
        month -= 1;
        var date = new Date(year, month, day);
        return (typeof (date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
    }
    else {
        return op.toString();
    }
}
function ValidatorCompare(operand1, operand2, operator, val) {
    var dataType = val.type;
    var op1, op2;
    if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
        return false;
    if (operator == "DataTypeCheck")
        return true;
    if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
        return true;
    switch (operator) {
        case "NotEqual":
            return (op1 != op2);
        case "GreaterThan":
            return (op1 > op2);
        case "GreaterThanEqual":
            return (op1 >= op2);
        case "LessThan":
            return (op1 < op2);
        case "LessThanEqual":
            return (op1 <= op2);
        default:
            return (op1 == op2);
    }
}
function CompareValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.getAttribute("controltovalidate"));
    if (ValidatorTrim(value).length == 0)
        return false;
    var compareTo = "";
    if (null == document.getElementById(val.getAttribute("controltocompare"))) {
        if (typeof (val.getAttribute("valuetocompare")) == "string") {
            compareTo = val.getAttribute("valuetocompare");
        }
    }
    else {
        compareTo = ValidatorGetValue(val.getAttribute("controltocompare"));
    }
    return ValidatorCompare(value, compareTo, val.operator, val);
}

function ValidationSummaryOnSubmit() {
    var _sArray = new Array();
    if (typeof (Page_ValidationSummaries) == "undefined")
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid) {
            if (summary.getAttribute("showsummary") != "False") {
                summary.style.display = "";
                if (typeof (summary.getAttribute("displaymode")) != "string") {
                    summary.setAttribute("displaymode", "BulletList");
                }
                switch (summary.getAttribute("displaymode")) {
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        final = "";
                        break;
                    case "BulletList":
                    default:
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        final = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        final = "<br>";
                        break;
                }
                s = "";
                if (typeof (summary.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("headertext") + headerSep;
                }
                s += first;

                var _initPage_Validators = new Array();
                var _controlinitPage_Validators = true;
                for (i = 0; i < Page_Validators.length; i++) {

                    var a = Page_Validators[i];
                    _controlinitPage_Validators = true;

                    for (var j = 0; j < _initPage_Validators.length; j++) {
                        if (!_initPage_Validators[j].isvalid) {
                            if (_initPage_Validators[j].getAttribute("errormessage") == a.getAttribute("errormessage")) {
                                _controlinitPage_Validators = false;
                            }
                        }
                    }

                    if (_controlinitPage_Validators) {
                        _initPage_Validators.push(a);
                    }

                }


                for (i = 0; i < _initPage_Validators.length; i++) {
                    if (!_initPage_Validators[i].isvalid && typeof (_initPage_Validators[i].getAttribute("errormessage")) == "string") {
                        s += pre + _initPage_Validators[i].getAttribute("errormessage") + post;
                    }
                }

                for (i = 0; i < _spanList.length; i++) {
                    s += pre + _spanList[i].getAttribute("errormessage") + post;
                }
               
                s += final;
                summary.innerHTML = s;
                window.scrollTo(0, 0);
            }
            if (summary.getAttribute("showmessagebox") == "True") {
                s = "";
                if (typeof (summary.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("headertext") + "<BR>";
                }

                var _initPage_Validators = new Array();
                var _controlinitPage_Validators = true;
                for (i = 0; i < Page_Validators.length; i++) {

                    var a = Page_Validators[i];
                    _controlinitPage_Validators = true;

                    for (var j = 0; j < _initPage_Validators.length; j++) {
                        if (!_initPage_Validators[j].isvalid) {
                            if(_initPage_Validators[j].getAttribute("errormessage") == a.getAttribute("errormessage")){
                            _controlinitPage_Validators = false;
                            }
                        }
                    }

                    if (_controlinitPage_Validators) {
                        
                        _initPage_Validators.push(a);
                    }

                }


                for (i = 0; i < _initPage_Validators.length; i++) {
                    if (!_initPage_Validators[i].isvalid && typeof (_initPage_Validators[i].getAttribute("errormessage")) == "string") {
                        switch (summary.getAttribute("displaymode")) {
                            case "List":
                                s += _initPage_Validators[i].getAttribute("errormessage") + "<BR>";
                                break;
                            case "BulletList":
                            default:

                                s += "  - " + _initPage_Validators[i].getAttribute("errormessage") + "\n"; //"<BR>";
                                break;
                            case "SingleParagraph":
                                s += _initPage_Validators[i].getAttribute("errormessage") + " ";
                                break;
                        }
                    }
                }

                for (i = 0; i < _spanList.length; i++) {
                    
                    switch (summary.getAttribute("displaymode")) {
                        case "List":
                            s += _spanList[i].getAttribute("errormessage") + "<BR>";
                            break;
                        case "BulletList":
                        default:
                            s += "  - " + _spanList[i].getAttribute("errormessage") + "\n"; //"<BR>";
                            break;
                        case "SingleParagraph":
                            s += _spanList[i].getAttribute("errormessage") + " ";
                            break;
                    }

                }

                alert(s);
                return;


                span = document.createElement("SPAN");
                alert(span.innerText); return;
                s = span.innerText;
                alert(s);
            }
        }
    }
}



//**********************************
function L(name, otherValue, x) {
    t = document.getElementById(name + '_ctl03_ctl00');
    if (t == null) return;
    for (i = 0; i < 10000; i++) {
        o = document.getElementById(name + '_ctl00_' + i);
        if (o == null) break;
        t.style.display = o.checked ? '' : 'none';
    }
    M(t, x);
}

function M(t, x) {
    if (t.style.display == 'none' && t.value == '')
        t.value = Invisible_Text_Value;
    else if (t.value == Invisible_Text_Value)
        t.value = '';

    if (x) ValidatorOnChange(t.id);
}

function DDL(name, x) {
	t = document.getElementById(name + '_ctl01_ctl00') || document.getElementById(name + '_ctl03_ctl00');
	o = document.getElementById(name + '_ctl00');
	if (o == null || t == null) return;
	t.style.display = o.selectedIndex == o.length - 1 ? '' : 'none';
	M(t, x);
}


function TB(name, maxLength, x) {
    t = document.getElementById(name);
    if (t == null) return;

    if (t.value.length > maxLength)
        t.value = t.value.substring(0, maxLength);
}

var date_arr = new Array;
date_arr[0] = 31;
date_arr[1] = 31;
date_arr[2] = 28;
date_arr[3] = 31;
date_arr[4] = 30;
date_arr[5] = 31;
date_arr[6] = 30;
date_arr[7] = 31;
date_arr[8] = 30;
date_arr[9] = 30;
date_arr[10] = 31;
date_arr[11] = 31;
date_arr[12] = 30;

function UpdateDays(name) {
    d = document.getElementById(name + '_ctl01_ctl00');
    m = document.getElementById(name + '_ctl03_ctl00');
    y = document.getElementById(name + '_ctl05_ctl00');
    cy = parseInt(y[y.selectedIndex].value);

    temp = d.selectedIndex;

    for (x = d.options.length; x <= date_arr[0]; x++) {
        d.options[x] = new Option(x, x);
    }
    if (!dateIsEmpty(y[y.selectedIndex].value) && !dateIsEmpty(m[m.selectedIndex].value)) {
        d.options.length = (new Date(cy, parseInt(m.selectedIndex, 10), 0)).getDate() + 1;
    }
    else {
        d.options.length = (new Date(new Date().getFullYear(), parseInt(m.selectedIndex, 10), 0)).getDate() + 1;
    }
    //if (m.selectedIndex == 2 && ((cy % 4 == 0 && cy % 100 != 0) || (y.selectedIndex == 0))) d.options[d.options.length] = new Option(29, 29);

    if (temp >= d.options.length) temp = d.options.length - 1;
    d.options[temp].selected = true;
}

function dateIsEmpty(d) {
    if (d == '' || d == '-1' || d == '_____1' || d == '0') {
        return true;
    } else {
        return false;
    }
}
