var undefined; // undefined

// Browser
function Browser() { }
Browser.Agent = navigator.userAgent.toLowerCase();
Browser.Version = Browser.Agent.match(/msie ([^;]+);/);
Browser.IE = Browser.Agent.indexOf("msie") != -1;
Browser.Moz = Browser.Agent.indexOf("gecko") != -1;
Browser.Opera = Browser.Agent.indexOf("opera") != -1;
//if (Browser.Opera) Browser.Moz=true;
Browser.Other = Browser.Agent.search(/(msie|mozilla)/i) == -1;
Browser.Version = Browser.Version && Browser.Version.length ? +Browser.Version[1] : null,

Browser.XML = function () { }
Browser.XML.DOM = function () { if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLDOM"); else if (document.implementation && document.implementation.createDocument) return document.implementation.createDocument("", "", null); }
Browser.XML.HTTP = function () { if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); }

// DOM
function DOM() { }
DOM.Doc = document;

DOM.Get = function (id) { return this.Doc.getElementById(id); }
DOM.Create = function (tag, parent, className) { var el; if (Browser.Moz) el = document.mozCreateElement(tag); else el = this.Doc.createElement(tag); if (parent) parent.appendChild(el); if (className) el.className = className; return el; }
DOM.Event = function (evt, func, o) { if (!o) o = window; if (o.attachEvent) o.attachEvent("on" + evt, func); else if (o.addEventListener) o.addEventListener(evt, func, false); }
DOM.Deevent = function (evt, func, o) { if (!o) o = window; if (o.detachEvent) o.detachEvent("on" + evt, func); else if (o.removeEventListener) o.removeEventListener(evt, func, false); }
DOM.Find = function (o, tag, prop, eq) { tag = tag.toUpperCase(); while (o && o != this.Doc.documentElement && ((prop == undefined && o.tagName != tag) || (prop && ((eq != undefined && (o.tagName != tag || o[prop] != eq)) || (eq == undefined && o.tagName != tag))))) o = o.parentNode; return o.tagName == tag ? o : null; }

// Classes
DOM.Classes = {};
DOM.Classes.Add = function (el, cls) { if (el) return !this.Contains(el, cls) ? el.className += " " + cls : el.className; }
// google gadgets fix (by evgeny)
//DOM.Classes.Remove=function (el,cls) {if (el) return el.className=el.className.replace(new RegExp("\\b"+cls.ToRX()+"\\b"),"");}
DOM.Classes.Remove = function (el, cls) { if (el) return el.className = el.className.replace(new RegExp("\\b" + ToRX(cls) + "\\b"), ""); }
//DOM.Classes.Contains=function (el,cls) {if (el) return new RegExp("\\b"+cls.ToRX()+"\\b").test(el.className);}
DOM.Classes.Contains = function (el, cls) { if (el) return new RegExp("\\b" + ToRX(cls) + "\\b").test(el.className); }
DOM.Classes.Current = function (el, prop) { if (el) return el.currentStyle[prop]; }
DOM.Classes.Toggle = function (el, cls) { cls = cls || "hidden"; this[this.Contains(el, cls) ? "Remove" : "Add"](el, cls); }

// Img - Over
// DOM.ImgToggle(o);
DOM.ImgToggle = function (o, b) { var src = o.src; var toggle = b == undefined; var rxOff = /([^_])(\.\w+)$/, rxOn = /_(\.\w+)$/; if (toggle) b = rxOff.test(src); if (b) src = src.replace(rxOff, "$1_$2"); else src = src.replace(rxOn, "$1"); return o.src = src; }

// Positions
DOM.Pos = {};
DOM.Pos.X = function (o) { for (var x = 0; o; x += o.offsetLeft, o = o.offsetParent); return x; }
DOM.Pos.Y = function (o) { for (var y = 0; o; y += o.offsetTop, o = o.offsetParent); return y; }

//rem no-existing-files
/*if (Browser.Moz) {
var mozScript = document.createElement("script");
mozScript.type = "text/javascript";
mozScript.defer = true;
mozScript.src = "moz._js";
document.getElementsByTagName("head")[0].appendChild(mozScript);
}*/

/*********** functions that are used by BuildRealSite.cs on page building process **********/

/*********** function that handle text encoding on page **********/

// handle full image popup
function fnopenFullImage(obj, suffix) {
    var destPath =  '/';

    if (location.href.indexOf('/CMS/') > -1) {return;
        /*var cPath = $('#clientPath').val();
        var lang = $('#lang').val();
        if ($('#srcId').val() == 'fb') {
            destPath = fPath.value;
            suffix = '';
        } else {
            destPath = ('xml/' + lang + '/');
            suffix = '-sp';
        }
        obj = obj.replace('/images/', fPath.value);
        if ($('#srcId').val() == 'sp') {
            $(src).attr('href', 'xml/' + lang + '/' + 'FullImageView-sp.htm?image=' + obj);
            //$(src).attr('target', $(window.parent.document).find('iframe').attr('id'));
            //window.navigate('xml/' + lang + '/' + 'FullImageView-sp.htm?image=' + obj);
            return;
        }*/
    }

    var popup = window.open(destPath + 'FullImageView' + (typeof (suffix) != 'undefined' ? suffix : '') + '.htm?image=' + obj, 'popup', 'toolbar=no,location=no,menubar=no,directories=no,scrollbars=1,resizable=0');
    popup.focus();
}

// encoder for client utf-8 characters
function decoder(str) {
    var _string = "";
    var i = 0;
    var c = c1 = c2 = 0;
    while (i < str.length) {
        c = str.charCodeAt(i);
        if (c < 128) { _string += String.fromCharCode(c); i++; }
        else if ((c > 191) && (c < 224)) {
            c2 = str.charCodeAt(i + 1);
            _string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str.charCodeAt(i + 1);
            c3 = str.charCodeAt(i + 2);
            _string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    return _string;
}

// decoder for client utf-8 characters
function encoder(str) {
    //str = str.replace(/\\r\\n/g,'\\n');
    var utftext = '', c;
    for (var n = 0; n < str.length; n++) {
        c = str.charCodeAt(n);
        if (c < 128) { utftext += String.fromCharCode(c); }
        else if ((c > 127) && (c < 2048)) {
            utftext += '%' + ((c >> 6) | 192).toString(16);
            utftext += '%' + ((c & 63) | 128).toString(16);
        } else {
            utftext += '%' + ((c >> 12) | 224).toString(16);
            utftext += '%' + ((c >> 6) & 63).toString(16) | 128;
            utftext += '%' + ((c & 63) | 128).toString(16);
        }
    }
    return utftext;
}

// instended to distinct news links for specific handling
function isNewsLink(obj) {
    try { return (obj.parentNode.previousSibling.className.indexOf('news') > -1); }
    catch (e) {
        return false;
    }
}

// encodes links with utf-8 characters and process target
function fnConvertLinksToEncoded() {
    var doEncoding = new String(document.body.getAttribute('lang')) != 'false';
    var links = document.getElementsByTagName('A');
    var arrSplits;
    var linkContent;
    for (var i = 0; i < links.length; i++)
    // all links that do not launch javascript fuctions
        if (links[i].href && links[i].href.indexOf('javascript') == -1 && links[i].href.innerText('ppcdomain') == -1) {
            // save content in case of '@' in content
            linkContent = links[i].innerHTML;
            if (doEncoding) {
                if (navigator.appVersion.indexOf('MSIE 6.0') > -1)
                    links[i].href = encoder(links[i].href).replace(/%c3%97%c2/ig, '%d7').replace(/%c3%83%c2/ig, '%c3').replace(/%c3%85%c2/ig, '%c5');
                else
                    links[i].href = encoder(links[i].href);
            }
            else {
                /*if (navigator.appVersion.indexOf('MSIE 6.0')>-1)
                links[i].href = dencoder(links[i].href).replace(/%c3%97%c2/ig,'%d7').replace(/%c3%83%c2/ig,'%c3').replace(/%c3%85%c2/ig,'%c5');
                else*/
                links[i].href = dencoder(unescape(links[i].href));
            }
            if (!isNewsLink(links[i]) &&
		   ((new String(links[i].getAttribute('target'))).length == 0 ||
			(new String(links[i].getAttribute('Target'))).length == 0)) {
                //if (pDomain.indexOf('localhost') == 0 || 
                if (isLinkWebPage(links[i].href) &&
			  links[i].outerHTML.indexOf('internal_link') > -1 && links[i].innerHTML.indexOf('internal_link') == -1)
                //links[i].href.toLowerCase().indexOf('www' + pDomain.toLowerCase()) > -1 || 
                //links[i].href.toLowerCase().indexOf(location.protocol + '//' + pDomain.toLowerCase()) == 0) && 

                    links[i].target = '_self';
                else
                    links[i].target = '_blank';
            }
            if (links[i].type == 'file') links[i].target = '_blank';
            //fix for contact us link from item
            if (links[i].className.indexOf('linkContact') > -1) links[i].target = '_self';

            // fix back link content
            try {
                if (linkContent.indexOf('@') > -1)
                    links[i].innerHTML = linkContent;
            }
            catch (e) { }
        }
}

// is this link to web page ?
function isLinkWebPage(linkText) {
    return (linkText.toLowerCase().indexOf('.htm') != -1 ||
			linkText.toLowerCase().indexOf('.html') != -1 ||
			linkText.toLowerCase().indexOf('#') != -1);
}

// for firefox js code support:
function realPreviousSibling(node) {
    var tempNode = node.previousSibling;
    while (tempNode.nodeType != 1) {
        tempNode = tempNode.previousSibling;
    }
    return tempNode;
}

function realNextSibling(node) {
    var tempNode = node.nextSibling;
    while (tempNode.nodeType != 1) {
        tempNode = tempNode.nextSibling;
    }
    return tempNode;
}
/*********** end **************************************************************************/

/*********** function that handle flash on page **********/
function fnPrintFlash(sFileURL, nWidth, nHeight, id, fparams, fvars) {
    try { document.write(fnGetFlash(sFileURL, nWidth, nHeight, id, fparams, fvars)); }
    catch (e) { alert('Error loading script:\n' + e.message); }
}

function fnGetFlash(sFileURL, nWidth, nHeight, id, fparams, fvars) {
    var RetValue = "";
    if (window.ActiveXObject)
        RetValue += '<object type="application/x-shockwave-flash"' + ((id && id != '') ? ' id="' + id + '"' : '') + ' width="' + nWidth + '" height="' + nHeight + '">';
    else
        RetValue += '<object type="application/x-shockwave-flash"' + ((id && id != '') ? ' id="' + id + '"' : '') + ' width="' + nWidth + '" height="' + nHeight + '" data="' + sFileURL + '">';
    RetValue += '<param name="movie" value="' + sFileURL + '">';
    //document.write('<param name="quality" value="high">');
    if (id && id != '')
        RetValue += '<param name="scale" value="exactfit">';
    RetValue += '<param name="wmode" value="transparent">';
    if (fparams)
        for (fparam in fparams)
            RetValue += '<param name="' + fparam + '" value="' + fparams[fparam] + '">';

    if (fvars) {
        RetValue += '<param name="FlashVars" value="';
        for (fvar in fvars)
            RetValue += fvar + '=' + fvars[fvar] + '&';
        RetValue += '">';
    }
    RetValue += '<embed type="application/x-shockwave-flash" wmode="transparent" ';
    RetValue += 'width="' + nWidth + '" height="' + nHeight + '" src="' + sFileURL + '"/>';
    RetValue += '</object>';
    return RetValue;
}

function fnPrintFlashAdv(sFileURL, nWidth, nHeight, id, sFVars) {
    var fvars = new String(sFVars);
    var fileName = new String(fvars.substring(fvars.lastIndexOf("/") + 1));
    var fullFileName = new String(fvars.substring(fvars.indexOf("sMaskSWF=") + 9));

    sFVars = fvars.replace(/%26/ig, "&");
    if (isCustomFlash(fileName) && sFVars.indexOf("nMaskAlpha=100&nMaskColor=0xFFFFFF") == -1) {
        fnPrintFlash(sFileURL, "100%", "100%", "flash");
    }
    else {
        if (!isCustomFlash(fileName))
            sFileURL = fullFileName;
        if (window.ActiveXObject)
            document.write("<object type=\"application/x-shockwave-flash\" id=\"" + id + "\" width=\"" + nWidth + "\" height=\"" + nHeight + "\">");
        else
            document.write("<object FlashVars=\"" + sFVars + "\" type=\"application/x-shockwave-flash\" id=\"" + id + "\" width=\"" + nWidth + "\" height=\"" + nHeight + "\" data=\"" + sFileURL + "\">");
        document.write("<param name=\"movie\" value=\"" + sFileURL + "\">");
        document.write("<param name=\"quality\" value=\"high\">");
        document.write("<param name=\"wmode\" value=\"transparent\">");
        if (nWidth == '100%' && nHeight == '100%')
            document.write("<param name=\"scale\" value=\"exactfit\">");
        document.write("<param name=\"FlashVars\" value=\"" + sFVars + "\">");
        document.write("</object>");
    }
}

function isCustomFlash(fileName) {
    return fileName.indexOf(".") == fileName.lastIndexOf(".");
}

/*********** end ******************************************/
// function that simulates a virtual click 
// fixes page components the appear sliding out of place: phase 0
function fixRendering() {
    var sidebarMenu = document.getElementById('tdSideCategory');
    var mainMenu = (document.getElementById('divSubMenu0')) ? document.getElementById('divSubMenu0').parentNode.parentNode.parentNode.parentNode : null;
    var mainMenuAs = mainMenu.getElementsByTagName("a");
    if (mainMenuAs != null)
    { mainMenuAs[0].fireEvent("onmouseover"); mainMenuAs[0].fireEvent("onmouseout"); }
    var sidebarMenuAs = sidebarMenu.getElementsByTagName("a");
    if (sidebarMenuAs != null)
    { sidebarMenuAs[0].fireEvent("onmouseover"); sidebarMenuAs[0].fireEvent("onmouseout"); }
}

// handle new top menu design
// this code search particular cell in table to style all column
function findTableUp(obj) {
    var tabObj = obj;
    var success = true;
    while (tabObj.parentNode.tagName.toLowerCase() != "table") {
        if (tabObj.tagName.toLowerCase() == "body")
        { success = false; break; }
        tabObj = tabObj.parentNode;
    }
    // return tbody
    if (success) return tabObj;
    return null;
}

function findTable_2ndColumn_FirstRow(tabObj) {
    var success = true;
    try {
        if (navigator.appName.indexOf('Internet Explorer') > -1) {
            if (tabObj.firstChild.children[1].firstChild.tagName.toLowerCase() != "table")
                success = false;
        } else {
            if (tabObj.firstChild.childNodes.item(1).firstChild.tagName.toLowerCase() != "table")
                success = false;
        }
    }

    catch (e) { success = false; }

    // return inner table
    if (navigator.appName.indexOf('Internet Explorer') > -1)
    { if (success) return tabObj.firstChild.children[1].firstChild; }
    else
    { if (success) return tabObj.firstChild.childNodes.item(1).firstChild; }

    return null;
}

function findTable_2ndColumn_LastRow(tabObj) {
    var success = true;
    try {
        if (navigator.appName.indexOf('Internet Explorer') > -1) {
            if (tabObj.children[2].children[1].firstChild.tagName.toLowerCase() != "table")
                success = false;
        } else {
            if (tabObj.children[2].childNodes.item(1).firstChild.tagName.toLowerCase() != "table")
                success = false;
        }
    }
    catch (e) { success = false; }
    // return inner table
    if (navigator.appName.indexOf('Internet Explorer') > -1)
    { if (success) return tabObj.children[2].children[1].firstChild; }
    else
    { if (success) return tabObj.children[2].childNodes.item(1).firstChild; }

    return null;
}

function setUnderAndAboveCenterCell(obj, cls_down, cls_up) {
    // to find above need to go 3 levels up
    var tabObj = findTableUp(obj);
    if (tabObj == null) return;
    tabObj = findTableUp(tabObj.parentNode);
    if (tabObj == null) return;
    tabObj = findTableUp(tabObj.parentNode);
    if (tabObj == null) return;
    // now we have tabObj set to main upper table

    var index = null;
    try { index = (obj.index) ? obj.index : obj.getAttribute('index'); } catch (e) { }
    if (!index) return;

    // 1st row
    try {
        var tabObj1 = findTable_2ndColumn_FirstRow(tabObj);
        var tdObj1 = findCell(tabObj1, index);
        tdObj1.className = cls_up;
    }
    catch (e) { }
    // last row
    try {
        var tabObj2 = findTable_2ndColumn_LastRow(tabObj)
        var tdObj2 = findCell(tabObj2, index);
        tdObj2.className = cls_down;
    }
    catch (e) { }
}

function setClientWidthUnderAndAboveCenterCell(obj) {
    var cWidth = obj.clientWidth;
    // to find above need to go 3 levels up
    var tabObj = findTableUp(obj);
    if (tabObj == null) return;
    tabObj = findTableUp(tabObj.parentNode);
    if (tabObj == null) return;
    tabObj = findTableUp(tabObj.parentNode);
    if (tabObj == null) return;
    // now we have tabObj set to main upper table

    var index = null;
    try { index = (obj.index) ? obj.index : obj.getAttribute('index'); } catch (e) { }
    if (!index) return;

    // 1st row
    try {
        var tabObj1 = findTable_2ndColumn_FirstRow(tabObj);
        var tdObj1 = findCell(tabObj1, index);
        tdObj1.style.width = cWidth;
    }
    catch (e) { }
    // last row
    try {
        var tabObj2 = findTable_2ndColumn_LastRow(tabObj)
        var tdObj2 = findCell(tabObj2, index);
        tdObj2.style.width = cWidth;
    }
    catch (e) { }
}

function findCell(tabObj, indx) {
    for (var i = 0; i < tabObj.rows.length; i++)
        for (var j = 0; j < tabObj.rows[i].cells.length; j++)
            if (indx == ((tabObj.rows[i].cells[j].index) ?
						 parseInt(tabObj.rows[i].cells[j].index) :
						 parseInt(tabObj.rows[i].cells[j].getAttribute('index'))))
            { return tabObj.rows[i].cells[j]; }
    return null;
}

function setClientWidthMenu() {
    var i = 0;
    var obj = null;
    do {
        obj = document.getElementById('tt' + i);
        if (obj == null) break;
        setClientWidthUnderAndAboveCenterCell(obj);
        i++;
    } while (obj != null);
}

var objStrip, objLeftEar, objRightEar;
var earTop, hasMenu;

function setEars(s, t, m, isPreview) {
    try {
        earTop = t;
        hasMenu = m;
        objStrip = document.getElementById(s);
        document.getElementById("LeftSpace").innerHTML += "<span id='LeftEar'></span>";
        document.getElementById("RightSpace").innerHTML += "<span id='RightEar'></span>";
        objLeftEar = document.getElementById("LeftEar");
        objRightEar = document.getElementById("RightEar");
        setEarStyle(objLeftEar, isPreview);
        setEarStyle(objRightEar, isPreview);
        adjustEars();
        setEarsResize();
    }
    catch (e) { }
}

function adjustEars() {
    try {
        adjustEar(objLeftEar);
        adjustEar(objRightEar);
    }
    catch (e) { }
}

function adjustEar(objEar) {
    var totalWidth = document.body.clientWidth;
    objEar.style.visibility = setEarsVis(totalWidth, objStrip.clientWidth);
    objEar.style.height = objStrip.clientHeight;
    objEar.style.top = getEarTop();
    objEar.style.left = 0;
    objEar.style.width = (totalWidth - getStripWidth()) / 2;
    objEar.style.display = getDisplayStyle();
}

function getStripWidth() {
    if (document.getElementById("tdTopBanner") != null)
        return document.getElementById("tdTopBanner").clientWidth;
    else
        return document.getElementById("tdBottomBanner").clientWidth;
}

function getEarTop() {
    var retValue = earTop;
    if (objStrip.id == "tdBottomBanner" && document.getElementById("tdTopBanner") != null)
        retValue = earTop + document.getElementById("tdTopBanner").clientHeight;
    if (hasMenu)
        retValue += document.getElementById("topMenuBlock").clientHeight;
    return retValue;
}

function setEarsVis(totalWidth, stripWidth) {
    return totalWidth > stripWidth ? "visible" : "hidden";
}

function setEarStyle(objEar, isPreview) {
    objEar.style.position = "relative";
    objEar.style.zIndex = 100;
    var imgPath = (isPreview) ? document.getElementById('earsUrl').value : "images";
    if (objEar.id == "LeftEar") {
        objEar.style.backgroundImage = "url(" + imgPath + "/ear_left.gif)";
        objEar.style.backgroundPosition = "right";
    }
    else {
        objEar.style.backgroundImage = "url(" + imgPath + "/ear_right.gif)";
        objEar.style.backgroundPosition = "left";
    }
}

function getDisplayStyle() {
    return navigator.appVersion.indexOf("MSIE") != -1 ? "inline-block" : "-moz-inline-stack";
}

function setEarsResize() {
    navigator.appVersion.indexOf("MSIE") != -1 ? window.attachEvent('onresize', adjustEars) : window.onresize = adjustEars;
}

// *************************** MenuManager Class *******************************

var MenuManager = {

    setLastTopMenu: function (obj) {
        return; //temp      
        try {
            if (this.isLastTopMenu(obj)) {
                var subMenuName = 'topSubmenuDiv';
                var subMenuBoxName = 'topSubmenuBox';

                if (Env.isSkin(2, 3, 8, 9, 10, 11, 12, 13, 14, 15))
                    subMenuName = 'dropCut';

                if (Env.isSkin(3, 8, 9, 10, 11, 12, 13, 14, 15))
                    subMenuBoxName = 'tdTopSubmenuBox';

                var w2 = parseInt($(obj).find('.' + subMenuBoxName).attr('clientWidth'));
                var w1 = parseInt($(obj).css('width'));
                var x = findPos(obj)[0];
                var x1 = x - (w2 - w1);

                $(obj).find('.' + subMenuName).css('left', x1);
            }
        }
        catch (e) { }
    },

    isLastTopMenu: function (obj) {
        var retValue = false;
        if (Env.isSkin(1, 4, 5)) {
            retValue = (obj == $('.topMenuTD')[$('.topMenuTD').length - 1]);
        }
        else if (Env.isSkin(2, 8, 9, 11, 12, 13, 14, 15)) {
            retValue = (obj == $('.TopMenuH')[$('.TopMenuH').length - 1]);
        }
        else if (Env.isSkin(3, 10)) {
            retValue = (obj == $('.parentTd')[$('.parentTd').length - 1]);
        }
        return retValue;
    },

    setMouseEffects: function () {
        if (Env.isSkin(1, 4, 5)) {
            $('.tr_color_out').hover(function () {
                this.className = 'tr_color_over';
            }, function () {
                this.className = 'tr_color_out';
            });
            $('.topMenuTD').hover(function () {
                $(this).find('.topSubmenuDiv').css('display', 'block');
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.topSubmenuDiv').css('display', 'none');
            });
        }
        else if (Env.isSkin(6)) {
            $('.TopMenuH').hover(function () {
                $(this).find('.tm_background').attr('className', 'tm_background_hover');
                $(this).find('.topSubmenuDiv').css('display', 'block');
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.topSubmenuDiv').css('display', 'none');
                $(this).find('.tm_background_hover').attr('className', 'tm_background');
            });
            $('.tr_color_out').hover(function () {
                $(this).attr('className', 'tr_img_over_' + Env.getDir());
                $(this).find('img').attr('className', 'menu_bullet_over_' + Env.getDir());
            }, function () {
                $(this).attr('className', 'tr_color_out');
                $(this).find('img').attr('className', 'menu_bullet_' + Env.getDir());
            });
        }
        else if (Env.isSkin(7)) {
            $('.TopMenuH').hover(function () {
                if (Env.isCMS)
                    $(this).find('.TopMenuSpan_out').attr('className', 'TopMenuSpan_over');
                else {
                    $(this).find('.tm_background').attr('className', 'tm_background_hover');
                    $(this).find('.top_nav_out').attr('className', 'top_nav_over');
                }
                $(this).find('.topSubmenuDiv').css('display', 'block');
                MenuManager.setLastTopMenu(this);
            }, function () {
                if (Env.isCMS)
                    $(this).find('.TopMenuSpan_over').attr('className', 'TopMenuSpan_out');
                else {
                    $(this).find('.tm_background_hover').attr('className', 'tm_background');
                    $(this).find('.top_nav_over').attr('className', 'top_nav_out');
                }
                $(this).find('.topSubmenuDiv').css('display', 'none');
            });

            $('.topSubmenuBox').find('.tr_color_out').hover(function () {
                $(this).attr('className', 'tr_color_out_act_' + Env.getDir());
            }, function () {
                $(this).attr('className', 'tr_color_out');
            });

            $('.tableSideBar').find('.tr_color_out').hover(function () {
                $(this).attr('className', 'tr_color_out_act_' + Env.getDir());
                $($(this).find('td')[0]).attr('className', 'tr_img_over_' + Env.getDir());
                $(this).find('img').attr('className', 'menu_bullet_over_' + Env.getDir());
                $($(this).find('td')[1]).attr('className', 'tr_color_over_' + Env.getDir());
            }, function () {
                $(this).attr('className', 'tr_color_out');
                $($(this).find('td')[0]).attr('className', 'tr_color_out');
                $(this).find('img').attr('className', 'menu_bullet_' + Env.getDir());
                $($(this).find('td')[1]).attr('className', 'side_text_out');
            });
        }
        else if (Env.isSkin(2)) {
            $('.TopMenuH').mouseover(function () {
                MenuManager.setLastTopMenu(this);
            });
            $('.topMenuBar').find('.tr_color_out,.top_submenu_mouseout').hover(function () {
                this.className = 'top_submenu_mouseover';
                MenuManager.setParentHover(this, true);
            }, function () {
                this.className = 'top_submenu_mouseout';
                MenuManager.setParentHover(this, false);
            });
            $('.link_nav').hover(function () {
                $(this).css('background-image', 'url(/images/tm_background_hover.jpg)');
            }, function () {
                $(this).css('background-image', 'none');
            });
            $('.tm_background,.tm_background_act').hover(function () {
                fnOverOut(this, 'block');
            }, function () {
                fnOverOut(this, 'none');
            });
            $('.tableSideBar').find('.tr_color_out').hover(function () {
                if ($(this).attr('sub') != 'true') {
                    $(this).attr('className', 'tr_color_over_' + Env.getDir());
                    $(this).find('img').attr('className', 'menu_bullet_over_' + Env.getDir());
                    $(this).find('a').attr('className', 'tr_color_over1_' + Env.getDir());
                }
            }, function () {
                $(this).attr('className', 'tr_color_out');
                $(this).find('img').attr('className', 'menu_bullet_' + Env.getDir());
                $(this).find('a').attr('className', 'side_text_out');
            });
            if (!Env.isCMS) {
                $('.dropCut').hover(function () {
                    $(this).css('display', 'block');
                }, function () {
                    $(this).css('display', 'none');
                });
            }
        } else if (Env.isSkin(3, 10)) {
            $('.parentTd').mouseover(function () {
                MenuManager.setLastTopMenu(this);
            });
            $('.tr_color_out_sub').hover(function () {
                this.className = 'tr_color_over_sub';
                MenuManager.setParentHover(this, true);
            }, function () {
                this.className = 'tr_color_out_sub';
                MenuManager.setParentHover(this, false);
            });
            $('.tm_background,.tm_background_act').hover(function () {
                fnOverOut(this, 'block');
            }, function () {
                fnOverOut(this, 'none');
            });
        } else if (Env.isSkin(8, 9)) {
            $('.TopMenuH').hover(function () {
                $(this).find('.dropCut').css('display', 'block');
                var $tab = $(this).find('.menuTab');
                if ($tab.length > 0) {
                    $($tab.find('td')[1]).attr('className', 'link_nav_hover');
                    $($tab.find('td')[0]).attr('className', 'tm_background_over_' + Env.getDir());
                }
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.dropCut').css('display', 'none');
                var $tab = $(this).find('.menuTab');
                if ($tab.length > 0) {
                    $($tab.find('td')[1]).attr('className', 'link_nav_link');
                    $($tab.find('td')[0]).attr('className', 'tm_background_' + Env.getDir());
                }
            });
        } else if (Env.isSkin(12)) {
            $('.TopMenuH').hover(function () {
                $(this).find('.dropCut').css('display', 'block');
                var $tab = $(this).find('.menuTab');
                if ($tab.length > 0) {
                    $($tab.find('td')[0]).attr('className', 'link_nav_hover');
                }
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.dropCut').css('display', 'none');
                var $tab = $(this).find('.menuTab');
                if ($tab.length > 0) {
                    $($tab.find('td')[0]).attr('className', 'link_nav_link');
                }
            });
            $('#tblMainSideBar').find('.tr_color_out').hover(function () {
                $(this).find('img').attr('className', 'menu_bullet_over_' + Env.getDir());
            }, function () {
                $(this).find('img').attr('className', 'menu_bullet_' + Env.getDir());
            });
        } else if (Env.isSkin(11, 13, 14)) {
            $('.TopMenuH').hover(function () {
                $(this).find('.dropCut').css('display', 'block');
                $(this).find('.tm_background').attr('className', 'tm_background_hover');
                $(this).find('.link_nav_link').attr('className', 'link_nav_hover');
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.dropCut').css('display', 'none');
                $(this).find('.tm_background_hover').attr('className', 'tm_background');
                $(this).find('.link_nav_hover').attr('className', 'link_nav_link');
                MenuManager.setLastTopMenu(this);
            });
            $('#tblMainSideBar').find('.tr_color_out').hover(function () {
                $(this).find('img').attr('className', 'menu_bullet_over_' + Env.getDir());
            }, function () {
                $(this).find('img').attr('className', 'menu_bullet_' + Env.getDir());
            });
        } else if (Env.isSkin(15)) {
            $('.TopMenuH').hover(function () {
                $(this).find('.dropCut').css('display', 'block');
                $(this).find('.tm_background').attr('className', 'tm_background_hover');
                $(this).find('.link_nav_link').attr('className', 'link_nav_hover');
                MenuManager.setLastTopMenu(this);
            }, function () {
                $(this).find('.dropCut').css('display', 'none');
                $(this).find('.tm_background_hover').attr('className', 'tm_background');
                $(this).find('.link_nav_hover').attr('className', 'link_nav_link');
                MenuManager.setLastTopMenu(this);
            });
            $('#tblMainSideBar').find('.tr_color_out').hover(function () {
                $(this).find('img[className*=menu_bullet]').attr('className', 'menu_bullet_over_' + Env.getDir());
            }, function () {
                $(this).find('img[className*=menu_bullet]').attr('className', 'menu_bullet_' + Env.getDir());
            });
        }
    },

    setParentHover: function (obj, show) {
        //show mouseover effect on parent menu buttom
        var skinID = Env.getSkin();
        if (Env.isSkin(2)) {
            if (Env.isCMS)
                $(obj).parents('.TopMenuH').find('span').attr('className', ((show) ? 'TopMenuSpan_over' : 'TopMenuSpan_out'));
            else {
                $(obj).parents('.TopMenuH').find('.link_nav')
					.css('background-image', ((show) ? 'url(/images/tm_background_hover.jpg)' : 'none'))
					.css('color', (show) ? $('.tr_color_out').css('color') : '');
            }
        } else if (Env.isSkin(3, 10)) {
            $(obj).parents('.parentTd').find('span').attr('className', ((show) ? 'TopMenuSpan_over' : 'TopMenuSpan_out'));
        }
    },

    bindEvents: function () {
        if (!Env.isCMS) {
            $('.btnSearch').click(function () {
                document.location.href = "Related.htm?keyword=" + $(this).parents('.tabSearchBox').find('.txtSearch').val();
            });
            $('.txtSearch').keypress(function (event) {
                if (MenuManager.pressedEnter(event))
                    document.location.href = "Related.htm?keyword=" + $(this).val();
            });
        }
    },

    pressedEnter: function (e) {
        var keynum = -1;
        if (window.event) {
            keynum = window.event.keyCode;
        } else if (e.which) {
            keynum = e.which;
        }
        return (keynum == 13);
    },

    fixCss: function () {
        //disable upper case for top submenu
        $('.tdTopSubmenuBox').find('.a_side_text_out').each(function () {
            $(this).css('text-transform', 'none');
        });
    },

    getWidth: function (type) {
        //get top menu width (by clientWidth or style width)
        var retValue = 0;
        try {
            $('.tm_background').each(function () {
                if (type == "client" || $(this).css('width') == "auto")
                    retValue += $(this).attr('clientWidth');
                else {
                    retValue += parseInt($(this).css('width'));
                }
            });
        }
        catch (e) { }

        return retValue;
    }

}

function fnSetTopMenu() {

    // debugger;

    try {
        var objMenu = new MenuItemArray();

        objMenu.setMenuWidth();
    }
    catch (e) {
        // debugger;
        // got en exception;
    }

    MenuManager.setMouseEffects();
    MenuManager.fixCss();
}

// ******************************** Env Class **********************************

var Env = {
    isCMS: document.location.href.toLowerCase().indexOf("cms") != -1,
    isWizard: document.location.href.toLowerCase().indexOf("wizard") != -1,
    charWidth: 5,
    isFF: navigator.appName == "Netscape",
    getSkin: function () {
        return (this.isCMS) ? Skin_Name.split("/")[0].replace(/skin/, "") : document.getElementById("skinID").value;
    },
    isSkin: function () {
        var i = 0, retValue = false;
        for (i = 0; i < arguments.length; i++) {
            if (arguments[i] == this.getSkin()) {
                retValue = true;
                break;
            }
        }
        return retValue;
    },
    getLayoutType: function () {
        var obj = document.getElementById("layout_type");
        return (obj == null ? "" : obj.value);
    },
    getRef: function () {
        var ref = document.referrer;
        if (ref.indexOf('?') != -1) ref = ref.substring(0, ref.indexOf('?'));
        return ref;
    },
    getServerURL: function () {
        return window.location.protocol + "//" + window.location.host + window.location.pathname;
    },
    getRelatedKeyword: function () {
        var retValue = "";
        try {
            var s = window.location.search;
            retValue = s.substring(s.indexOf("keyword") + 8).replace(/%20/g, ' ');
        }
        catch (e) { }
        return retValue;
    },
    getDir: function () {
        var $obj = $('.bodybg');
        if ($obj.length == 0)
            $obj = $('#mainTd');
        var dir = $obj.attr('dir');
        if (dir == '')
            dir = $obj.find('table').attr('dir');
        return dir;
    }
}

// ***************************** MenuItem Class ********************************

function MenuItem(obj) {
    this.source = obj;
    this.className = this.source.className;
    this.isActiveItem = this.fnIsActiveItem();
    this.isMenuItem = this.fnIsMenuItem();
    this.num = -1;
}
MenuItem.prototype.fnIsMenuItem = function () {
    var re;

    re = new RegExp("tt[0-9]+", "gm");
    return re.test(this.source.id);
}
MenuItem.prototype.addToArray = function (arr) {
    if (this.isMenuItem) {
        arr.push(this)
    }
}
MenuItem.prototype.fnIsActiveItem = function () {
    var s;

    s = (Env.isFF) ? this.source.parentNode.innerHTML : this.source.outerHTML;
    return s.indexOf("tm_background_act") != -1;
}
MenuItem.prototype.getMenuText = function () {
    // return this.source.innerText;
    // debugger;
    // return (Env.isFF) ? this.source.firstElementChild.text : this.source.innerText;
    return (this.source.innerText === undefined) ? $(this.source).text().trim() : this.source.innerText;
}
MenuItem.prototype.setWidth = function (arrayObj, spaceWidth) {
    var node, minReqLength, newWidth, shadeWidth, newShadeWidth, origWidth, kxChange;

    //1. set width to main object
    origWidth = parseInt(this.source.width);

    minReqLength = Env.charWidth * this.getMenuText().length;
    newWidth = minReqLength + spaceWidth;
    kxChange = newWidth / origWidth;

    this.source.style.width = newWidth;

    //2. set additional width to parent <td>
    node = this.source.parentNode.parentNode.parentNode.parentNode;
    node.style.width = newWidth;

    //3. set additional width to shade    
    if (!Env.isSkin(11, 12, 13, 14, 15)) {
        shade = this.getItemShade();
        if (shade !== undefined) {
            //shadeWidth = parseInt(this.getItemShade().width);
            shadeWidth = parseInt((this.getItemShade().style.width.indexOf("px") != -1) ? this.getItemShade().style.width.replace("px", "") : this.getItemShade().width);
            newShadeWidth = shadeWidth * kxChange;
            this.getItemShade().style.width = newShadeWidth;
        }
    }
    return newWidth;
}
MenuItem.prototype.getItemShade = function () {
    var pNode, shadeNode;

    pNode = this.source.parentNode.parentNode.parentNode.parentNode;
    shadeNode = pNode.childNodes[1];
    return shadeNode;
}

// ************************** MenuItemArray Class ******************************

function MenuItemArray() {
    this.tag = "td";
    this.array = null;
    this.bgArray = null;
    this.menuWidth = -1;
}
MenuItemArray.prototype.getArray = function () {
    var coll, i, item, arr;

    arr = new Array();
    if (this.array != null) {
        arr = this.array;
    }
    else {
        coll = document.getElementsByTagName(this.tag);
        for (i = 0; i < coll.length; i++) {
            item = new MenuItem(coll[i]);
            item.addToArray(arr);
        }
        this.array = arr;
    }
    return arr;
}
MenuItemArray.prototype.getTextLen = function () {
    var arrMenu, i, len;

    len = 0;
    arrMenu = this.getArray();
    for (i = 0; i < arrMenu.length; i++) {
        len += arrMenu[i].getMenuText().length * Env.charWidth;
    }
    return len;
}
MenuItemArray.prototype.getFreeSpaceShare = function () {
    return Math.floor((this.getMenuWidth() - this.getTextLen()) / this.getArray().length);
}
MenuItemArray.prototype.getMenuWidth = function () {
    var i, w, arr;

    w = 0;
    if (this.menuWidth != -1) {
        w = this.menuWidth;
    }
    else {
        arr = this.getArray();
        for (i = 0; i < arr.length; i++) {
            w += parseInt(arr[i].source.width);
        }
        this.menuWidth = w;
    }
    return w;
}
MenuItemArray.prototype.setMenuWidth = function () {
    var arr, spaceWidth, newMenuWidth, initWidth, resWidth, diff;
    initWidth = MenuManager.getWidth("client");
    newMenuWidth = 0;
    arr = this.getArray();
    spaceWidth = this.getFreeSpaceShare();

    for (i = 0; i < arr.length; i++) {
        arr[i].num = i;
        newMenuWidth += arr[i].setWidth(this, spaceWidth);
    }

    resWidth = MenuManager.getWidth("style");
    diff = resWidth - initWidth;
    this.setLastItemWidth(diff, arr);
}
MenuItemArray.prototype.setLastItemWidth = function (diff, arr) {
    var obj, i;
    i = arr.length - 1;
    obj = arr[i].source;
    obj.style.width = parseInt(obj.style.width) + diff;
}

// ************************************ PPC ************************************

var PPC_Client = {
    isPageRelated: (window.location.search.indexOf("click_data") != -1),   //related.htm ?
    relatedText: "Sponsored Results for ",                                 //header text in related.htm
    ref: Env.getRef(),
    serverURL: Env.getServerURL(),
    relatedKeyword: Env.getRelatedKeyword(),
    serverHandler: "PPCsite.aspx",

    loadPPC: function () {
        this.processPPC();
    },
    processPPC: function () {
        var callRelated = true;
        $('.ppc_item').each(function () {
            var $obj = $(this); //PPC container object
            if (PPC_Client.validObject($obj)) {
                $.get(PPC_Client.getParam($obj, 1), function (data) {
                    if (callRelated) {
                        callRelated = false;
                        PPC_Client.processRelated();
                    }
                    PPC_Client.processResponse($obj, data, false);
                });
            }
        });
    },
    processRelated: function () {
        var callRelated = true;
        $('.ppc_related').each(function () {
            var $obj = $(this); //PPC container object
            if (PPC_Client.validObject($obj)) {
                $.get(PPC_Client.getParam($obj, 2), function (data) {
                    PPC_Client.processResponse($obj, data, true);
                });
            }
        });
    },
    // check if item has id ?
    validObject: function ($obj) {
        return ($obj.text().indexOf("on_page_id=") != -1);
    },
    // create ajax request parameters line
    getParam: function ($obj, type) {
        var param = $obj.text() + "&item_type=" + type + "&referer=" + this.ref + "&serve_url=" + this.serverURL;
        if (this.isPageRelated) {
            param += window.location.search.replace("?", "&");
            $('.ppc_item_title').text(this.relatedText + "\"" + this.relatedKeyword + "\"");
        }
        return this.serverHandler + '?' + param;
    },
    //process ajax response 
    processResponse: function ($obj, data, isRelated) {
        if (this.itemHasContainer(data)) {
            var $response = this.getPPCcontainer(data);
            if (isRelated) {
                var dir = $response.attr('scrollDir');
                if (dir != "no") {
                    this.addScroll($response, dir);
                    this.loadContent($obj, $response.parent());
                } else {
                    this.loadContent($obj, $response);
                }
            } else {
                this.loadContent($obj, $response);
            }
            if (this.itemHasResults($response))   //has result
                this.displayPPCcontainer($obj);
        }
    },
    //loads ajax response to PPC container
    loadContent: function ($container, $response) {
        $container.html($.browser.msie ? $response.attr('outerHTML') : $response.html());
    },
    //if ajax response has <table> tag ?
    itemHasContainer: function (data) {
        return ($(data).find('table').length > 0);
    },
    //returns container <table> of the responsed content
    getPPCcontainer: function (data) {
        return $($(data).find('table')[0]);
    },
    //if response has any ads ?
    itemHasResults: function ($response) {
        return ($response.text().length > 10);
    },
    //show PPC item parent container
    displayPPCcontainer: function ($obj) {
        $obj.parents('.ppc_container').css('display', 'block');
    },
    //add scrolling to PPC related
    addScroll: function ($obj, dir) {
        //var dir = $obj.attr('scrollDir');
        var $marquee = $(document.createElement("marquee")).attr('truespeed', true).attr('behavior', 'scroll').
			attr('scrollamount', 1).attr('scrolldelay', 28).attr('loop', -1).css('direction', 'ltr').
			css('width', '100%').attr('direction', dir).attr('onmouseover', 'this.scrollAmount=0').
			attr('onmouseout', 'this.scrollAmount=1')
        if (dir == "up") $marquee.css('height', '300px');
        $obj.wrap($marquee);
    }
};

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

function ppclog(source, price, vendor, position, ens, tts) {
    document.forms.ppclgr.source.value = source;
    document.forms.ppclgr.price.value = price;
    document.forms.ppclgr.vendor.value = vendor;
    document.forms.ppclgr.position.value = position;
    document.forms.ppclgr.ens.value = ens;
    document.forms.ppclgr.tts.value = tts;

    setTimeout("document.forms.ppclgr.submit()", 10);
    return true;
}

// *********************************** FORMS ***********************************

var cObject = function () {
    var conn = false;
    if (window.XMLHttpRequest) {
        conn = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            conn = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                conn = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                conn = false;
            }
        }
    }
    return conn;
}

function createXMLHttpRequest() {
    var req = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            req = new XMLHttpRequest();
        } catch (e) {
            req = false;
        }
        // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                req = false;
            }
        }
    }


    return req
}

function fnOpenDisclaimer(formId, clientId) {
    $.post("http://" + window.location.host + "/ThankYouActions.aspx", { action: 4, formID: formId },
		function (data) {

		    if ($(data.lastChild).find("ErrorCode").length > 0) {
		        alert($(data.lastChild).find("ErrorText").text())
		        return;
		    }

		    //		    var res = $(data).find("disclatimertext").text();
		    //		    res = unescape(res.split(";")[0].split("=")[1]);

		    //		    while (res.indexOf("%3C") > -1 || res.indexOf("%3E") > -1 || res.indexOf("%20") > -1) {
		    //		        res = res.replace("%3C", "<").replace("%3E", ">").replace("%20", "&nbsp;");
		    //		    }


		    //		    res = res.replace(/%0D%0A/g, '<br>').replace(/%26nbsp%3B/g, '&nbsp;');
		    if ($("#div_terms_landing_" + formId).length < 1) {

		        $("<div style='display:none; direction: " + Env.getDir() + "' id='div_terms_landing_" + formId + "' class='relative_terms_landing'>" +
					"<div class='terms_landing_tools'>" +
						"<div class='bg_terms'>" +
							"<a class='close_terms' onclick=\"javascript:$('#div_terms_landing_" + formId + "').hide('slow');\">close</a>" +
							"<a class=print_terms onclick=\"javascript:fnPrintTerms('#div_terms_landing_" + formId + "')\">print</a> " +
						"</div>" +
					"</div>" +
					"<div class='terms_landing'>" +
					   "<div class='text_terms' style='padding: 7px;'>" + data + "</div>" +
					"</div>" +
				"</div>").appendTo($("body"));

		        $("#div_terms_landing_" + formId).show('slow');
		    }
		    else
		        $("#div_terms_landing_" + formId).show('slow');

		}, "text");
}

function fnPrintTerms(id) {
    $(id).find(".text_terms").printElement();
}

function FormatVal(val) {

    if (validDate(val)) {
        var ar = val.split("/")
        return ar[2] + ar[1] + ar[0];
    }
    else {
        return val;
    }

}

function fnSubmitForm(idForm, clientId, msg, msg2, btn) {

    var tJQ = $(btn).closest("table.form_container_cms");

    var bodyMail = "";
    var flag = false;


    //    tJQ.find("tr").each(function (index) {

    //        if ($(this).children("td").length == 3 && $(this).children("td:has('input')").length > 0) {
    //            bodyMail += $(this).children("td")[1].innerText + "  :  " +
    //    	$(this).children("td:has('input')").find("input").val() + "\t\n";
    //        }

    //    });

    //	paramsList = paramsList.replace("*SUBJECT*", subject);
    //	paramsList += "</FormData></xml>";

    //	$.post("http://" + window.location.host + "/ThankYouActions.aspx",
    //		{ action: 3, xmlCode: paramsList, FormID: idForm, ClientID: clientId, BodyMail: bodyMail },
    //		function (data) {
    //			if ($(data.lastChild).find("ErrorCode").length > 0) {
    //				alert($(data.lastChild).find("ErrorText").text())
    //				return;
    //			}
    //			document.location.href = "ThankYou.aspx?idForm=" + idForm + "&clientId=" + clientId;
    //		});



    //    var tJQ = $(btn).closest("table.form_container_cms");
    //    
    //    if (tJQ.find("input:checkbox").length > 0 && !tJQ.find("input:checkbox").attr("checked")) {
    //        alert(msg); return;
    //    }


    //    var bodyMail = "";
    //    var flag = false;

    //    var fieldsList = [];
    //    //---------------- build fild list ---
    //    tJQ.find(".form_display_input").each(function (index) {

    //        if ($(this).parent().parent().children(":first").hasClass("form_required_sign") && (typeof $(this).attr("value") === "undefined" || $(this).attr("value") === "")) flag = true

    //        fieldsList.push($(this).attr("fieldID"));
    //        fieldsList.push($(this).attr("value"));

    //    });
    //    //------------- find errors ---------------------------------
    //    if (tJQ.find(".form_input_error").length > 0 || flag) {
    //        alert(msg2);
    //        return;
    //    }
    //    //------------- build mail body -----------
    //    tJQ.find("tr").each(function (index) {

    //        if ($(this).children("td").length == 3 && $(this).children("td:has('input')").length > 0) {
    //            bodyMail += $(this).children("td")[1].innerText + "  :  " + $(this).children("td:has('input')").find("input").val() + "\t\n";
    //        }

    //    });

    //    $.post("http://" + window.location.host + "/ThankYouActions.aspx", { action: 3, fields: fieldsList, FormID: idForm, ClientID: clientId, BodyMail: bodyMail },
    //                    function (data) {    

    if (tJQ.find("input:checkbox").length > 0 && !tJQ.find("input:checkbox").attr("checked")) {
        alert(msg); return;
    }

    var fieldsList = [];
    //---------------- build fild list ---
    var sendToSrv = {};
    tJQ.find(".form_display_input").each(function (index) {
        var curFlag = false;
        var isReq = $(this).parent().parent().children(":first").hasClass("form_required_sign");
        curFlag = $(this).attr("value") == $(this).attr("oldval");

        if (isReq && (typeof $(this).attr("value") === "undefined" || $(this).val() === "" || curFlag)) {
            flag = true
        }

        var fieldObj = {};

        var val = "";
        if (!curFlag) {
            val = $(this).val();
        }
        else {
            if (!isReq) {
                $(this).val('');
            }
        }
        fieldObj[$(this).attr("fieldID")] = val;
        sendToSrv = $.extend(sendToSrv, fieldObj);

    });

    tJQ.find(":input:not([type=checkbox]):not([type=submit]):not([type=button])").each(function (index) {
        var titleItem = $(this).parent(":first").siblings(".tdtitleitem");
        var fieldName;
        if (titleItem.length) {
            fieldName = titleItem.text();
        }
        else {
            fieldName = $(this).attr("oldval");
        }
        var userInput = $(this).val();
        bodyMail += "<div style='font-weight: bolder; color: red; font-family: arial;'>" + fieldName + "&nbsp;:&nbsp;</div>" +
                            "<div style='font-family: arial;'>" + userInput + "&nbsp;</div><div></div>";

    });

    tJQ.find("tr:has(td:has(input))").each(function (x) { var z = $(this).children("td:has(input)").find("input"); z.focus(); z.blur(); });

    //------------- find errors ---------------------------------
    if (tJQ.find(".form_input_error").length > 0 || flag) {
        alert(msg2);
        return;
    }

    //    //------------- build mail body -----------
    //    tJQ.find("tr").each(function (index) {

    //        if ($(this).children("td").length == 3 && $(this).children("td:has('input')").length > 0) {
    //            bodyMail += $(this).children("td")[1].innerText + "  :  " + $(this).children("td:has('input')").find("input").val() + "\t\n";
    //        }

    //    });

    $.post("http://" + window.location.host + "/ThankYouActions.aspx", { action: 3, fields: JSON.stringify(sendToSrv), FormID: idForm, ClientID: clientId, BodyMail: bodyMail },
                    function (data) {
                        if (data.indexOf("Error") != -1) {
                            alert($(data).text());
                            return;
                        }
                        document.location.href = "ThankYou.aspx?idForm=" + idForm + "&clientId=" + clientId;
                    }, "text");
}

function fnBuildThankYouPage() {

    var resDiv = $("div[id*='Form_Thank_You']");
    if (resDiv.length == 0) return;
    var description = "", image = false, alt = "", type, style = "", trackingCode = "", isDefault = false;

    var FormID = window.location.search.slice(1).split("&")[0].split("=")[1];

    $(document).ajaxError(function (e, xhr, settings, exception) {
        alert('error in: ' + settings.url + ' \n' + 'error:\n' + xhr.responseText);
    });

    $.post("http://" + window.location.host + "/ThankYouActions.aspx", { action: 1, FormID: FormID },

		function (data) {

		    if (!data.noVal) {
		        var imgName = '/images/' + (data.imageName != "" ? data.imageName : "img_prev.jpg");
		        $("td[id*='hTitle']").children("h1").text(data.name);
		        $("td.link_navig1").text(data.name);

		        description = unescape(data.description);

		        if (data.imageName.length > 0) image = true;

		        alt = data.alt;

		        if (data.structure == "tp5") {
		            style = "style='float:left;margin:5px;'"
		        }
		        else if (data.structure == "tp6") {
		            style = "style='float:right;margin:5px;'"
		        }

		        trackingCode = unescape(data.trackingcode);

		        isDefault = data.isdefault == 'true';

		        var htmlCode = "";

		        var homePage = $("td:has(img[src*='HomePage']):last").html();

		        var emptyDiv = "<div style='width: 100%; height: 20px;'></div>";

		        var separator = '<tr><td colspan="2" class="dotted">' + emptyDiv + '<img height="1" src="/images/space.gif" complete="complete"></td></tr>' +
							'<tr><td colspan="2">' + emptyDiv + '</td></tr>'

		        if (description == "" || isDefault) {
		            description = $("#defaultThankYou").val();
		        }

		        if (style.length > 0 && !isDefault) {
		            htmlCode = "<div>" + ((image) ? "<img " + style + " src='" + imgName +
		                    "' alt='" + alt + "'/>" : "") +
							description + "</div>" + emptyDiv +
							" <table width='100%'>" + separator + "</table><div style='width: 100%; text-align: center;'>" + homePage +
							"</div><table width='100%'>" + separator + "</table>";
		        }
		        else {
		            if (data.structure == "tp7" && !isDefault) {
		                htmlCode = "<div><table style='width:100%'><tr><td style='width:40%' valign=top>" +
							((image) ? "<img " + style + " src='" + imgName +
							"' alt='" + alt + "'/>" : "") +
							"</td><td valign=top>" + description + "</td></tr>" +
							separator + "<tr><td colspan='2' align='center'>" + homePage + "</td></tr>" + separator + "</table></div>";
		            }
		            else if (data.structure == "tp8" && !isDefault) {
		                htmlCode = "<div><table style='width:100%'><tr><td style='width:40%' valign=top>" + description +
								"</td><td valign=top>" + ((image) ? "<img " + style + " src='" + imgName +
								"' alt='" + alt + "'/>" : "") + "</td></tr>" + separator + "<tr><td colspan='2' align='center'>" +
								homePage + "</td></tr>" + separator + "</table></div>";
		            }
		            else {
		                htmlCode = "<div style='font-size: 14px;'>" + description +
							   "</div>" + emptyDiv + "<table width='100%'>" + separator + "</table>" +
							   "<div style='width: 100%; text-align: center;'>" + homePage + "</div>" +
							   "<table width='100%'>" + separator + "</table>";
		            }
		        }

		        resDiv.html(htmlCode);

		        $(".MainPageColor").show();
		    }

		}, "json");
}

function onKeyUpFormElm(obj, submit) {
    if (submit) {
        $(obj).toggleClass('form_input_error', true);
        $(obj).toggleClass('form_input_default', false);
    }

    if (obj.value.length == 0)
        $(obj).val($(obj).attr("oldval"));
}

function onFocus(obj) {
    if (obj.getAttribute("oldval") == "") {
        $(obj).attr("oldval", $(obj).val());
    }

    if (obj.getAttribute("oldval") == obj.value) {
        $(obj).val("");
    }

    $(obj).select();
}

function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return (emailPattern.test(elementValue) || elementValue == "");
}

function validatePhoneNumber(elementValue) {
    //var emailPattern = /[^0-9]/
    //return !emailPattern.test(elementValue);
    var phonePattern = /^[\d{1}|\+|(\(\s*(\d+\s?)+\))][((\s\d)|(\-\d)|(\d))]+$/;
    return (phonePattern.test(elementValue) || elementValue == "");
}

function validateInteger(elementValue) {

    if (elementValue == "") {
        return true;
    }

    var iValue = parseInt(elementValue, 10);

    if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) {
        return false;
    }

    return true;
}

function validateOnString(elementValue) {
    //var emailPattern =  /[#`%*$]/
    //return !emailPattern.test(elementValue);
    return true;    //no validation for string   
}

function validEmptyString(obj) {
    var checkRes1 = validateOnString(obj.value);
    var checkRes2 = (($(obj).parent().parent().children(":first").hasClass("form_required_sign") && obj.value.length > 0 && $(obj).attr("value") != $(obj).attr("oldval")) || !$(obj).parent().parent().children(":first").hasClass("form_required_sign"))

    if (checkRes1 && checkRes2) {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);
    }
    else {
        $(obj).toggleClass('form_input_error', true);
        $(obj).toggleClass('form_input_default', false);
    }
}

function validPhoneNumber(obj) {
    var mainPart = $(obj).parent(":first").siblings(".tdtitleitem").length;
    if ($(obj).parent().prev().hasClass("form_required_sign") || (obj.value != $(obj).attr("oldval") && !mainPart) || (mainPart && obj.value.length > 0)) {
        if (!validatePhoneNumber(obj.value)) {
            $(obj).toggleClass('form_input_default', false);
            $(obj).toggleClass('form_input_error', true);
        }
        else {
            $(obj).toggleClass('form_input_error', false);
            $(obj).toggleClass('form_input_default', true);
        }
    }
    else {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);
    }
}

function validInteger(obj) {
    if (!validateInteger(obj.value)) {
        $(obj).toggleClass('form_input_default', false);
        $(obj).toggleClass('form_input_error', true);
    }
    else {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);
    }
}

function validEmail(obj) {
    var mainPart = $(obj).parent(":first").siblings(".tdtitleitem").length;
    if ($(obj).parent().prev().hasClass("form_required_sign") || (obj.value != $(obj).attr("oldval") && !mainPart) || (mainPart && obj.value.length > 0)) {
        if (!validateEmail(obj.value)) {
            $(obj).toggleClass('form_input_default', false);
            $(obj).toggleClass('form_input_error', true);
        }
        else {
            $(obj).toggleClass('form_input_error', false);
            $(obj).toggleClass('form_input_default', true);
        }
    }
    else {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);
    }
}

function validDate(val) {
    // regular expression to match required date format
    var re = /^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/;
    var retState = false;
    var day, month, year;

    if (val != null && val.length > 0) {
	regs = val.match(re);
        if (regs != null) {
	    month = parseInt(regs[2],10);
	    day = parseInt(regs[1],10);
            if (day > 0 && day < 32 && month > 0 && month < 13)
               retState = true;
	}
    }
    return retState;
}

function fnBlurDate(obj) {
    if (!validDate(obj.value)) {
        $(obj).toggleClass('form_input_default', true);
        $(obj).toggleClass('form_input_error', false);
        $(obj).val('');
    } else {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);

        var fy = (new Date()).getFullYear();
        var ar = obj.value.split("/");

        if (ar.length == 3 && ar[2].length == 2)
            ar[2] = (new String(fy)).slice(0, 2) + ar[2];
	    if (ar[0].length == 1) ar[0] = '0' + ar[0]; 
	    if (ar[1].length == 1) ar[1] = '0' + ar[1];

        obj.value = ar[0] + "/" + ar[1] + "/" + ar[2];
    }
}

function fnKeyUpDate(obj) {
return;
    if (!validDate(obj.value)) {
        $(obj).toggleClass('form_input_default', false);
        $(obj).toggleClass('form_input_error', true);
    } else {
        $(obj).toggleClass('form_input_error', false);
        $(obj).toggleClass('form_input_default', true);
    }
    var ar = obj.value.split("/")

    if ((ar.length == 1 && ar[0].length == 2) || (ar.length == 2 && ar[1].length == 2)) {
        obj.value = obj.value + "/";
    }
    else {
        if (ar.length == 3 && ar[2].length > 4) {
            while (ar[2].length > 4)
                ar[2] = ar[2].substr(0, ar[2].length - 1)

            obj.value = ar[0] + "/" + ar[1] + "/" + ar[2];

            if (validDate(obj.value)) {
                $(obj).toggleClass('form_input_error', false);
                $(obj).toggleClass('form_input_default', true);
            }
        }
    }
}

function fnKeyDownDate(obj) {
/*    if (event.keyCode == 8 || event.keyCode == 46) {
        var newStringVal = obj.value;
        if (newStringVal.charAt(newStringVal.length - 1) == "/") {
            newStringVal = newStringVal.substr(0, newStringVal.length - 1);
        }
        obj.value = newStringVal;
    }
    else {

        if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
            return false;

        if (obj.value.length == 10) {
            return false;
        }

        var ar = obj.value.split("/")

        if ((ar.length == 1 && ar[0].length == 2) || (ar.length == 2 && ar[1].length == 2)) {
            obj.value = obj.value + "/";
        }
        else {
            if (ar.length == 3 && ar[2].length > 4) {
                while (ar[2].length > 4)
                    ar[2] = ar[2].substr(0, ar[2].length - 1)

                obj.value = ar[0] + "/" + ar[1] + "/" + ar[2];
            }
        }
    }

    */
    return true;
}

function addWatermarkOnBlur() {
    $(".form_display_input").blur(function () {
        var obj = this;
        var $obj = $(obj);
        if (obj.value.length == 0) {
            var watermark = $obj.attr("oldval");
            $obj.val(watermark);
        }
    });

    $(".form_display_input").each(function () {
        var $this = $(this);
        var keyDownFunc = $this.attr("onkeydown");
        if (keyDownFunc) {
            if (keyDownFunc.toString().indexOf("fnKeyDownDate(this)")) {
                watermark = $this.attr('oldval') + " dd/mm/yyyy";
                $this.val(watermark);
                $this.attr('oldval', watermark);
            }
        }
    });
}

function fnOpenDisclaimerFB(id) { window.open('/ThankYouActions.aspx?action=4&formID=' + id); }

