/* 
 * flowplayer.js 3.2.0. The Flowplayer API
 * 
 * Copyright 2010 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * 
 * Flowplayer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Flowplayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Flowplayer.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Date: 2010-05-20 17:15:38 +0000 (Thu, 20 May 2010)
 * Revision: 480 
 */
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.slice(0,q)||"*";var o=s.slice(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).slice(2,10)}var h=function(t,r,s){var q=this,p={},u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.slice(0,v.length-1);var w="onBefore"+v.slice(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(y&&"onBeforeBegin,onMetaData,onStart,onUpdate,onResume".indexOf(v)!=-1){i(A,y);if(y.metaData){if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var o=this,s={},u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var z=q._api().fp_getPlugin(p);if(!z){return}i(o,z);delete o.methods;if(!u){m(z.methods,function(){var B=""+this;o[B]=function(){var C=[].slice.call(arguments);var D=q._api().fp_invoke(p,B,C);return D==="undefined"||D===undefined?o:D}});u=true}}var A=s[w];if(A){var y=A.apply(o,v);if(w.slice(0,1)=="_"){delete s[w]}return y}return o}})};function b(q,G,t){var w=this,v=null,D=false,u,s,F=[],y={},x={},E,r,p,C,o,A;i(w,{id:function(){return E},isLoaded:function(){return(v!==null&&v.fp_play!=undefined&&!D)},getParent:function(){return q},hide:function(H){if(H){q.style.height="0px"}if(w.isLoaded()){v.style.height="0px"}return w},show:function(){q.style.height=A+"px";if(w.isLoaded()){v.style.height=o+"px"}return w},isHidden:function(){return w.isLoaded()&&parseInt(v.style.height,10)===0},load:function(J){if(!w.isLoaded()&&w._fireEvent("onBeforeLoad")!==false){var H=function(){u=q.innerHTML;if(u&&!flashembed.isSupported(G.version)){q.innerHTML=""}flashembed(q,G,{config:t});if(J){J.cached=true;j(x,"onLoad",J)}};var I=0;m(a,function(){this.unload(function(K){if(++I==a.length){H()}})})}return w},unload:function(J){if(this.isFullscreen()&&/WebKit/i.test(navigator.userAgent)){if(J){J(false)}return w}if(u.replace(/\s/g,"")!==""){if(w._fireEvent("onBeforeUnload")===false){if(J){J(false)}return w}D=true;try{if(v){v.fp_close();w._fireEvent("onUnload")}}catch(H){}var I=function(){v=null;q.innerHTML=u;D=false;if(J){J(true)}};setTimeout(I,50)}else{if(J){J(false)}}return w},getClip:function(H){if(H===undefined){H=C}return F[H]},getCommonClip:function(){return s},getPlaylist:function(){return F},getPlugin:function(H){var J=y[H];if(!J&&w.isLoaded()){var I=w._api().fp_getPlugin(H);if(I){J=new l(H,I,w);y[H]=J}}return J},getScreen:function(){return w.getPlugin("screen")},getControls:function(){return w.getPlugin("controls")._fireEvent("onUpdate")},getLogo:function(){try{return w.getPlugin("logo")._fireEvent("onUpdate")}catch(H){}},getPlay:function(){return w.getPlugin("play")._fireEvent("onUpdate")},getConfig:function(H){return H?k(t):t},getFlashParams:function(){return G},loadPlugin:function(K,J,M,L){if(typeof M=="function"){L=M;M={}}var I=L?e():"_";w._api().fp_loadPlugin(K,J,M,I);var H={};H[I]=L;var N=new l(K,null,w,H);y[K]=N;return N},getState:function(){return w.isLoaded()?v.fp_getState():-1},play:function(I,H){var J=function(){if(I!==undefined){w._api().fp_play(I,H)}else{w._api().fp_play()}};if(w.isLoaded()){J()}else{if(D){setTimeout(function(){w.play(I,H)},50)}else{w.load(function(){J()})}}return w},getVersion:function(){var I="flowplayer.js 3.2.0";if(w.isLoaded()){var H=v.fp_getVersion();H.push(I);return H}return I},_api:function(){if(!w.isLoaded()){throw"Flowplayer "+w.id()+" not loaded when calling an API method"}return v},setClip:function(H){w.setPlaylist([H]);return w},getIndex:function(){return p}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error,MouseOver,MouseOut").split(","),function(){var H="on"+this;if(H.indexOf("*")!=-1){H=H.slice(0,H.length-1);var I="onBefore"+H.slice(2);w[I]=function(J){j(x,I,J);return w}}w[H]=function(J){j(x,H,J);return w}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip,playFeed,setKeyboardShortcutsEnabled,isKeyboardShortcutsEnabled").split(","),function(){var H=this;w[H]=function(J,I){if(!w.isLoaded()){return w}var K=null;if(J!==undefined&&I!==undefined){K=v["fp_"+H](J,I)}else{K=(J===undefined)?v["fp_"+H]():v["fp_"+H](J)}return K==="undefined"||K===undefined?w:K}});w._fireEvent=function(Q){if(typeof Q=="string"){Q=[Q]}var R=Q[0],O=Q[1],M=Q[2],L=Q[3],K=0;if(t.debug){g(Q)}if(!w.isLoaded()&&R=="onLoad"&&O=="player"){v=v||c(r);o=v.clientHeight;m(F,function(){this._fireEvent("onLoad")});m(y,function(S,T){T._fireEvent("onUpdate")});s._fireEvent("onLoad")}if(R=="onLoad"&&O!="player"){return}if(R=="onError"){if(typeof O=="string"||(typeof O=="number"&&typeof M=="number")){O=M;M=L}}if(R=="onContextMenu"){m(t.contextMenu[O],function(S,T){T.call(w)});return}if(R=="onPluginEvent"||R=="onBeforePluginEvent"){var H=O.name||O;var I=y[H];if(I){I._fireEvent("onUpdate",O);return I._fireEvent(M,Q.slice(3))}return}if(R=="onPlaylistReplace"){F=[];var N=0;m(O,function(){F.push(new h(this,N++,w))})}if(R=="onClipAdd"){if(O.isInStream){return}O=new h(O,M,w);F.splice(M,0,O);for(K=M+1;K<F.length;K++){F[K].index++}}var P=true;if(typeof O=="number"&&O<F.length){C=O;var J=F[O];if(J){P=J._fireEvent(R,M,L)}if(!J||P!==false){P=s._fireEvent(R,M,L,J)}}m(x[R],function(){P=this.call(w,O,M);if(this.cached){x[R].splice(K,1)}if(P===false){return false}K++});return P};function B(){if($f(q)){$f(q).getParent().innerHTML="";p=$f(q).getIndex();a[p]=w}else{a.push(w);p=a.length-1}A=parseInt(q.style.height,10)||q.clientHeight;E=q.id||"fp"+e();r=G.id||E+"_api";G.id=r;t.playerId=E;if(typeof t=="string"){t={clip:{url:t}}}if(typeof t.clip=="string"){t.clip={url:t.clip}}t.clip=t.clip||{};if(q.getAttribute("href",2)&&!t.clip.url){t.clip.url=q.getAttribute("href",2)}s=new h(t.clip,-1,w);t.playlist=t.playlist||[t.clip];var H=0;m(t.playlist,function(){var J=this;if(typeof J=="object"&&J.length){J={url:""+J}}m(t.clip,function(K,L){if(L!==undefined&&J[K]===undefined&&typeof L!="function"){J[K]=L}});t.playlist[H]=J;J=new h(J,H,w);F.push(J);H++});m(t,function(J,K){if(typeof K=="function"){if(s[J]){s[J](K)}else{j(x,J,K)}delete t[J]}});m(t.plugins,function(J,K){if(K){y[J]=new l(J,K,w)}});if(!t.plugins||t.plugins.controls===undefined){y.controls=new l("controls",null,w)}y.canvas=new l("canvas",null,w);function I(J){if(!w.isLoaded()&&w._fireEvent("onBeforeClick")!==false){w.load()}return f(J)}u=q.innerHTML;if(u.replace(/\s/g,"")!==""){if(q.addEventListener){q.addEventListener("click",I,false)}else{if(q.attachEvent){q.attachEvent("onclick",I)}}}else{if(q.addEventListener){q.addEventListener("click",f,false)}w.load()}}if(typeof q=="string"){var z=c(q);if(!z){throw"Flowplayer cannot access element: "+q}else{q=z;B()}}else{B()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var t=arguments[1],q=(arguments.length==3)?arguments[2]:{};if(typeof t=="string"){t={src:t}}t=i({bgcolor:"#000000",version:[9,0],expressInstall:"http://static.flowplayer.org/swf/expressinstall.swf",cachebusting:true},t);if(typeof o=="string"){if(o.indexOf(".")!=-1){var s=[];m(n(o),function(){s.push(new b(this,k(t),k(q)))});return new d(s)}else{var r=c(o);return new b(r!==null?r:o,t,q)}}else{if(o){return new b(o,t,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.fn.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var h=document.all,j="http://www.adobe.com/go/getflashplayer",c=typeof jQuery=="function",e=/(\d+)[^\d]+(\d+)[^\d]*(\d*)/,b={width:"100%",height:"100%",id:"_"+(""+Math.random()).slice(9),allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:[3,0],onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function i(l,f){if(f){for(key in f){if(f.hasOwnProperty(key)){l[key]=f[key]}}}return l}function a(f,n){var m=[];for(var l in f){if(f.hasOwnProperty(l)){m[l]=n(f[l])}}return m}window.flashembed=function(f,m,l){if(typeof f=="string"){f=document.getElementById(f.replace("#",""))}if(!f){return}if(typeof m=="string"){m={src:m}}return new d(f,i(i({},b),m),l)};var g=i(window.flashembed,{conf:b,getVersion:function(){var f;try{f=navigator.plugins["Shockwave Flash"].description.slice(16)}catch(n){try{var l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");f=l&&l.GetVariable("$version")}catch(m){}}f=e.exec(f);return f?[f[1],f[3]]:[0,0]},asString:function(l){if(l===null||l===undefined){return null}var f=typeof l;if(f=="object"&&l.push){f="array"}switch(f){case"string":l=l.replace(new RegExp('(["\\\\])',"g"),"\\$1");l=l.replace(/^\s?(\d+\.?\d+)%/,"$1pct");return'"'+l+'"';case"array":return"["+a(l,function(o){return g.asString(o)}).join(",")+"]";case"function":return'"function()"';case"object":var m=[];for(var n in l){if(l.hasOwnProperty(n)){m.push('"'+n+'":'+g.asString(l[n]))}}return"{"+m.join(",")+"}"}return String(l).replace(/\s/g," ").replace(/\'/g,'"')},getHTML:function(o,l){o=i({},o);var n='<object width="'+o.width+'" height="'+o.height+'" id="'+o.id+'" name="'+o.id+'"';if(o.cachebusting){o.src+=((o.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(o.w3c||!h){n+=' data="'+o.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(o.w3c||h){n+='<param name="movie" value="'+o.src+'" />'}o.width=o.height=o.id=o.w3c=o.src=null;o.onFail=o.version=o.expressInstall=null;for(var m in o){if(o[m]){n+='<param name="'+m+'" value="'+o[m]+'" />'}}var p="";if(l){for(var f in l){if(l[f]){var q=l[f];p+=f+"="+(/function|object/.test(typeof q)?g.asString(q):q)+"&"}}p=p.slice(0,-1);n+='<param name="flashvars" value=\''+p+"' />"}n+="</object>";return n},isSupported:function(f){return k[0]>f[0]||k[0]==f[0]&&k[1]>=f[1]}});var k=g.getVersion();function d(f,n,m){if(g.isSupported(n.version)){f.innerHTML=g.getHTML(n,m)}else{if(n.expressInstall&&g.isSupported([6,65])){f.innerHTML=g.getHTML(i(n,{src:n.expressInstall}),{MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title})}else{if(!f.innerHTML.replace(/\s/g,"")){f.innerHTML="<h2>Flash version "+n.version+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(f.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+j+"'>here</a></p>");if(f.tagName=="A"){f.onclick=function(){location.href=j}}}if(n.onFail){var l=n.onFail.call(this);if(typeof l=="string"){f.innerHTML=l}}}}if(h){window[n.id]=document.getElementById(n.id)}i(this,{getRoot:function(){return f},getOptions:function(){return n},getConf:function(){return m},getApi:function(){return f.firstChild}})}if(c){jQuery.tools=jQuery.tools||{version:"3.2.0"};jQuery.tools.flashembed={conf:b};jQuery.fn.flashembed=function(l,f){return this.each(function(){$(this).data("flashembed",flashembed(this,l,f))})}}})();
function is_msie()
{
    var m = navigator.userAgent.match(/MSIE (\d+(\.\d+)?)/);
    if (navigator.userAgent.indexOf('Opera') == -1 && m)
        return parseFloat(m[1]);
    else
        return 0;
}

function is_opera()
{
    var m = navigator.userAgent.match(/Opera.(\d+(\.\d+)?)/);
    return m ? parseFloat(m[1]) : 0;
}

function is_mozilla()
{
    var m = navigator.userAgent.match(/Gecko/),
        m1 = navigator.userAgent.match(/AppleWebKit/);
    return m && !m1 ? 1 : 0;
}

function is_webkit()
{
    var m = navigator.userAgent.match(/AppleWebKit/);
    return m ? 1 : 0;
}

function setCookie(name, value, expires, path, domain, secure)
{
    // set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires) {
	   expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + expires);

	if (!path) path = '/';
	document.cookie = name + "=" +escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") +
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

function getCookie(name)
{
    var srch = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(srch);
        if (offset != -1) {
            offset += srch.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, end));
        }
    }
}

function showCookieError()
{
    if (!navigator.cookieEnabled) {
        alert('This feature requires cookies to be enabled in your browser. Please enable cookies ' +
        'and try again.');
    }
}

var quirksMode = !document.compatMode || document.compatMode == 'BackCompat';

function getClientWidth()
{
    return !quirksMode ? document.documentElement.clientWidth : document.body.clientWidth;
}

function getClientHeight()
{
    return !quirksMode ? document.documentElement.clientHeight : document.body.clientHeight;
}

function getScrollLeft()
{
    return document.documentElement.scrollLeft || document.body.scrollLeft;
}

function getScrollTop()
{
    return document.documentElement.scrollTop || document.body.scrollTop;
}

function getScrollWidth()
{
    return !quirksMode ?
    	document.documentElement.scrollWidth :
    	document.body.scrollWidth;
}

function getScrollHeight()
{
    return !quirksMode ?
    	document.documentElement.scrollHeight :
    	document.body.scrollHeight;
}

function scrollTo(sl, st)
{
    if (!quirksMode && !is_webkit()) {
		document.documentElement.scrollLeft = sl;
		document.documentElement.scrollTop = st;
	} else {
		document.body.scrollLeft = sl;
		document.body.scrollTop = st;
	}
}

function getControlPixelPos(e, ofs_x, ofs_y, w, h, pad, fixedPos)
{
    var l = ofs_x ? ofs_x: 0;
    var t = ofs_y ? ofs_y: 0;
    var ctl = e;
    if (!pad) pad = 0;

    if (e.getBoundingClientRect) {
    	var br = e.getBoundingClientRect();
    	l += br.left;
    	t += br.top;
    	if (!fixedPos) {
	    	l += getScrollLeft();
	    	t += getScrollTop();
    	}
    } else {
	    while (e && e.tagName != 'BODY') {
	        var p = e.offsetParent;
	        l += e.offsetLeft;
	        t += e.offsetTop;
	        l -= p && p.tagName != 'BODY' ? p.scrollLeft : 0;
	        t -= p && p.tagName != 'BODY' ? p.scrollTop : 0;
	        e = p;
	    }
	    if (fixedPos) {
	    	l -= getScrollLeft();
	    	t -= getScrollTop();
	    }
    }
    if (w > 0 && h > 0) {
        var sl = fixedPos ? 0 : getScrollLeft();
        var st = fixedPos ? 0 : getScrollTop();
        if (l > getClientWidth()+sl-w-pad-1) {
            l += ctl.offsetWidth-w;
            if (l > getClientWidth()+sl-w-pad-1) {
                l = getClientWidth()+sl-w-pad-1;
            }
            if (l < sl+pad+1) {
            	l = sl+pad+1;
           	}
        }
        if (t > getClientHeight()+st-h-pad-1) {
            t = getClientHeight()+st-h-pad-1;
        }
        if (t < st+pad+1) {
        	t = st+pad+1;
       	}
    }
    return new Array(l, t);
}


function trim(str, chars)
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function __getComputedStyle(element, style)
{
	var computedStyle;
	if (typeof element.currentStyle != 'undefined') {
		computedStyle = element.currentStyle;
	} else {
		computedStyle = document.defaultView.getComputedStyle(element, null);
	}
	return computedStyle[style];
}

function valueFilter(e, forbidden)
{
    var skip = false,
        e = e || window.event,
        key = String.fromCharCode(e.which || e.keyCode);

    for (var i=0; i<forbidden.length; i++) {
        if(String(forbidden[i]) === key.toLowerCase()) {
            skip = true;
            break;
        }
    }
    if (skip) {
        if(e.preventDefault) e.preventDefault();
        e.returnValue = false;
    }
    return true;
}

function valueFilterAllowed(e, allowed)
{
    var skip = true,
        e = e || window.event,
        key = String.fromCharCode(e.which || e.keyCode);
    if ((e.which || e.keyCode) == 8 || (e.which || e.keyCode) == 9 ||
        ((e.which || e.keyCode) >= 35 && (e.which || e.keyCode) <= 40))
        return true;
    for (var i=0; i<allowed.length; i++) {
        if(String(allowed[i]) === key.toLowerCase()) {
            skip = false;
            break;
        }
    }

    if (skip) {
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
    }
    return true;
}

function disable(el, dis)
{
	el.disabled = dis ? true : false;
	el.style.backgroundColor = dis ? '#D4D0C8' : '';
}

hiddenElements = [];
function hideElementsByType(hideIn, showIn, tagname)
{
    var topObjPos = hideIn ? getObjPosition(hideIn) : null;
    var ctls = document.getElementsByTagName(tagname);
    for (var i = 0; i < ctls.length; i++) {
        var ctlPos = getObjPosition(ctls[i]);
        if (!topObjPos || (topObjPos.left <= ctlPos.right &&
            ctlPos.left <= topObjPos.right &&
            topObjPos.top <= ctlPos.bottom &&
            ctlPos.top <= topObjPos.bottom) &&
            ctls[i].style.visibility != 'hidden')
        {
            ctls[i].style.visibility = 'hidden';
            hiddenElements.push(ctls[i]);
        }
    }
    if (showIn) {
        var ctls = showIn.getElementsByTagName(tagname);
        for (i = 0; i < ctls.length; i++) {
            ctls[i].style.visibility = 'visible';
        }
    }
}

function hideElements(hideIn, showIn)
{
    if (is_msie() && is_msie() < 7) {
        hideElementsByType(hideIn, showIn, 'SELECT');
    }
    hideElementsByType(hideIn, showIn, 'OBJECT');
    hideElementsByType(hideIn, showIn, 'EMBED');
}

function showElements()
{
    if (typeof(fadeStack) != 'undefined' && fadeStack.isFadeDisplayed()) return;
    for (var i = 0; i < hiddenElements.length; i++) {
        hiddenElements[i].style.visibility = 'visible';
    }
    hiddenElements = [];
}

function getObjPosition(obj)
{
    var pos = getControlPixelPos(obj, 0, 0, 0, 0, 0);
    return { left: pos[0], top: pos[1],
        right: pos[0]+obj.offsetWidth, bottom: pos[1]+obj.offsetHeight,
        width: obj.offsetWidth, height: obj.offsetHeight };
}

function addWindowOnLoad(fnc)
{
    if (is_msie()) {
        window.attachEvent('onload', fnc);
    } else {
        window.addEventListener('load', fnc, false);
    }
}

function makeElementVisible(id, onAjaxEnd)
{
    var f = function()
    {
        var e = document.getElementById(id);
        if (!e) return;
        var pos = Math.round(getObjPosition(e).bottom);
        var diff = getClientHeight() + getScrollTop() - pos;
        if (diff < 0) {
            var scroll = -diff + getScrollTop() + 10;
            if (f.pause) {
                setTimeout(function(){ scrollTo(0, scroll); }, 500);
            } else {
                scrollTo(0, scroll);
            }
        }
    }
    if (onAjaxEnd) {
        addOnEndAjaxEvent(f);
    } else {
        if (is_webkit()) {
            f.pause = true;
        }
        addWindowOnLoad(f);
    }
}

// localStorage
function putToLocalStorage(key, oValue, domain)
{
	if (typeof(localStorage) != "undefined") {
		var lStorage = localStorage[domain?domain:location.hostname];
		lStorage.setItem(key, toJson(oValue));
	} else {
        throw 'LocalStorage is not supported';
    }
}

function getFromLocalStorage(key, domain)
{
	if (typeof(localStorage) != "undefined") {
	   var lStorage = localStorage[domain?domain:location.hostname];
	   return lStorage.getItem(key);
	} else {
    	throw 'LocalStorage is not supported';
    }
}
function isLocalStorageAvailable()
{
	return (typeof(localStorage) != "undefined");
}

function putToSessionStorage(key, oValue)
{
	if (typeof(sessionStorage) != "undefined") {
        var sStorage = sessionStorage;
        sStorage.setItem(key, toJson(oValue));
    } else {
        throw 'SessionStorage is not supported';
    }
}

function getFromSessionStorage(key, domain)
{
    if (typeof(sessionStorage) != "undefined"){
        var sStorage = sessionStorage;
       return sStorage.getItem(key);
    } else {
        throw 'SessionStorage is not supported';
    }
}
function isSessionStorageAvailable()
{
    return (typeof(sessionStorage) != "undefined" && sessionStorage != null);
}

function putToGlobalStorage(key, oValue, domain)
{
    if (typeof(globalStorage) != "undefined") {
        var gStorage = globalStorage[domain?domain:location.hostname];
        gStorage.setItem(key, toJson(oValue));
    } else {
        throw 'GlobalStorage is not supported';
    }
}

function getFromGlobalStorage(key, domain)
{
    if (typeof(globalStorage) != "undefined") {
       var gStorage = globalStorage[domain?domain:location.hostname];
       return gStorage.getItem(key);
    } else {
        throw 'GlobalStorage is not supported';
    }
}
function isGlobalStorageAvailable()
{
    return (typeof(globalStorage) != "undefined");
}

function putToUserDataStorage(key, oValue)
{
    if (document.getElementById('storageElement') != "undefined") {
         putToUserData(key, toJson(oValue));
    } else {
        throw 'userData is not supported';
    }
}

function getFromUserDataStorage(key)
{
    if (document.getElementById('storageElement') != "undefined") {
       return getFromUserData(key);
    } else {
        throw 'userData is not supported';
    }
}
function isUserDataStorageAvailable()
{
    return (is_msie() >= 5 && is_msie() < 8 && document.getElementById('storageElement') != "undefined");
}

function toJson(item)
{
	if (typeof (item.toJson) == 'function')
       return item.toJson();

	var out = '';
    if (typeof(item) == 'number') {
        out = item.toString();
    } else if (typeof(item) == 'boolean') {
        out = item ? 'true' : 'false';
    } else if (typeof(item) == 'object') {
        var first = true;
        if (item.length != 'undefined') {
            // numeric array
            out = '[';
            for (var k = 0; k < item.length; k++) {
                if (!first) out += ', ';
                first = false;
                out += toJson(item[k]);
            }
            out += ']';
        } else {
            // hash
            out = '{';
            for (k1 in item) {
                if (!first) out += ', ';
                first = false;
                out +=  '"' + toJson(k1) + '": ' + toJson(item[k1]);
            }
            out += '}';
        }
    } else {
        // assume a string
        out = quote(item);

    }
    return out;
}

var escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
    meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };


function quote(string) {
	// If the string contains no control characters, no quote characters, and no
	// backslash characters, then we can safely slap some quotes around it.
	// Otherwise we must also replace the offending characters with safe escape
	// sequences.
    escapeable.lastIndex = 0;
    return escapeable.test(string) ?
        '"' + string.replace(escapeable, function (a) {
            var c = meta[a];
            if (typeof c === 'string') {
                return c;
            }
            return '\\u' + ('0000' +
                    (+(a.charCodeAt(0))).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
}


// client side storage for ie 5-7
function initUserData()
{
	if (is_msie() >= 5 && is_msie() < 8) {
		storage = document.getElementById('userDataStorage');
		if (!storage.addBehavior) {
			throw new 'userData is not available';
		} else {
			storage.addBehavior("#default#userData");
			storage.load("userDataStorage");
		}
		return true;
	}
	return false;
}

function putToUserData(sKey, sValue) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.setAttribute(sKey, sValue);
    storage.save("userDataStorage");
}

function getFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return '';
    return storage.getAttribute(sKey);
}

function removeFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.removeAttribute(sKey);
    storage.save("userDataStorage");
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}

    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');

    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }

    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }

    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }

    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }

    return histogram;
}

function html_entity_decode( string, quote_style ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'

    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();

    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }

    return tmp_str;
}

function addHandler(object, event, handler)
{
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof object.attachEvent != 'undefined')
    object.attachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function removeHandler(object, event, handler)
{
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function getXmlHttpRequest()
{
	var req = null;
	if (window.XMLHttpRequest) {
	    req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	    try {
	        req = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	        try {
	            req = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch (e) {
	            req = null;
	        }
	    }
	}
    return req;
}

function sendRequest(url, useJsTag)
{
    if (!useJsTag) {
        var xmlHttp = getXmlHttpRequest();
        if (xmlHttp) {
    	    xmlHttp.open("GET", url, true);
    	    xmlHttp.send(null);
        }
    } else {
        var s = document.getElementById('__ajaxScriptTag__');
        if (s) s.parentNode.removeChild(s);
        s = document.createElement('script');
        s.id = '__ajaxScriptTag__';
        var head = document.getElementsByTagName('head')[0];
        if (head) head.appendChild(s);
        s.src = url;
    }
}

String.prototype.toBool = function() {
	return (/^true|1$/i).test(this);
}

// TODO: replace with Array.prototype.indexOf
function array_indexof(array, val)
{
    for (var i = 0, l = array.length; i < l; i++) {
        if (array[i] == val) {
            return i;
        }
    }
    return -1;
}

// TODO: replace with Array.prototype.unique
function array_unique(array)
{
    // original by: Carlos R. L. Rodrigues
    var p, i, j;
    for(i = array.length; i;){
        for(p = --i; p > 0;){
            if(array[i] === array[--p]){
                for(j = p; --p && array[i] === array[p];);
                i -= array.splice(p + 1, j - p).length;
            }
        }
    }
    return true;
}

/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
function RGBColor(color_string)
{
    this.ok = false;
    color_string = color_string.replace(/"/g,'');
    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // before getting into regexps, try simple matches
    // and overwrite the input
    var simple_colors = {
        aliceblue: 'f0f8ff',
        antiquewhite: 'faebd7',
        aqua: '00ffff',
        aquamarine: '7fffd4',
        azure: 'f0ffff',
        beige: 'f5f5dc',
        bisque: 'ffe4c4',
        black: '000000',
        blanchedalmond: 'ffebcd',
        blue: '0000ff',
        blueviolet: '8a2be2',
        brown: 'a52a2a',
        burlywood: 'deb887',
        cadetblue: '5f9ea0',
        chartreuse: '7fff00',
        chocolate: 'd2691e',
        coral: 'ff7f50',
        cornflowerblue: '6495ed',
        cornsilk: 'fff8dc',
        crimson: 'dc143c',
        cyan: '00ffff',
        darkblue: '00008b',
        darkcyan: '008b8b',
        darkgoldenrod: 'b8860b',
        darkgray: 'a9a9a9',
        darkgreen: '006400',
        darkkhaki: 'bdb76b',
        darkmagenta: '8b008b',
        darkolivegreen: '556b2f',
        darkorange: 'ff8c00',
        darkorchid: '9932cc',
        darkred: '8b0000',
        darksalmon: 'e9967a',
        darkseagreen: '8fbc8f',
        darkslateblue: '483d8b',
        darkslategray: '2f4f4f',
        darkturquoise: '00ced1',
        darkviolet: '9400d3',
        deeppink: 'ff1493',
        deepskyblue: '00bfff',
        dimgray: '696969',
        dodgerblue: '1e90ff',
        feldspar: 'd19275',
        firebrick: 'b22222',
        floralwhite: 'fffaf0',
        forestgreen: '228b22',
        fuchsia: 'ff00ff',
        gainsboro: 'dcdcdc',
        ghostwhite: 'f8f8ff',
        gold: 'ffd700',
        goldenrod: 'daa520',
        gray: '808080',
        green: '008000',
        greenyellow: 'adff2f',
        honeydew: 'f0fff0',
        hotpink: 'ff69b4',
        indianred : 'cd5c5c',
        indigo : '4b0082',
        ivory: 'fffff0',
        khaki: 'f0e68c',
        lavender: 'e6e6fa',
        lavenderblush: 'fff0f5',
        lawngreen: '7cfc00',
        lemonchiffon: 'fffacd',
        lightblue: 'add8e6',
        lightcoral: 'f08080',
        lightcyan: 'e0ffff',
        lightgoldenrodyellow: 'fafad2',
        lightgrey: 'd3d3d3',
        lightgreen: '90ee90',
        lightpink: 'ffb6c1',
        lightsalmon: 'ffa07a',
        lightseagreen: '20b2aa',
        lightskyblue: '87cefa',
        lightslateblue: '8470ff',
        lightslategray: '778899',
        lightsteelblue: 'b0c4de',
        lightyellow: 'ffffe0',
        lime: '00ff00',
        limegreen: '32cd32',
        linen: 'faf0e6',
        magenta: 'ff00ff',
        maroon: '800000',
        mediumaquamarine: '66cdaa',
        mediumblue: '0000cd',
        mediumorchid: 'ba55d3',
        mediumpurple: '9370d8',
        mediumseagreen: '3cb371',
        mediumslateblue: '7b68ee',
        mediumspringgreen: '00fa9a',
        mediumturquoise: '48d1cc',
        mediumvioletred: 'c71585',
        midnightblue: '191970',
        mintcream: 'f5fffa',
        mistyrose: 'ffe4e1',
        moccasin: 'ffe4b5',
        navajowhite: 'ffdead',
        navy: '000080',
        oldlace: 'fdf5e6',
        olive: '808000',
        olivedrab: '6b8e23',
        orange: 'ffa500',
        orangered: 'ff4500',
        orchid: 'da70d6',
        palegoldenrod: 'eee8aa',
        palegreen: '98fb98',
        paleturquoise: 'afeeee',
        palevioletred: 'd87093',
        papayawhip: 'ffefd5',
        peachpuff: 'ffdab9',
        peru: 'cd853f',
        pink: 'ffc0cb',
        plum: 'dda0dd',
        powderblue: 'b0e0e6',
        purple: '800080',
        red: 'ff0000',
        rosybrown: 'bc8f8f',
        royalblue: '4169e1',
        saddlebrown: '8b4513',
        salmon: 'fa8072',
        sandybrown: 'f4a460',
        seagreen: '2e8b57',
        seashell: 'fff5ee',
        sienna: 'a0522d',
        silver: 'c0c0c0',
        skyblue: '87ceeb',
        slateblue: '6a5acd',
        slategray: '708090',
        snow: 'fffafa',
        springgreen: '00ff7f',
        steelblue: '4682b4',
        tan: 'd2b48c',
        teal: '008080',
        thistle: 'd8bfd8',
        tomato: 'ff6347',
        turquoise: '40e0d0',
        violet: 'ee82ee',
        violetred: 'd02090',
        wheat: 'f5deb3',
        white: 'ffffff',
        whitesmoke: 'f5f5f5',
        yellow: 'ffff00',
        yellowgreen: '9acd32'
    };
    for (var key in simple_colors) {
        if (color_string == key) {
            color_string = simple_colors[key];
        }
    }
    // emd of simple type-in colors

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }
}

function min(a, b)
{
    return a<b? a: b;
}

function max(a, b)
{
    return a>b? a: b;
}

if (typeof mobileVersion == "undefined") mobileVersion = false;
var useAbsPosition = is_msie() && quirksMode || mobileVersion;

var asyncLoadDone = false, asyncHandlerAdded = false, asyncScripts = [];
function asyncLoad(file)
{
	if (!asyncHandlerAdded) {
		var f = function() {
			if (asyncLoadDone) return;
			asyncLoadDone = true;
			for (var i = 0; i < asyncScripts.length; i++) {
				var script = document.createElement('script');
				script.type = 'text/javascript';
				script.src = asyncScripts[i];
				document.body.appendChild(script);
			}
		}
		asyncHandlerAdded = true;
		if (document.addEventListener) {
			document.addEventListener("DOMContentLoaded", f, false);
			document.addEventListener("load", f, false);
		} else if (window.attachEvent) {
			window.attachEvent("onload", f);
		}
	}
	asyncScripts.push(file);
}
function getUrl()
{
	return window.location.toString()
	    .replace(/\/preview/, '')
	    .replace(/&+/g, '&')
	    .replace(/&$/, '')
	    .replace(/\?$/, '');
}

function add_to_favorites()
{
    if (typeof(window.external) != "undefined") {
        var url = window.location.href;
        var desc = document.title ? document.title : url;
        window.external.AddFavorite(url, desc);
    } else {
        alert("Sorry, your browser does not support this feature.");
    }
}

function addToFav(ctrl)
{
	var url = ctrl.getAttribute('data-url').replace('%current_url%', getUrl());
    var desc = ctrl.getAttribute('data-desc');
    add_to_fav(url, desc);
}

function add_to_fav(url, desc)
{
    if (typeof(window.external) != "undefined" &&
    	typeof(window.external.AddFavorite) != "undefined")
    {
        window.external.AddFavorite(url, desc);
    } else {
        alert("Sorry, your browser does not support this feature.");
    }
}

function sendToFriend(ctrl)
{
    var subj = ctrl.getAttribute('data-subj');
    var text = ctrl.getAttribute('data-text').replace(/%current_url%/ig, getUrl());
    send_to_friend('', subj, text);
}

function send_to_friend(url, subj, text)
{
	// url needed for backward compatibility
	var body = text.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
    location.href = 'mailto:?subject='+escape(subj)+'&body='+escape(body);
}

function openNamedWindow(url, name, attr)
{
    // IE fix: if 'base' tag is presented and relative url is not beginning with slash
    var base;
    if (is_msie() && !url.match(/^[a-z]+:/) && url.charAt(0) != '/'
    && (base = document.getElementsByTagName('base')[0])) {
        if (base.href.charAt(base.href.length-1) != '/') {
            url = '/' + url;
        }
        url = base.href + url;
    }
    if (attr) {
        window.open(url, name, attr);
    } else {
        window.open(url, name);
    }
}

function openWindow(url, attr)
{
	openNamedWindow(url, '', attr);
}

// backward compatibility
open_window = openWindow;

function nav_dropdown_change(ctl)
{
    var url = ctl.options[ctl.selectedIndex].value.replace(/ /g, '');
    if (url) {
        if (m = url.match(/^popup\((\d+),(\d+),(.*)\)$/))
            openWindow(m[3], 'scrollbars=yes,resizable=yes,width='+m[1]+',height='+m[2]);
        else if (m = url.match(/^new\((.*)\)$/))
            openWindow(m[1], '');
        else  {
            setLocation(url);
        }
    }
}

hiddedByAjaxRefresh = new Array();
function AjaxFrameRefresh(frameIds, args, shownd, fade, controls)
{
    if (!frameIds) return false;
    if (typeof frameIds != 'object') frameIds = [frameIds];
    var url = window.location.href;
    if (controls) {
        if (typeof controls != 'object') controls = [ controls ];
    } else {
        controls = [];
    }
    controls = controls.join('/');
    var i = url.indexOf('#');
    if (i != -1) {
        // deleting anchor from url
       url = url.substring(0, i);
    }
    url += -1 == url.indexOf('?') ? '?' : '&';
    var fl = false;
    for(var i = 0; i < frameIds.length; i++) {
        var frameId = frameIds[i];
        var form = getFormByFrame(frameId);
        if (!form) continue;
        url += 'ajaxdst[' + i + ']=' + getPluginByForm(form) + ':' + getInterfaceByForm(form) + ':' +
            frameId + ':' + controls + '&';
        for (var j = 0; j < form.elements.length; j++) {
            if (!form.elements[j].disabled) {
                form.elements[j].disabled = true;
                hiddedByAjaxRefresh.push(form.elements[j]);
            }
        }
        fl = true;
    }
    if (!fl) return false;
    if (args) url += args;
    if (shownd) {
        var txt = typeof(shownd) == 'string' ? shownd : false;
        showWaitWnd(txt, fade);
    }
    AjaxRequest(url);
}

function ajaxPostSubmit(form, action, wait, text, no_fade)
{
    if (ajaxPostFrameId)
        form.target = ajaxPostFrameId;
    if (wait) {
        showWaitWnd(text, !no_fade);
    }
    if (action) {
        form.submitAction.value = action;
    }
    form.submit();
    if (wait) {
        for (var i = 0; i < form.elements.length; i++) {
            form.elements[i].disabled = true;
        }
    }
}

function endAjaxPostSubmit(form, wait)
{
    if (wait) {
        hideWaitWnd();
        for (var i = 0; i < form.elements.length; i++) {
            form.elements[i].disabled = false;
        }
    }
    form.submitAction.value = '';
    form.target = '_self';
}

var waitHidden = new Array(), waitFade = false;

function showWaitWnd(text, fade)
{
    var w = document.getElementById('waitWindow');
    if (w) {
        if (w.style.visibility == 'visible') return;
        if (fade) {
        	if (typeof fadeStack != 'undefined') fadeStack.show();
            waitFade = true;
            hideElements();
        } else {
        	hideElements(w);
        }
        var wtext = document.getElementById('waitWindowText');
        var messageStr = text ? document.createTextNode(text) : document.createTextNode('Please wait...');
        wtext.innerHTML = '';
        wtext.appendChild(messageStr);
        if (useAbsPosition) {
        	w.style.top = getClientHeight() / 2 - w.offsetHeight / 2 + getScrollTop() + 'px';
        	w.style.left = getClientWidth() / 2 - w.offsetWidth / 2 + getScrollLeft() + 'px';
        	w.style.position = 'absolute';
        } else {
        	w.style.top = getClientHeight() / 2 - w.offsetHeight / 2 + 'px';
        	w.style.left = getClientWidth() / 2 - w.offsetWidth / 2 + 'px';
        	w.style.position = 'fixed';
        }
        if (is_msie() && is_msie() < 7.0) {
            // Go home, IE6!
            waitHidden = new Array();
            var cl = w.style.pixelLeft, cr = cl+w.style.pixelWidth,
                ct = w.style.pixelTop,  cb = ct+w.style.pixelHeight;
            var c = document.getElementsByTagName('SELECT');
            for (var i = 0; i < c.length; i++) {
                var cl1 = 0, ct1 = 0, e = c[i];
                while (e) {
                    cl1 += e.offsetLeft;
                    ct1 += e.offsetTop;
                    e = e.offsetParent;
                }
                var cr1 = cl1+c[i].offsetWidth, cb1 = ct1+c[i].offsetHeight;
                if (c[i] && c[i].style.visibility != 'hidden'
                && !(cl1 > cr || cr1 < cl || ct1 > cb || cb1 < ct)) {
                    c[i].style.visibility = 'hidden';
                    waitHidden.push(c[i]);
                }
            }
        }
        w.style.visibility = 'visible';
    }
}

function hideWaitWnd()
{
    var w = document.getElementById('waitWindow');
    if (w) {
    	if (w.style.visibility == 'hidden') return;
        w.style.visibility = 'hidden';
        w.style.left = '0px';
        w.style.top = '0px';
        if (waitFade) {
            if (typeof fadeStack != 'undefined') fadeStack.hide();
            waitFade = false;
        }
        for (var i = 0; i < waitHidden.length; i++) {
            if (waitHidden[i]) {
                waitHidden[i].style.visibility = 'visible';
            }
        }
        showElements();
    }
}

function is_valid_email(ctl)
{
    if (window.RegExp) {
        var reg = new RegExp("^([_\.a-zA-Z0-9\-]+@[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)+)?$", "g");
        if (!reg.test(ctl.value)) {
            fviewSetError(ctl.form, ctl.name, "Incorrect email format");
            return false;
        }
    }
    return true;
}

function form_check_confirmation(f)
{
    var vNeedConfirm = getControlsByForm(f, 'form_need_confirmation');
    if (vNeedConfirm && vNeedConfirm.length > 0 && vNeedConfirm[0].value == 1) {
        return confirm('Please review the information you entered.\nSelect OK if the information' +
                       ' is accurate, select Cancel to make corrections before submitting.');
    }
    return true;
}

function form_show_wait_msg(f)
{
    var inputs = f.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'file') {
            showWaitWnd('Uploading files, please wait...', true);
            break;
        }
    }
}

var popupUploadCallback = false;
function popupUploadFilesShow(id, ctl, params, callback)
{
    var url = 'core/file_store/file_upload.php?iID=' + id + '&ctl=' + ctl;
    for (var k in params) {
        url += '&params[' + k + ']=' + escape(params[k]);
    }
    if (callback) {
        url += '&callback=1';
        popupUploadCallback = callback;
    }
    if (params['enable_java'] == 1 && params['default_uploader'] == 'java' &&
        getCookie('use_java_uploader') == '' )
    {
    	url += '&use_java=1';
    }

    if (getCookie('use_java_uploader') == '1') {
        url += '&use_java=1';
    }
    popup_exec_url(url, null, 400, 500, true, null, '', null);
}

function popupUploadDone(id, ctl, num, keepPopup)
{
    if (popupUploadCallback) {
        if (!keepPopup) _call('hide_popup');
        var f = popupUploadCallback;
        popupUploadCallback = false;
        f(id, ctl, num);
    }
}

function popupPluploader(frameId, modNum, optionId, orderNum, itemNum, optionNum)
{
    var url = 'core/file_store/plupload/?modNum=' + modNum + '&numbers=' +
        orderNum + ':' + itemNum + ':' + optionNum + '&optId=' + optionId;
    popupUploadCallback = function() {
        AjaxFrameRefresh(frameId, null, true);
    }
    _call('popup_exec_url', [url, null, 800, 330, true, null, '']);
}

function prnt()
{
    if (window.print) {
        window.print();
    } else {
        alert('Sorry, your browser doesn\'t support this feature.');
    }
}

function _dump(d, l)
{
    if (l == null) l = 1;
    var s = "";
    if ("object" == typeof(d)) {
        s += typeof(d) + " {\n";
        for (var k in d) {
            for (var i = 0; i < l; i++) s += "  ";
            s += k + ": " + _dump(d[k], l + 1);
        }
        for (var i = 0; i < l - 1; i++) s += "  ";
        s += "}\n"
    } else {
        s += d + "\n";
    }
    return s;
}

function fviewSetError(form, item_name, text)
{
    var frameId = form.getAttribute('attr_frame_id');
    if (!frameId) frameId = 0;
    var e = document.getElementById('fview_err_' + frameId + '_' + item_name);
    if (e) e.innerHTML = text ?
        '<img src="/core/form_view/images/error_arrow.gif" width="12" height="7" align="baseline"/>&#xA0;'
        + text : '';
    e.parentNode.style.display = text ? '' : 'none';
}

function setLocation(url, setPrevUrl)
{
    if (setPrevUrl) {
        var p = location.pathname.replace(/^.*\//, '');
        if (!p) p = './';
        if (url != p) {
            if (url.indexOf('?') == -1) url += '?'; else url += '&';
            url += 'prev_url=' + escape(p);
        }
    }
    var isRelative = !url.match(/^[a-z]+:/);
    if (isRelative || url.indexOf(location.hostname) != -1) {
        preventExitPopup = true;
    }
    // IE fix: if 'base' tag is presented and relative url is not beginning with slash
    var base;
    if (is_msie() && isRelative && url.charAt(0) != '/' && (base = document.getElementsByTagName('base')[0])) {
        if (base.href.charAt(base.href.length-1) != '/') {
            url = '/' + url;
        }
        url = base.href + url;
    }
    location.href = url;
}

function goTo(url)
{
    setLocation(url, true);
}

var preventExitPopup = false;
function setExitPopup(url, flags)
{
    var f = function() {
        var elements = document.getElementsByTagName('a');
        for (var i = 0; i < elements.length; i++) {
            var href = elements[i].getAttribute('href');
            if (!href.match(/^[a-z]+:/) || href.indexOf(location.hostname) != -1) {
                addHandler(elements[i], 'click', function() {preventExitPopup = true;});
            }
        }
        var elements = document.getElementsByTagName('form');
        for (var i = 0; i < elements.length; i++) {
            addHandler(elements[i], 'submit', function() {preventExitPopup = true;});
            elements[i].__realSubmit = elements[i].submit;
            elements[i].submit = function() {preventExitPopup = true;return this.__realSubmit();}
        }
    };
    addWindowOnLoad(f);
    addHandler(window, 'unload', function() {
        if (!preventExitPopup) {
        	openNamedWindow(url, 'exitPopup', flags);
        }
    });
}

var UserTracker = {
    refreshSession: false,
    trackVisitor: false,
    enabled: false,
    url: '',
    siteId: 0,
    interval: 0,
    track: function() {
        if (this.trackVisitor || this.refreshSession) {
            var url = this.url + '?rand=' + Math.random();
            if (this.refreshSession) {
                url += '&refreshSession=1';
            }
            if (this.trackVisitor) {
                url += '&siteId=' + this.siteId + '&url=' + escape(location.href) +
                    '&title=' + encodeURIComponent(top.document.title) + '&memberIds=' + UserTracker.memberIds;
            }
            sendRequest(url, true);
            this.refreshSession = false;
            this.trackVisitor = false;
        }
    },
    start: function() {
        if (this.enabled && this.interval && this.siteId) {
            setInterval(function() { UserTracker.trackVisitor = true }, this.interval*1000);
            this.trackVisitor = true;
        }
        setInterval(function() { UserTracker.refreshSession = true }, 600000);
        setInterval(function() { UserTracker.track() }, 5000);
        UserTracker.track();
    }
};
addWindowOnLoad(function() {UserTracker.start()});

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
    if (!document.getElementById) {return;}
    this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
    this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
    this.params = new Object();
    this.variables = new Object();
    this.attributes = new Array();
    if(swf) {this.setAttribute('swf', swf);}
    if(id) {this.setAttribute('id', id);}
    if(w) {this.setAttribute('width', w);}
    if(h) {this.setAttribute('height', h);}
    if(ver) {this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split(".")));}
    this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
    if (!window.opera && document.all && this.installedVer.major > 7) {
        // only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
        deconcept.SWFObject.doPrepUnload = true;
    }
    if(c) {this.addParam('bgcolor', c);}
    var q = quality ? quality : 'high';
    this.addParam('quality', q);
    this.setAttribute('useExpressInstall', false);
    this.setAttribute('doExpressInstall', false);
    var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
    this.setAttribute('xiRedirectUrl', xir);
    this.setAttribute('redirectUrl', '');
    if(redirectUrl) {this.setAttribute('redirectUrl', redirectUrl);}
}
deconcept.SWFObject.prototype = {
    useExpressInstall: function(path) {
        this.xiSWFPath = !path ? "expressinstall.swf" : path;
        this.setAttribute('useExpressInstall', true);
    },
    setAttribute: function(name, value){
        this.attributes[name] = value;
    },
    getAttribute: function(name){
        return this.attributes[name];
    },
    addParam: function(name, value){
        this.params[name] = value;
    },
    getParams: function(){
        return this.params;
    },
    addVariable: function(name, value){
        this.variables[name] = value;
    },
    getVariable: function(name){
        return this.variables[name];
    },
    getVariables: function(){
        return this.variables;
    },
    getVariablePairs: function(){
        var variablePairs = new Array();
        var key;
        var variables = this.getVariables();
        for(key in variables){
            variablePairs[variablePairs.length] = key +"="+ variables[key];
        }
        return variablePairs;
    },
    getSWFHTML: function() {
        var swfNode = "";
        if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "PlugIn");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
            swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
            var params = this.getParams();
             for(var key in params){swfNode += [key] +'="'+ params[key] +'" ';}
            var pairs = this.getVariablePairs().join("&");
             if (pairs.length > 0){swfNode += 'flashvars="'+ pairs +'"';}
            swfNode += '/>';
        } else { // PC IE
            if (this.getAttribute("doExpressInstall")) {
                this.addVariable("MMplayerType", "ActiveX");
                this.setAttribute('swf', this.xiSWFPath);
            }
            swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
            swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
            var params = this.getParams();
            for(var key in params) {
             swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
            }
            var pairs = this.getVariablePairs().join("&");
            if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
            swfNode += "</object>";
        }
        return swfNode;
    },
    write: function(elementId){
        if(this.getAttribute('useExpressInstall')) {
            // check to see if we need to do an express install
            var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
            if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
                this.setAttribute('doExpressInstall', true);
                this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
                document.title = document.title.slice(0, 47) + " - Flash Player Installation";
                this.addVariable("MMdoctitle", document.title);
            }
        }
        if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
            var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
            n.innerHTML = this.getSWFHTML();
            return true;
        }else{
            if(this.getAttribute('redirectUrl') != "") {
                document.location.replace(this.getAttribute('redirectUrl'));
            }
        }
        return false;
    }
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
    var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
    if(navigator.plugins && navigator.mimeTypes.length){
        var x = navigator.plugins["Shockwave Flash"];
        if(x && x.description) {
            PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
        }
    }else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
        var axo = 1;
        var counter = 3;
        while(axo) {
            try {
                counter++;
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
                PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
            } catch (e) {
                axo = null;
            }
        }
    } else { // Win IE (non mobile)
        // do minor version lookup in IE, but avoid fp6 crashing issues
        // see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
        try{
            var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        }catch(e){
            try {
                var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
                axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
            } catch(e) {
                if (PlayerVersion.major == 6) {
                    return PlayerVersion;
                }
            }
            try {
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            } catch(e) {}
        }
        if (axo != null) {
            PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
        }
    }
    return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
    this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
    this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
    this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
    if(this.major < fv.major) return false;
    if(this.major > fv.major) return true;
    if(this.minor < fv.minor) return false;
    if(this.minor > fv.minor) return true;
    if(this.rev < fv.rev) return false;
    return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
    getRequestParameter: function(param) {
        var q = document.location.search || document.location.hash;
        if (param == null) {return q;}
        if(q) {
            var pairs = q.substring(1).split("&");
            for (var i=0; i < pairs.length; i++) {
                if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
                    return pairs[i].substring((pairs[i].indexOf("=")+1));
                }
            }
        }
        return "";
    }
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
    var objects = document.getElementsByTagName("OBJECT");
    for (var i = objects.length - 1; i >= 0; i--) {
        objects[i].style.display = 'none';
        for (var x in objects[i]) {
            if (typeof objects[i][x] == 'function') {
                objects[i][x] = function(){};
            }
        }
    }
}
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (deconcept.SWFObject.doPrepUnload) {
    if (!deconcept.unloadSet) {
        deconcept.SWFObjectUtil.prepUnload = function() {
            __flash_unloadHandler = function(){};
            __flash_savedUnloadHandler = function(){};
            window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
        }
        window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
        deconcept.unloadSet = true;
    }
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) {document.getElementById = function(id) {return document.all[id];}}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;
jmenuMovedLayers = 0;
jmenuMenuXLeftShift = 6;
jmenuMenuXRightShift = 10;
jmenuHiddenControls = new Array();
jmenuLWidth = new Array();
jmenuLWidthDetected = 0;

var jmenu_openedChildren = new Array();

var currentMenuName = '';

function activateMenu(menuName)
{
    if (menuName != currentMenuName) {
        jmenuShutdown();
        currentMenuName = menuName;
        jmenu = window['jmenu_'+menuName];
        jmenuMovedLayers = 0;
        jmenuMenuXLeftShift = 6;
        jmenuMenuXRightShift = 10;
        jmenuHiddenControls = new Array();
        jmenuLWidth = new Array();
        jmenuLWidthDetected = 0;
    }
}

function jmenuShutdown()
{
    if (typeof jmenu == "undefined") return;
    for (i=1; i<=jmenu.numl; i++) {
        var listl = eval("jmenu.listl.l"+i);
        jmenuPopUpL(listl, false);
    }
    jmenuShowControls(true);
}

function jmenuMoveLayers()
{
    if (!jmenuLWidthDetected) {
        for (i = 1; i <= jmenu.numl; i++) {
            var listl = jmenu.listl["l" + i];
            var l = document.getElementById(listl);
            jmenuLWidth[listl] = l ? l.offsetWidth : 0;
        }
        jmenuLWidthDetected = 1;
    }
}

function jmenuHideControls2(tagname)
{
    if (is_msie() == 0 || is_msie() >= 7) return;

    var ctls = document.getElementsByTagName(tagname);
    if (!ctls)
        return;

    for (var i=0; i<ctls.length; i++) {
        ctls[i].style.visibility = 'hidden';
        jmenuHiddenControls[jmenuHiddenControls.length] = ctls[i];
    }
}

function jmenuHideControls(topObj, tagname)
{
    if (is_msie() == 0 || is_msie() >= 7) return;

    if (topObj) {
        var menuPos = jmenuGetObjPosition(topObj);
        var ctls = document.getElementsByTagName(tagname);
        for (var i=0; i<ctls.length; i++) {
            var ctlPos = jmenuGetObjPosition(ctls[i]);
            if (!(ctlPos.right < menuPos.left || ctlPos.left > menuPos.right
            || ctlPos.bottom < menuPos.top || ctlPos.top > menuPos.bottom)) {
                ctls[i].style.visibility = 'hidden';
                jmenuHiddenControls[jmenuHiddenControls.length] = ctls[i];
            }
        }
    }
}

function jmenuShowControls(v)
{
    if (is_msie() == 0 || is_msie() >= 7) return;

    if (v) {
        for (var i=0; i<jmenuHiddenControls.length; i++)
            jmenuHiddenControls[i].style.visibility = 'visible';
        jmenuHiddenControls = new Array();
    } else {
        jmenuHiddenControls = new Array();
        jmenuHideControls2('SELECT');
    }
}

function jmenuResizeHandler()
{
    if (typeof jmenu == "undefined") return;
    jmenuShutdown();
    for (i=1; i<=jmenu.numl; i++) {
        var listl = eval("jmenu.listl.l"+i);
        jmenuSetLeft(listl, 0);
        jmenuSetTop(listl, 0);
    }
    jmenuMovedLayers = 0;
}
window.onresize = jmenuResizeHandler;

function getPixelPos(e)
{
    var l = 0;
    var t = 0;
    while (e) {
        l += e.offsetLeft;
        t += e.offsetTop;
        if (__getComputedStyle(e, 'position') != 'static' && __getComputedStyle(e, 'position') != '')
            break;
        e = e.offsetParent;
    }

    return new Array(l, t);
}

function jmenuMoveLayer(menuName, abscissa_margin, ordinate_margin, orientation)
{
    if (jmenu.jmenuLoaded) {
        if (!jmenuMovedLayers) {
            jmenuMoveLayers();
            jmenuMovedLayers = 1;
        }

        var layer = document.getElementById(menuName + jmenu.menuName);
        if (!layer) return;
        var layerwidth = layer.offsetWidth;
        var layerheight = layer.offsetHeight;
        var ref = document.getElementById("ref" + menuName + jmenu.menuName);
        if (ref && ref.firstChild && ref.firstChild.tagName && ref.firstChild.tagName.toLowerCase() == 'img') {
            ref = ref.firstChild;
        }
        var pos = ref ? getPixelPos(ref) : [0, 0];
        var newX = pos[0], newY = pos[1];
        if (orientation == "vert") {
            newX += ref.offsetWidth;
        } else if (orientation == "vert_right") {
            newX -= layerwidth;
        } else if (orientation == "horz_bottom") {
            newY -= layerheight;
        } else {
            newY += ref.offsetHeight;
        }
        newX -= abscissa_margin;
        newY -= ordinate_margin;
        windowwidth = getClientWidth();
        windowxoffset = getScrollLeft();
        if (newX + layerwidth > windowwidth + windowxoffset) {
            if (layerwidth > windowwidth) {
                newX = windowxoffset;
                // for mobile version set horizontal scrolling
                /*if (jmenu.mobile) {
                    layer.style.width = (windowwidth - 20) + 'px';
                    layer.style.overflow = 'auto';
                }*/
            } else {
                newX = windowwidth + windowxoffset - layerwidth;
            }
        }
        windowheight = getClientHeight();
        windowyoffset = getScrollTop();
        if (newY + layerheight > windowheight + windowyoffset) {
            if (layerheight > windowheight) {
                newY = windowyoffset;
                // for mobile version set vertical scrolling
                /*if (jmenu.mobile) {
                    layer.style.height = (windowheight - 20) + 'px';
                    layer.style.overflow = 'auto';
                }*/
            } else {
                newY = windowheight + windowyoffset - layerheight;
            }
        }
        jmenuSetLeft(menuName + jmenu.menuName, newX);
        jmenuSetTop(menuName + jmenu.menuName, newY);
    }
}

function jmenuPopUp(menuName)
{
    var submenuName = menuName;
    if (!menuName)
        return;

    jmenuShutdown();

    var popUpMenu = document.getElementById(menuName + jmenu.menuName);
    if (popUpMenu) {
        jmenuHideControls(popUpMenu, 'SELECT');
    }

    do {
        if (!menuName) {
            break;
        }

        jmenuPopUpL(menuName, true, submenuName == menuName);
        menuName = eval("jmenu.father."+menuName);

        var popUpMenu2 = document.getElementById(menuName + jmenu.menuName);
        if (popUpMenu2) {
            jmenuHideControls(popUpMenu2, 'SELECT');
        }

    } while (menuName != "")
}

function jmenuGetObjPosition(obj)
{
    var pos = getControlPixelPos(obj, 0, 0, 0, 0, 0);
    return {left: pos[0], top: pos[1],
        right: pos[0]+obj.offsetWidth, bottom: pos[1]+obj.offsetHeight,
        width: obj.offsetWidth, height: obj.offsetHeight};
}


function jmenuPopUpL(menuName, on, runAnimation)
{
    if (!menuName)
        return;

    var el = document.getElementById(menuName + jmenu.menuName);

    if (!el)
        return;

    if (jmenu.jmenuLoaded) {
        if (!jmenuMovedLayers) {
            jmenuMoveLayers();
            jmenuMovedLayers = 1;
        }
        if (on) {
            if (runAnimation) {
                animate(menuName + jmenu.menuName);
                if (jmenu.mobile) {
	                var cl = document.getElementById(menuName + jmenu.menuName).getElementsByTagName('a');
	                if (cl.length) {
	                	try { cl[0].focus(); } catch(e) { }
	                }
                }
            } else { 
                document.getElementById(menuName + jmenu.menuName).style.visibility = 'visible';
            }
            highlightParentItem('ref' + menuName + jmenu.menuName, true);
        } else {
            document.getElementById(menuName + jmenu.menuName).style.visibility = 'hidden';
            highlightParentItem('ref' + menuName + jmenu.menuName, false);
            if (jmenu.mobile) {
            	var cl = document.getElementById('ref' + menuName + jmenu.menuName).getElementsByTagName('a');
            	if (cl.length) {
            		try { cl[0].focus(); } catch(e) { }
            	}
            }
        }
    }
}

function animate(submenuId)
{
    var stepQuantity = 10;
    var timeStep = 25;
    var totalTime = 100;
    var menuDiv = document.getElementById(submenuId);
    if (jmenu.prevSubmenu == submenuId || is_msie() || true) {
        menuDiv.style.visibility = 'visible';
        return;
    }
    var opacityEnd = __getComputedStyle(menuDiv, 'opacity');
    jmenu.prevSubmenu = submenuId;
    if (!menuDiv.opacityEnd) menuDiv.opacityEnd = opacityEnd;
    if (menuDiv.style.visibility == 'hidden') {
        clearInterval(menuDiv.timerId);
        opacityEnd = menuDiv.style.opacity = menuDiv.opacityEnd;
        var menuHeight = parseInt(menuDiv.offsetHeight);
        var borderTop     = parseInt(__getComputedStyle(menuDiv, 'borderTopWidth'));
        var borderBottom  = parseInt(__getComputedStyle(menuDiv, 'borderBottomWidth'));
        var paddingTop    = parseInt(__getComputedStyle(menuDiv, 'paddingTop'));
        var paddingBottom = parseInt(__getComputedStyle(menuDiv, 'paddingBottom'));

        menuHeight = menuHeight - borderTop - borderBottom - paddingTop - paddingBottom;

        var step = parseInt(menuHeight / stepQuantity);

        timeStep = parseInt(totalTime / stepQuantity);
        var opacityStep = parseFloat(opacityEnd / stepQuantity);
        menuDiv.style.overflow = 'hidden';
        menuDiv.style.opacity = '0';
        menuDiv.style.height = '0px';
        menuDiv.style.visibility = 'visible';
        menuDiv.timerId = setInterval(function() {
            var height  = parseInt(menuDiv.style.height ? menuDiv.style.height : 0);
            var opacity = parseFloat(menuDiv.style.opacity);
            if (height + step >= menuHeight) {
                clearInterval(menuDiv.timerId);
                menuDiv.style.height  = '';
                menuDiv.style.opacity = opacityEnd;
            } else {
                menuDiv.style.opacity = opacity + opacityStep;
                menuDiv.style.height  = (height + step) + 'px';
            }
        }, timeStep);
    }
}

function timerCallback(ctrl, endHeight, step, opacityEnd, opacityStep)
{
    var height  = parseInt(ctrl.style.height);
    var opacity = parseFloat(ctrl.style.opacity);
    if (height + step >= endHeight) {
        clearInterval(ctrl.timerId);
        ctrl.style.height  = 'auto';
        ctrl.style.opacity = opacityEnd;
    } else {
        ctrl.style.opacity = opacity + opacityStep;
        ctrl.style.height  = (height + step) + 'px';
    }
}

function jmenuSetLeft(layer,x)
{
    var el = document.getElementById(layer);

    if (!el)
        return;

    el.style.left = x + "px";
}

function jmenuSetTop(layer,y)
{
    var el = document.getElementById(layer);

    if (!el)
        return;

    el.style.top = y + "px";
}

function jmenuGenerateClientMenu(menuName)
{
    activateMenu(menuName);
    if (!jmenu) {
        return;
    }
    if (typeof(jmenu) != "object") {
        return;
    }
    var parent = document.getElementById(menuName);
    if (!parent) {
        return;
    }
    if (jmenu.cssClass) parent.className = jmenu.cssClass;

    document.onclick = jmenuShutdown;

    var first = 1, t = '', position = 0, startTabIndex = parseInt(parent.getAttribute('tabindex'));
    t += jmenu.beforeFirst;
    for (var i = 0; i < jmenu.items.length; i++) {
        var item = jmenu.items[i];
        var extraAttr = '';
        var caption = '';
        if (!item.parentId) {
            var style = "";
            if (item.meuHref) {
                style = "cursor: pointer; ";
            }
            if (jmenu.menuType == 'text') {
                caption = item.alt;
            } else if (jmenu.menuType == 'image') {
                if (item.sprite) {
                    // sprite
                    caption = "";
                    extraAttr = "data-x=\"" + item.x + "\" " +
                        "data-y=\"" + item.y + "\" " +
                        "data-hoverx=\"" + item.hoverX + "\" " +
                        "data-hovery=\"" + item.hoverY + "\" " +
                        "title=\"" + item.alt + "\"";
                    style += "background-position: -" + item.x + "px -" + item.y + "px; " +
                        "width: " + item.width + "px; height: " + item.height + "px; " +
                        "background-image: url(" + item.sprite + "); display: -moz-inline-box; display: inline-block; " +
                        "vertical-align: top";
                    if (is_msie()) {
                        style += "; overflow: hidden";
                    }
                } else {
                    // separate images
                    caption =
                        "<img border=\"0\" "  +
                        (item.src ? "src=\"" + item.src + "\" " : "") +
                        (item.alt ? "alt=\"" + item.alt + "\" " : "") +
                        "/>";
                    extraAttr =
                        (item.inactSrc ? "data-inactsrc=\"" + item.inactSrc + "\" " : "") +
                        (item.hoverSrc ? "data-hoversrc=\"" + item.hoverSrc + "\" " : "");
                }
            }
            extraAttr +=
                (item.cssClass ? "class=\"" + item.cssClass + "\" " : "") +
		        (item.inactClass ? "data-inactclass=\"" + item.inactClass + "\" " : "") +
                (item.hoverClass ? "data-hoverclass=\"" + item.hoverClass + "\" " : "") +
		        (item.menuHref ? "data-menuhref=\"" + item.menuHref + "\" " : "") +
		        (item.menuId ? "data-menuid=\"" + item.menuId + "\" " : "") +
		        (item.menuOrient ? "data-menuorient=\"" + item.menuOrient + "\" " : "data-menuorient=\"vert\" ") +
		        (item.menuMode ? "data-menumode=\"" + item.menuMode + "\" " : "data-menumode=\"normal\" ") +
		        (item.popupW ? "data-popupw=\"" + item.popupW + "\" " : "") +
		        (item.popupH ? "data-popuph=\"" + item.popupH + "\" " : "") +
		        (item.id ? "id=\"" + item.id + menuName + "\" " : "") +
                "data-menuname=\"" + menuName + "\" " +
                "style=\"" + style + "\" ";
                if (!jmenu.mobile) {
		            extraAttr +=
		                "onmouseover=\"navbutton_over(this, event)\" " +
		                "onmouseout=\"navbutton_out(this, event)\" " +
		                "onclick=\"navbutton_click(this, event)\" ";
                } else {
                    if (item.menuId) {
                        extraAttr += "onclick=\"navbutton_over(this, event)\" ";
                        item.menuHref = null;
                    } else {
                        extraAttr += "onclick=\"navbutton_click(this, event)\" ";
                    }
                }
            var menuItem = '';
            // find separator
            var menuSep = '';
            jmenu.menuSeparators.sort(SortCallback);
            for (var k = 0; k < jmenu.menuSeparators.length; k++) {
                var sep = jmenu.menuSeparators[k];
                if (position % sep.order == 0) {
                    menuSep = trim(jmenu.menuSeparators[k].code);
                    break;
                }
            }
            menuItem += !first ? menuSep : '';

            if (item.menuHref && item.menuMode != 'new_window' && item.menuMode != 'popup') {
                menuItem += '<a href="' + item.menuHref + '" ';
            } else {
                menuItem += '<a href="javascript:undefined" ';
            }
            menuItem += 'tabindex="' + (startTabIndex + i) + '" ';
            menuItem += extraAttr + '>';
            menuItem += caption;
            menuItem += '</a>';

    	    t += menuItem;
            first = 0;
            position++;
            if (position == jmenu.maxItems) break;
        }
    }
    t+= '<div id="'+jmenu.menuName+ 'SubmenuPlaceholder"></div>';
    t+= jmenu.afterLast;
    parent.tabIndex = -1;
	parent.innerHTML = t;

    jmenuMoveLayers();
    jmenu.jmenuLoaded = 1;
}

function SortCallback(a,b)
{
    if (a.order > b.order) return -1;
    if (a.order < b.order) return 1;
    return 0;
}

function jmenuGeneratePopUpMenu(menuId)
{
    if (!jmenu)
        return;

    if (menuId == "")
        return;

    if (document.getElementById(menuId + jmenu.menuName))
        return;

    var submenuDiv = document.createElement('div');
    submenuDiv.id = menuId.toString()+jmenu.menuName;
    submenuDiv.style.position = 'absolute';
    submenuDiv.style.left = 0;
    submenuDiv.style.top = 0;
    submenuDiv.style.visibility = 'hidden';
    submenuDiv.className = 'submenuShell' + (jmenu.mobile ? ' MobileSubMenu' : '');
    submenuDiv.style.zIndex = 7300;
    if (jmenu.closeOnOut) {
        submenuDiv.onmouseover = function() {
            if (jmenu._timer) clearTimeout(jmenu._timer);
            jmenu._inSubMenu = true;
        }
        submenuDiv.onmouseout = function() {
            jmenu._timer = setTimeout(function(){ jmenu._inSubMenu = false; jmenuShutdown(); }, 100);
        }
    }

    // count quantity of items for current menu item
    var items_count = 0;
    var current_menu_items = new Array();
    for (var i=0; i<jmenu.items.length; i++) {
        var father = eval("jmenu.father."+jmenu.items[i].id.substr(3));
        if (father == menuId) {
            items_count++;
            current_menu_items.push(jmenu.items[i]);
        }
    }
    var columnsQuantity = 1;
    if (!jmenu.mobile && navmenu_max_items_per_column > 0) {
        columnsQuantity = parseInt(items_count / navmenu_max_items_per_column) + 1;
        var itemsPerColumn  = parseInt(items_count / columnsQuantity) +
                                ((items_count % columnsQuantity > 0) ? 1 : 0);
    }

    var isMultiColumn = (columnsQuantity > 1);
    if (isMultiColumn) {
        var table = document.createElement('table');
        table.setAttribute('cellpadding', '0');
        table.setAttribute('cellspacing', '0');
        submenuDiv.appendChild(table);
        var tbody = document.createElement('tbody');
        table.appendChild(tbody);
        var columns = document.createElement('tr');
        tbody.appendChild(columns);
    }
    var ncol = 0;
    if (jmenu.mobile) {
        // create 'Back/Close' option
        if (!isMultiColumn) {
            column = submenuDiv;
        } else {
            var column = document.createElement('td');
            column.className = 'submenuColumnFirst submenuLines';
            columns.appendChild(column);
            ncol++;
        }
        var a = document.createElement('a');
        a.setAttribute('data-parentmenuid', menuId);
        a.href = 'javascript:undefined';
    	a.className = "submenuInactiveItem MobileSubMenuClose";
    	a.innerHTML = 'Close ✖';
        a.onclick = function(event) { 
        	jmenuPopUp(menuId); 
        	jmenuPopUpL(menuId, false); 
        	event.cancelBubble = true;
    	}
        column.appendChild(a);
    }
    for (var i = 0; i < current_menu_items.length; i++) {
        // columns code
        var current_item = current_menu_items[i];
        if (!isMultiColumn) {
            column = submenuDiv;
        } else {
            var ind = jmenu.mobile ? i + 1 : i;
            if (ind % itemsPerColumn == 0) {
                var column = document.createElement('td');
                if (ncol == 0) {
                    column.className = 'submenuColumnFirst submenuLines';
                } else if (ncol == columnsQuantity-1) {
                    column.className = 'submenuColumnLast submenuLines';
                } else {
                    column.className = 'submenuColumn submenuLines';
                }
                columns.appendChild(column);
                ncol++;
            }
        }

        var caption = (current_item.alt) ? current_item.alt : '';
        var href = current_item.menuHref;

        var div = document.createElement('div');
        div.className = "submenuInactiveItem" + (jmenu.mobile ? " MobileSubMenuInactiveItem" : '');
        div.setAttribute('data-parentmenuid', menuId);

        if (current_item.separator) {
            div.className = 'submenuSeparator submenuLines' + (jmenu.mobile ? ' MobileSubMenuSeparator' : '');
        } else if (current_item.header) {
            div.innerHTML = current_item.alt;
            div.className = 'submenuHeading' + (jmenu.mobile ? ' MobileSubMenuHeading' : '');
        } else {
        	div.setAttribute('data-menuid', current_item.menuId ? current_item.menuId : '');
        	div.setAttribute('data-menuhref', current_item.menuHref ? current_item.menuHref : '');
        	div.setAttribute('data-menumode', current_item.menuMode ? current_item.menuMode : '');
        	div.setAttribute('data-menuorient', current_item.menuOrient ? current_item.menuOrient : '');
        	div.setAttribute('data-popupw', current_item.popupW ? current_item.popupW : '');
        	div.setAttribute('data-popuph', current_item.popupH ? current_item.popupH : '');
            div.id  = current_item.id ? current_item.id + jmenu.menuName : '';

            if (!jmenu.mobile) {
                div.onmouseover = function(event) {navmenu_over(this, event ? event : window.event);};
                div.onmouseout = function(event) {navmenu_out(this, event ? event : window.event);};
                div.onclick = function(event) {navmenu_click(this, event ? event : window.event);return false;};
            } else {
                if (current_item.menuId) {
                    href = null;
                    div.onclick = function(event) {navmenu_over(this, event ? event : window.event);return false;};
                } else {
                    div.onclick = function(event) {navmenu_click(this, event ? event : window.event);return false;};
                }
            }

            var a = document.createElement('a');
            if (href) {
                a.href = href;
            } else {
                a.href = 'javascript:undefined';
            }
            a.innerHTML = caption;
            div.appendChild(a);

            if (current_item.menuId) {
                div.className = div.className + ' hasSubmenu';
            }
        }
        column.appendChild(div);
    }

    var menuDiv = document.getElementById(jmenu.menuName+'SubmenuPlaceholder');
    menuDiv.appendChild(submenuDiv);
}

var navmenu_highlight = 1;


function getParentsMenuRecursively(parentmenuId, disallowedMenuItemsToHide) {

	disallowedMenuItemsToHide.push(parentmenuId);

	var parentMenu    = document.getElementById('ref' + parentmenuId + jmenu.menuName);
	if(!parentMenu) return;

	var _parentMenuID  =  parentMenu.getAttribute('data-parentmenuid');
	if(!_parentMenuID) return;

	getParentsMenuRecursively(_parentMenuID, disallowedMenuItemsToHide);
}

function highlightParentItem(id, isOn)
{
    var m = id.match(/(ref(L\d+))(.+)/);
    var refLm = m[1];
    var menuName = m[3];
    var Lm = m[2];
    var currentItem  = document.getElementById(id);
    var parentMenuId = currentItem.getAttribute('data-parentmenuid');
    var parentElement = document.getElementById('ref' + parentMenuId + menuName);

    if (parentElement) { // submenu level
        if (isOn) {
            currentItem.className = currentItem.className.replace('submenuInactiveItem', 'submenuActiveItem');
            if (jmenu.mobile) {
                currentItem.className = currentItem.className.replace('MobileSubMenuInactiveItem', 'MobileSubMenuActiveItem');
            }
        } else {
            currentItem.className = currentItem.className.replace('submenuActiveItem', 'submenuInactiveItem');
            if (jmenu.mobile) {
                currentItem.className = currentItem.className.replace('MobileSubMenuActiveItem', 'MobileSubMenuInactiveItem');
            }
        }
    }
    if (!parentElement) { // first level
        navbutton_highlight(currentItem, isOn);
    }
}

function navmenu_over(ctl, event)
{
    var menuHref = ctl.getAttribute('data-menuhref');
    var menuId = ctl.getAttribute('data-menuid');
    var parentmenuId = ctl.getAttribute('data-parentmenuid');

    ctl.className = ctl.className.replace('submenuInactiveItem', 'submenuActiveItem');
    if (jmenu.mobile) {
        ctl.className = ctl.className.replace('MobileSubMenuInactiveItem', 'MobileSubMenuActiveItem');
    }

    if (menuId) {
        jmenuGeneratePopUpMenu(menuId);
        jmenuMoveLayer(menuId, 2, 6, 'vert');
        jmenuPopUp(menuId);
        if (array_indexof(jmenu_openedChildren, menuId) == -1) jmenu_openedChildren.push(menuId);
	} else {
		var disallowedMenuItemsToHide = new Array();
		getParentsMenuRecursively(parentmenuId, disallowedMenuItemsToHide);
        for (var i = 0; i <	jmenu_openedChildren.length; i++) {
            if (array_indexof(disallowedMenuItemsToHide, jmenu_openedChildren[i]) == -1)
                jmenuPopUpL(jmenu_openedChildren[i], false);
        }
	}

    if (menuHref) {
        window.status = menuHref.replace(/(&&|\?&|&$|\?$)/g, '');
    }
    if (jmenu.mobile) {
    	event.cancelBubble = true;
    }
}

function navmenu_out(ctl, event)
{
    if (ctl.getAttribute('data-menuid')) return; // see jmenuPopUpL
    ctl.className  = ctl.className.replace('submenuActiveItem', 'submenuInactiveItem') ;
}

function navmenu_click(ctl, event)
{
    var menuHref = ctl.getAttribute('data-menuhref');
    var menuId = ctl.getAttribute('data-menuid');
    var menuMode = ctl.getAttribute('data-menumode');
    var popupW = ctl.getAttribute('data-popupw');
    var popupH = ctl.getAttribute('data-popuph');

    if (menuHref) {
        if (menuMode == 'new_window') {
            openWindow(menuHref, '');
            return false;
        } else if (menuMode == 'popup') {
            var attr = "scrollbars=yes,resizable=yes";
            if (popupW)
                attr += ',width=' + popupW;
            if (popupH)
                attr += ',height=' + popupH;
            openWindow(menuHref, attr);
            return false;
        } else {
            setLocation(menuHref);
        }
    } else {
        event.cancelBubble = true;
    }
}

function navbutton_over(ctl, event)
{
    var menuHref = ctl.getAttribute('data-menuhref');
    var menuId = ctl.getAttribute('data-menuid');
    var parentMenuId = ctl.getAttribute('data-parentmenuid');
    var menuMode = ctl.getAttribute('data-menumode');
    var menuOrient = ctl.getAttribute('data-menuorient');
    var menuName = ctl.getAttribute('data-menuname');

    activateMenu(menuName);
    var subMenuObj = document.getElementById(menuId+menuName);
    if (subMenuObj && subMenuObj.style.visibility == 'visible') {
        jmenu.prevSubmenu = menuId+menuName;
    } else {
        jmenu.prevSubmenu = '';
    }

    navbutton_highlight(ctl, true);
    if (menuId) {
        jmenuGeneratePopUpMenu(menuId);
        jmenuMoveLayer(menuId, 0, 0, menuOrient);
        jmenuPopUp(menuId);
    } else if (parentMenuId) {
        jmenuPopUp(parentMenuId);
    }
    else {
        jmenuShutdown();
    }

    if (menuHref) {
        window.status = menuHref.replace(/(&&|\?&|&$|\?$)/g, '');
    }
    if (jmenu.mobile) {
    	event.cancelBubble = true;
    }
}

function navbutton_out(ctl, event)
{
    var menuId = ctl.getAttribute('data-menuid');
    if (menuId) {
        if (jmenu.closeOnOut) {
            setTimeout(function(){ if (!jmenu._inSubMenu) { jmenuPopUpL(menuId, false); jmenuShowControls(true); } }, 100);
        }
        return; // see jmenuPopUpL
    }
    navbutton_highlight(ctl, false);
}

function navbutton_click(ctl, event)
{
    var menuHref = ctl.getAttribute('data-menuhref');
    var menuId = ctl.getAttribute('data-menuid');
    var menuMode = ctl.getAttribute('data-menumode');
    var popupW = ctl.getAttribute('data-popupw');
    var popupH = ctl.getAttribute('data-popuph');
    var menuName = ctl.getAttribute('data-menuname');
    activateMenu(menuName);

    if (menuHref) {
        if (menuMode == 'new_window') {
            openWindow(menuHref, '');
        } else if (menuMode == 'popup') {
            var attr = "scrollbars=yes,resizable=yes";
            if (popupW)
                attr += ',width=' + popupW;
            if (popupH)
                attr += ',height=' + popupH;
            openWindow(menuHref, attr);
        } else {
            setLocation(menuHref);
        }
    } else {
        event.cancelBubble = true;
    }
}

function navbutton_highlight(ctl, v)
{
    if (navmenu_highlight) {
        var useSprite = ctl.getAttribute('data-hoverx') != '' && ctl.getAttribute('data-hoverx') != null;
        if (useSprite) {
            if (v) {
                var hoverX = ctl.getAttribute('data-hoverx');
                var hoverY = ctl.getAttribute('data-hovery');
                ctl.style.backgroundPosition = '-' + hoverX + 'px -' + hoverY + 'px';
            } else {
                var x = ctl.getAttribute('data-x');
                var y = ctl.getAttribute('data-y');
                ctl.style.backgroundPosition = '-' + x + 'px -' + y + 'px';
            }
        } else {
            if (v) {
                var hoverSrc = ctl.getAttribute('data-hoversrc');
                var hoverClass = ctl.getAttribute('data-hoverclass');
                var img = ctl.getElementsByTagName('img')[0];
                if (img) img.src = hoverSrc;
                ctl.className = hoverClass;
            } else {
                var inactSrc = ctl.getAttribute('data-inactsrc');
                var inactClass = ctl.getAttribute('data-inactclass');
                var img = ctl.getElementsByTagName('img')[0];
                if (img) img.src = inactSrc;
                ctl.className = inactClass;
            }
        }
    }
}
/**
 * Base (common / universal) function for search form controls.
 *
 * @param  mixed  aValue       (int) Frame ID if search by Frame
 *                             (int) Interface Instance ID if search by Interface
 *                             (obj) Reference to form
 * @param  string aControlName Control Name
 * @param  string aAttrName    Form attribute name for comparison with "aValue". If "aValue" is reference to form, may be false or unsigned.
 * @return mixed               FALSE if no controls found, control's array otherwise
 * @access private
*/
function _getControlsCommon(aValue, aControlName, aAttrName)
{
    if (!aValue)      return false;
    if (!aControlName) return false;
    var ctls = document.getElementsByName(aControlName);
    if (!ctls || !ctls.length) return false;
    var out        = new Array();
    var form       = false;
    var vNeedValue = false;
    for (var i = 0; i < ctls.length; i++ ) {
        form   = ctls[i].form;
        if (!form) continue;
        if ((aAttrName == 'attr_frame_id') || (aAttrName == 'attr_instance_id')) {
            vNeedValue = form.getAttribute(aAttrName);
            if (vNeedValue == aValue) out[out.length] = ctls[i];
        } else if (!aAttrName) {
            if (form == aValue)       out[out.length] = ctls[i];
        }
    }
    return out.length ? out : false;
}

/**
 * Find form by Frame ID
 * 
 * @param  int    frameId     Frame ID
 * @return mixed              FALSE if form not found, reference to form otherwise
 * @access public
*/
function getFormByFrame(frameId)
{
    if (!frameId) return false;
    var fb = document.getElementById('framebox_' + frameId);
    if (!fb) return false;
    var forms = fb.getElementsByTagName('FORM');
    for (var i = 0; i < forms.length; i++ ) {
        if (frameId != 1) {
            var vFrameId = forms[i].getAttribute('attr_frame_id');
            if (vFrameId && vFrameId == frameId) return forms[i];
        } else {
            return forms[i];
        }
    }
    return false;
}

/**
 * Get interface ID by form
 * 
 * @param  obj    form        Reference to form
 * @return mixed              Interface Instance ID on success, null on failure (attribute is not present)
 * @access public
*/
function getInterfaceByForm(form)
{
    return form.getAttribute('attr_instance_id');
}
function getPluginByForm(form)
{
    return form.getAttribute('attr_plugin_num');
}

/**
 * Get frame ID by form
 * 
 * @param  obj    form        Reference to form
 * @return mixed              Frame ID on success, null on failure (attribute is not present)
 * @access public
*/
function getFrameByForm(form)
{
    return form.getAttribute('attr_frame_id');
}

/**
 * Find form's controls by control Name and form's Frame ID
 * 
 * @param  int    frameId     Frame ID
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's array otherwise
 * @access public
*/
function getControlsByFrame(frameId, controlName)
{
    return _getControlsCommon(frameId, controlName, 'attr_frame_id')
}

/**
 * Find form's controls by control Name and form's Instance ID
 * 
 * @param  int    instanceId  Interface Instance ID
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's array otherwise
 * @access public
*/
function getControlsByInterface(instanceId, controlName)
{
    return _getControlsCommon(instanceId, controlName, 'attr_instance_id')
}

/**
 * Find form's controls by control Name
 * 
 * @param  obj    form        Reference to form
 * @param  string controlName Control Name
 * @return mixed              FALSE if no controls found, control's collection otherwise
 * @access public
*/
function getControlsByForm(form, controlName)
{
    return _getControlsCommon(form, controlName)
}

/**
 * Find frame element by ID
 * 
 * @param  int    frameId   Frame ID
 * @param  string elementId Element ID without Frame ID postfix.
 * @return mixed            FALSE if no elements found, element otherwise.
 * @access public
*/
function getFrameElementById(frameId, elementId)
{
    if (!frameId)   return false;
    if (!elementId) return false;
    var ctls = document.getElementById(elementId + '_' + frameId);
    return ctls;
}

/**
 * Find frame elements by Name
 * 
 * @param  int    frameId        Frame ID.
 * @param  string elementOldName Element Name without Frame ID postfix.
 * @return mixed                 FALSE if no elements found, element's collection otherwise.
 * @access public
*/
function getFrameElementsByName(frameId, elementOldName)
{
    if (!frameId)        return false;
    if (!elementOldName) return false;
    var ctls = document.getElementsByName(elementOldName + '_' + frameId);
    if (!ctls || !ctls.length) return false;
    return ctls;
}var divHeight = 300;
var divWidth = 300;
var imageZoomCtrls = [];
var lastX = 0;
var lastY = 0;

// call on window resize
function recalcZoomPosition()
{
    for(var i = 0; i < imageZoomCtrls.length; i++) {
        imageZoomCtrls[i].position = getObjPosition(imageZoomCtrls[i]);
        recalulateZoomData(imageZoomCtrls[i]);
    }
}

function trackMouse(event)
{
    if (!event) event = window.event;
    lastX = event.clientX;
    lastY = event.clientY;
}

addHandler(window, 'resize', recalcZoomPosition);
addHandler(document, 'mousemove', trackMouse);

function zoomMove(ctrl, event)
{
    if (!event) event = window.event;
    if (!ctrl.bigImageControl) return;
    lastX = event.clientX;
    lastY = event.clientY;
    moveZoomCursor(ctrl, lastX, lastY);
}

function startZoom(ctrl, event)
{
    if (!ctrl.bigImageControl) {
        createZoomDiv(ctrl);
    } else if (ctrl.broken != 1) {
        ctrl.bigImageControl.style.visibility = 'visible';
    }
}

function stopZoom(ctrl, event)
{
    if (!event) event = window.event;
    lastX = event.clientX;
    lastY = event.clientY;
    if (ctrl.bigImageControl && isCursorOutOfImage(ctrl, lastX, lastY)) {
	    ctrl.bigImageControl.style.visibility = 'hidden';
	    ctrl.zoomCursor.style.visibility = 'hidden';
	    showElements();
    }
}

function createZoomDiv(ctrl)
{
    var url = ctrl.getAttribute('data-bigimage');
    var position = getObjPosition(ctrl,0,0,0,0,0);
    imageZoomCtrls.push(ctrl);
    ctrl.divWidth = divWidth;
    ctrl.divHeight = divHeight;
    ctrl.position = position;
    ctrl.scale = 1;

    ctrl.bigImageControl = document.createElement('DIV');
    document.body.appendChild(ctrl.bigImageControl);
    ctrl.bigImageControl.className = 'zoomBigImage';
    ctrl.bigImageControl.style.visibility = 'hidden';
    ctrl.bigImageControl.style.position = 'absolute';
    ctrl.bigImageControl.style.top = position['top'] + 'px';

    var b_left = position.left + position.width + 10;
    var b_top = position.top;
    if (b_left + ctrl.divWidth > getClientWidth()) {
        b_left = position.left - 10;
        b_top = position.top + position.height + 10;
    }
    ctrl.bigImageControl.style.left = b_left + 'px';
    ctrl.bigImageControl.style.top = b_top + 'px';
    
    ctrl.bigImageControl.style.overflow = 'hidden';
    ctrl.bigImageControl.style.width = ctrl.divWidth + 'px';
    ctrl.bigImageControl.style.height = ctrl.divHeight + 'px';
    ctrl.bigImageControl.style.zIndex = 999;

    ctrl.indicator = document.createElement('DIV');
    ctrl.indicator.style.position = 'absolute';
    ctrl.indicator.style.backgroundColor = 'white';
    ctrl.indicator.style.color = 'black';
    ctrl.indicator.style.textDecoration = 'none';
    ctrl.indicator.innerHTML = 'Loading...';
    ctrl.indicator.style.padding = '6px';
    ctrl.indicator.style.opacity = 0.6;
    ctrl.indicator.style.filter = 'Alpha(Opacity=60);';
    ctrl.indicator.style.visibility = 'hidden';
    ctrl.indicator.style.zIndex = 9999;

    ctrl.zoomCursor = document.createElement('DIV');
    ctrl.zoomCursor.style.visibility = 'hidden';
    ctrl.zoomCursor.style.backgroundColor = 'white';
    ctrl.zoomCursor.style.border = '1px solid Gray';
    ctrl.zoomCursor.style.opacity = 0.6;
    ctrl.zoomCursor.style.filter = 'Alpha(Opacity=60);';
    ctrl.zoomCursor.style.position = 'absolute';
    ctrl.zoomCursor.style.zIndex = 10000;
    ctrl.zoomCursor.style.width = '0px';
    ctrl.zoomCursor.style.height = '0px';
    ctrl.zoomCursor.style.top = '0px';
    ctrl.zoomCursor.style.left = '0px';

    ctrl.onload = function () {
        ctrl.broken = 0;
        if (is_msie()) {
            // we must recreate the img to get right offsetWidth and offsetHeight
            ctrl.bigImageControl.removeBigImage();
            ctrl.bigImageControl.createBigImage();
        }
        recalulateZoomData(this);
        ctrl.changed = 1;
    }

    ctrl.bigImageControl.removeBigImage = function() {
        ctrl.bigImageControl.removeChild(ctrl.bigImageControl.image);
        ctrl.bigImageControl.image = null;
    }
    ctrl.bigImageControl.createBigImage = function() {
        var image = new Image();
        ctrl.bigImageControl.image = image;
        ctrl.changed = 1;
        image.onload = function()
        {
            if (image.offsetWidth == 1 && image.offsetHeight == 1) { // broken image
                ctrl.indicator.style.visibility = 'hidden';
                ctrl.zoomCursor.style.visibility = 'hidden';
                ctrl.bigImageControl.style.visibility = 'hidden';
                ctrl.broken = 1;
                return;
            }
            if (image.offsetWidth)
                ctrl.scale = image.offsetWidth/ctrl.position['width'];
            if (ctrl.divWidth > image.offsetWidth)
                ctrl.divWidth  = image.offsetWidth;
            if (ctrl.divHeight > image.offsetHeight)
                ctrl.divHeight = image.offsetHeight;
            ctrl.bigImageControl.style.width = ctrl.divWidth + 'px';
            ctrl.bigImageControl.style.height = ctrl.divHeight + 'px';
            ctrl.indicator.style.visibility = 'hidden';
            ctrl.zoomCursor.style.width = ctrl.divWidth/ctrl.scale + 'px';
            ctrl.zoomCursor.style.height = ctrl.divHeight/ctrl.scale + 'px';
            ctrl.changed = 0;

            moveZoomCursor(ctrl, lastX, lastY);
        }
        ctrl.bigImageControl.appendChild(image);
    };
    ctrl.bigImageControl.createBigImage();
    ctrl.bigImageControl.image.src = url + (is_msie() ? "&random=" + Math.random().toString(): '');
    document.body.appendChild(ctrl.zoomCursor);
    document.body.appendChild(ctrl.indicator);
    ctrl.indicator.style.top = ctrl.position.top + ctrl.offsetHeight / 2 - ctrl.indicator.offsetHeight / 2 + 'px';
    ctrl.indicator.style.left = ctrl.position.left + ctrl.offsetWidth / 2 - ctrl.indicator.offsetWidth / 2 + 'px';
    ctrl.indicator.style.visibility = 'visible';

    ctrl.zoomCursor.onmousemove = function(event) {zoomMove(ctrl,event)};
    ctrl.zoomCursor.onmouseout = function(event) {stopZoom(ctrl,event)};
    ctrl.zoomCursor.onmouseover = ctrl.parentNode.onmouseover;
    if (is_opera() == 0)
        ctrl.onmouseout = function(event) {stopZoom(ctrl,event)};

}

function recalulateZoomData(ctrl)
{
    if (ctrl.bigImageControl.style.visibility == 'visible') {
        ctrl.indicator.style.visibility = 'visible';
        ctrl.bigImageControl.style.visibility = 'hidden';
        ctrl.zoomCursor.style.visibility = 'hidden';
        showElements();
    }
    ctrl.indicator.style.top = ctrl.position.top + ctrl.offsetHeight / 2 - ctrl.indicator.offsetHeight / 2 + 'px';
    ctrl.indicator.style.left = ctrl.position.left + ctrl.offsetWidth / 2 - ctrl.indicator.offsetWidth / 2 + 'px';
    ctrl.position.width = ctrl.offsetWidth;
    ctrl.position.height = ctrl.offsetHeight;
    ctrl.divWidth = divWidth;
    ctrl.divHeight = divHeight;
    ctrl.bigImageControl.image.src = ctrl.getAttribute('data-bigimage');
    ctrl.changed = 0;
}

function isCursorOutOfImage(ctrl, clientX, clientY)
{
    return clientX + getScrollLeft() <= ctrl.position['left'] ||
        clientX + getScrollLeft() >= ctrl.position['left']  + ctrl.position['width'] ||
        clientY + getScrollTop() <= ctrl.position['top'] ||
        clientY + getScrollTop() >= ctrl.position['top'] + ctrl.position['height'];
}

function moveZoomCursor(ctrl, clientX, clientY)
{
    if (ctrl.broken == 1) return;
    if (isCursorOutOfImage(ctrl, clientX, clientY) || ctrl.changed == 1)
    {
        if (ctrl.bigImageControl.style.visibility == 'visible') {
	        ctrl.zoomCursor.style.visibility = 'hidden';
	        ctrl.bigImageControl.style.visibility = 'hidden';
	        showElements();
        }
        return ;
    }
    var b_left = ctrl.position.left + ctrl.position.width + 10;
    var b_top = ctrl.position.top;
    if (b_left + ctrl.divWidth > getClientWidth()) {
        b_left = ctrl.position.left - 10;
        b_top = ctrl.position.top + ctrl.position.height  +10;
    }
    ctrl.bigImageControl.style.left = b_left + 'px';
    ctrl.bigImageControl.style.top = b_top + 'px';
    var cursorY = clientY + getScrollTop();
    var cursorX = clientX + getScrollLeft();
    var cursorTop = cursorY - ctrl.position.top - ctrl.zoomCursor.offsetHeight/2;
    var cursorLeft = cursorX - ctrl.position.left - ctrl.zoomCursor.offsetWidth/2;
    if (cursorTop < 0) cursorTop = 0;
    if (cursorLeft < 0) cursorLeft = 0;
    if (cursorTop + ctrl.zoomCursor.offsetHeight > ctrl.position.height)
        cursorTop = ctrl.position.height - ctrl.zoomCursor.offsetHeight;
    if (cursorLeft + ctrl.zoomCursor.offsetWidth > ctrl.position.width)
        cursorLeft = ctrl.position.width - ctrl.zoomCursor.offsetWidth;
    ctrl.zoomCursor.style.left = ctrl.position.left + cursorLeft + 'px';
    ctrl.zoomCursor.style.top = ctrl.position.top + cursorTop  + 'px';
    ctrl.zoomCursor.style.visibility = 'visible';
    ctrl.bigImageControl.style.visibility = 'visible';
    hideElements(ctrl.bigImageControl);
    var bigTop = cursorTop*ctrl.scale;
    var bigLeft = cursorLeft*ctrl.scale;
    ctrl.bigImageControl.image.style.marginTop = -bigTop + 'px';
    ctrl.bigImageControl.image.style.marginLeft = -bigLeft + 'px';
}
var popupFrameVisible = false, popupSavedRange = null, hiddenDropdowns = new Array(),
	popupEventsAttached = false, popupIFrame = null,
	popupDiv = null, popupCloseAction = null, popupCloseMsg = null;

var popupStack = [];
function createPopup(noIFrame)
{
    var zIndex = 8000 + 100*popupStack.length;
    var p = {'zIndex': zIndex};
    if (!noIFrame) {
        if (popupStack.length == 0) {
            if (!popupIFrame) {
                var res = render_popup_iframe(zIndex);
                popupIFrame = res.iframe;
                popupDiv = res.div;
            }
            p['iframe'] = popupIFrame;
            p['div'] = popupDiv;
        } else {
            var res = render_popup_iframe(zIndex);
            p['iframe'] = res.iframe;
            p['div'] = res.div;
        }
    }
    popupStack.push(p);
}

// available properties: 'iframe', 'div', 'closeFunc', 'dialog', 'fade', 'zIndex', 'title'
function getPopupProp(prop, ind)
{
    var len = popupStack.length;
    if (!len) return null;
    if (!ind && ind !== 0) {
        ind = len-1;
    } else if (ind < 0) ind = len + ind - 1;
    if (ind < 0) return null;
    return popupStack[ind][prop];
}

function setPopupProp(prop, value)
{
    popupStack[popupStack.length-1][prop] = value;
}

// type: 'ok', 'cancel'
function getPopupButton(type)
{
    var len = popupStack.length;
    var id = type == 'ok' ? 'PopupOKButton' : 'PopupCancelButton';
    return !len ? null : document.getElementById(id + len);
}

function getPopupForm(formId)
{
    var iframe = getPopupProp('iframe');
    if (!iframe) return null;
    var d = iframe.contentDocument || iframe.contentWindow;
    if (d.document) d = d.document;
    return d.getElementById(formId);
}

function popupAttachEvents()
{
	var fb = fadeStack.getUpperFade();
	if (fb && fb.style.display != 'none' && typeof(fb.onclick) == 'function') return;
	if (!popupEventsAttached) {
		popupEventsAttached = true;
	    if (document.body.addEventListener){
	 	    document.body.addEventListener('mousedown', mouse_cancel_popup, false);
		} else if (document.body.attachEvent){
	  	    document.body.attachEvent('onmousedown', mouse_cancel_popup);
		}
	}
}

function popup_select_start(event)
{
    if (!event) event = window.event;
    var src = event.srcElement ? event.srcElement : event.target;
    if (!(src.tagName == "INPUT" &&
    (src.type == "text" || src.type == "file")
    || src.tagName == "TEXTAREA"
    || src.isContentEditable))
        return false;
}

function popup_context_menu(event)
{
    if (!event) event = window.event;
    return (event.ctrlKey && event.altKey);
}

function popup_key_press(event)
{
    if (!event) event = window.event;
    if (event.keyCode == 27) hide_popup();
}

function popup_menu_over(event)
{
    if (!event) event = window.event;
    e = event.srcElement ? event.srcElement : event.target;
    while (e && e.className.substr(0, 11) != 'popup_slink') e = e.parentElement;
    e.className = 'popup_slink2';
}

function popup_menu_out(event)
{
    if (!event) event = window.event;
    e = event.srcElement ? event.srcElement : event.target;
    while (e && e.className.substr(0, 11) != 'popup_slink') e = e.parentElement;
    e.className = 'popup_slink';
}

function frame_mouse_down(event)
{
    if (!event) event = window.event;
    event.cancelBubble = true;
}

function popup_exec_html_simple(s, title, button)
{
    createPopup();
    var a = getPopupProp('div');

    a.style.width = '500px';
    var src =
        "<table cellspacing='0' cellpadding='0' id='PopupFrameTable'>"+
        "<tr><td id='PopupFrameTableMainCell'>"+s+"</td></tr></table>";
    a.innerHTML = src;
    a.onselectstart = popup_select_start;
    a.oncontextmenu = popup_context_menu;
    a.onkeypress = popup_key_press;
    a.onmousedown = frame_mouse_down;

    var at = document.getElementById("PopupFrameTable");

    var w = at.offsetWidth;
    if (button && w < button.offsetWidth) w = button.offsetWidth;
    var h = at.offsetHeight;

    var l, t, pp;
    if (button) {
        pp = getControlPixelPos(button, 0, button.offsetHeight, w, h, 20);
	    l = pp[0];
	    t = pp[1];
	    pos = pp[2];
    } else {
        fadeStack.show();
        fadeStack.setZIndex(getPopupProp('zIndex') - 10);
        setPopupProp('fade', 1);
    	l = getScrollLeft()+Math.round((getClientWidth()-w)/2);
        t = getScrollTop()+Math.round((getClientHeight()-h)/2)-50;
        pos = '';
    }

    a.style.width = w+(quirksMode && is_msie() ? 18 : 0)+'px';
    a.style.height = h+(quirksMode && is_msie() ? 18 : 0)+'px';
    a.style.left = l+'px';
    a.style.top = t+'px';
    if (pos) a.style.position = pos;
    hideElements(a);
    a.style.visibility = "";
    a.focus();
    popupAttachEvents();
    popupFrameVisible = true;
}

function popup_exec_html(html, button, w, h, title, close_button)
{
    createPopup(1);

    var a = document.createElement('div');
    a.innerHTML = html;
    a.style.overflow = 'auto';
    a.style.backgroundColor = '#FFFFFF';
    popup_exec(a, button, w, h, title, close_button);
}

function popup_exec_url(url, button, w, h, reload, close_function, title, close_button)
{
    createPopup();
    var a = getPopupProp('iframe');

    if (a.src.replace('http://' + location.host, '') != url || reload) {
        if (close_function) {
            setPopupProp('closeFunc', close_function);
        }
        var src = "<html><head><style>"+
            "body { margin: 0px; padding: 8px; overflow: hidden; "+
            "background: #F4F4F4 } "+
            "body, td { font: 8pt Verdana } "+
            ".loading { position: absolute; left: 50%; top: 50%; width: 32px; height: 32px; "+
            "text-align: center; margin-left: -16x; margin-top: -16px; }"+
            "</style>"+
            "</head><body "+
            "onselectstart='parent.popup_select_start(event)' "+
            "oncontextmenu='return (event.ctrlKey && event.altKey)' "+
            "onkeypress='if (event.keyCode==27) parent.hide_popup()'>"+
            "<img class='loading' src='/core/images/working.gif'/></body></html>";
        var d = a.contentDocument ? a.contentDocument : a.contentWindow.document;
        d.open();
        d.write(src);
        d.close();
        if (is_opera()) a.src = '';
        a.src = url;
    }

    var l, t, pp;
    if (button) {
        pp = getControlPixelPos(button, 0, button.offsetHeight, w, h, 20);
	    l = pp[0];t = pp[1];
	    a.style.position = 'absolute';
    } else {
        if (useAbsPosition) {
            a.style.position = 'absolute';
        } else {
            a.style.position = 'fixed';
        }
    }

    a.onload = function(event) {
    	var d = this.contentDocument ? this.contentDocument : this.contentWindow.document;
    	focusFirstControl(d.body);
	}
    popup_exec(a, button, w, h, title, close_button);
}

function popup_exec(bodyEl, button, w, h, title, close_button)
{
    if (title != null) {
        var mainDiv = document.createElement('DIV');
        mainDiv.className = 'PopupBody';
        var contentsDiv = document.createElement('DIV');
        contentsDiv.className = 'contents';
        var divInnerContents = document.createElement('DIV');

        if (getClientWidth() > 750) {
        	var maxW = getClientWidth()-200;
        	var maxH = getClientHeight()-120;
    	} else {
    		// small screen device
    		var maxW = getClientWidth()-40;
        	var maxH = getClientHeight()-100;
    	}
        if (w && w > maxW) w = maxW;
        if (h && h > maxH) h = maxH;

        if (title != '') {
            var headerDiv = document.createElement('DIV');
            headerDiv.className = 'PopupHeader';
            var titleDiv = document.createElement('DIV');
            titleDiv.className = 'PopupTitle PopupTitleBorder';
            var closeDiv = document.createElement('DIV');

            closeDiv.onmousedown = hide_popup;
            closeDiv.id = 'PopupCloseDiv' + popupStack.length;
            // Fix for strange IE error
            closeDiv.style.width = '20px';
            closeDiv.style.height = '20px';

            titleDiv.appendChild(document.createTextNode(title));
            setPopupProp('title', titleDiv);
            var buttonsDiv = null;
            if (close_button !== false) {
                buttonsDiv = document.createElement('DIV');
                buttonsDiv.className = 'PopupButtons';
                buttonsDiv.id = 'PopupButtonsDiv' + popupStack.length;
            }
            headerDiv.appendChild(titleDiv);
            headerDiv.appendChild(closeDiv);

            contentsDiv.appendChild(headerDiv);
            contentsDiv.appendChild(divInnerContents);
            if (buttonsDiv) contentsDiv.appendChild(buttonsDiv);
        } else {
            contentsDiv.appendChild(divInnerContents);
        }
        if (headerDiv)
            mainDiv.headerDiv = headerDiv;
        mainDiv.contentsDiv = contentsDiv;
        mainDiv.appendChild(contentsDiv);
        mainDiv.body = bodyEl;

        bodyEl.style.border      = '0px';
        bodyEl.style.position    = 'static';
        if (w) bodyEl.style.width  = w + 'px';
        if (h) bodyEl.style.height = h + 'px';
        bodyEl.style.visibility  = 'visible';

        divInnerContents.appendChild(bodyEl);

        if (buttonsDiv) {
            var b = document.createElement('BUTTON');
            b.id = 'PopupOKButton' + popupStack.length;
            b.innerHTML = 'OK';
            b.onclick = hide_popup;
            b.className = 'Button btnOk';
            b.style.display = 'none';
            buttonsDiv.appendChild(b);

            b = document.createElement('BUTTON');
            b.id = 'PopupCancelButton' + popupStack.length;
            b.innerHTML = close_button ? close_button : 'Close';
            b.onclick = hide_popup;
            b.className = 'Button btnCancel';
            buttonsDiv.appendChild(b);
        }

        mainDiv.style.position = useAbsPosition ? 'absolute' : 'fixed';
        mainDiv.style.visibility = 'hidden';
        mainDiv.style.display = '';
        mainDiv.style.zIndex = getPopupProp('zIndex');

        // append shadows
        var frDiv = document.createElement('DIV');
        frDiv.className = 'tl';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'tc';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'tr';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'ml';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'mr';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'bl';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'bc';
        mainDiv.appendChild(frDiv);
        frDiv = document.createElement('DIV');
        frDiv.className = 'br';
        mainDiv.appendChild(frDiv);

        document.body.appendChild(mainDiv);
        disableScroll();

        correctPopupSizesForIE(mainDiv);

        // when scroll is hidden client width is changed
        // we need recalculate position
        if (useAbsPosition) {
    	    l = getScrollLeft()+Math.round((getClientWidth()-bodyEl.offsetWidth)/2);
            t = getScrollTop()+Math.round((getClientHeight()-bodyEl.offsetHeight)/2);
        } else {
            l = Math.round((getClientWidth()-bodyEl.offsetWidth)/2);
            t = Math.round((getClientHeight()-bodyEl.offsetHeight)/2);
        }
        // this offsets needed to set dialog content to center
        mainDiv.topOffset = -2; // upper border
        mainDiv.leftOffset = -16; // left border and shadow
        var buttonsOffset = 0;
        if (buttonsDiv) buttonsOffset = buttonsDiv.offsetHeight;
        if (headerDiv) {
            mainDiv.topOffset -= (headerDiv.offsetHeight + buttonsOffset)/2;
        }
        // setup dialog position
        mainDiv.style.left = l+mainDiv.leftOffset+'px';
        mainDiv.style.top = t+mainDiv.topOffset+'px';
        mainDiv.onmousedown = frame_mouse_down;
        setPopupProp('dialog', mainDiv);
        enableDialogDragging(mainDiv);
        if (closeDiv)
            closeDiv.className = 'PopupCloseButton';
        mainDiv.style.visibility = 'visible';
    } else {
        if (!button) {
            if (useAbsPosition) {
                l = getScrollLeft()+Math.round((getClientWidth()-w)/2);
                t = getScrollTop()+Math.round((getClientHeight()-h)/2);
            } else {
                l = Math.round((getClientWidth()-w)/2);
                t = Math.round((getClientHeight()-h)/2);
            }
        } else {
            pp = getControlPixelPos(button, 0, button.offsetHeight, w, h, 20);
            l = pp[0];
            t = pp[1];
        }
        bodyEl.style.width = w+'px';
        bodyEl.style.height = h+'px';
        bodyEl.style.left = l+'px';
        bodyEl.style.top = t+'px';
        disableScroll();
    }
    if (!button) {
        fadeStack.show();
        fadeStack.setZIndex(getPopupProp('zIndex') - 10);
        setPopupProp('fade', 1);
    }

    bodyEl.style.visibility = 'visible';
    focusFirstControl(bodyEl);
    popupAttachEvents();
    popupFrameVisible = true;
    if (button) {
        hideElements(bodyEl, bodyEl);
    } else {
        hideElements(null, bodyEl);
    }
}

function popup_show_buttons(show)
{
    var bDiv = document.getElementById('PopupButtonsDiv' + popupStack.length);
    if (bDiv)
        bDiv.style.display = show ? '' : 'none';
}

function popup_iframe_move(w, h)
{
    var a = getPopupProp('iframe');
    var l = (useAbsPosition ? getScrollLeft() : 0) + Math.round((getClientWidth()-w)/2);
    var t = (useAbsPosition ? getScrollTop() : 0) + Math.round((getClientHeight()-h)/2);
    a.style.width = w+'px';
    a.style.height = h+'px';
    var d = getPopupProp('dialog');
    if (d)  { // if frame with shadows applied
        d.style.left = l+d.leftOffset+'px';
        d.style.top = t+d.topOffset+'px';
        if (is_msie() && d.headerDiv) {
            d.headerDiv.style.width = 'auto';
            d.headerDiv.style.width = d.contentsDiv.offsetWidth;
        }
    } else { // for old style (without shadows, only iframe)
        a.style.left = l+'px';
        a.style.top = t+'px';
    }
}

function mouse_cancel_popup()
{
	if (popupFrameVisible) {
		if (popupCloseAction == 'alert') {
			alert(popupCloseMsg);
		} else if (popupCloseAction == 'confirm') {
			if (confirm(popupCloseMsg)) hide_popup();
		} else {
			hide_popup();
		}
	}
}

function hide_popup()
{
    if (popupFrameVisible) {
        var curPopup = popupStack.pop();
        var isLast = popupStack.length == 0;
        if (isLast) {
            popupFrameVisible = false;
        }
        var a = curPopup['div'];
        if (a) {
            if (isLast) {
                a.style.visibility = "hidden";
                a.style.pixelLeft = 0;
                a.style.pixelTop = 0;
                a.style.pixelWidth = 0;
                a.style.pixelHeight = 0;
            } else {
                a.parentNode.removeChild(a);
            }
        }
        a = curPopup['iframe'];
        if (a) {
            var closeF = curPopup['closeFunc'];
	        if (closeF) {
	            if (typeof(closeF) == 'function') {
	                closeF(a);
	            } else {
	               eval(closeF + '(a)');
	            }
	        }

	        if (isLast) {
    	        a.style.visibility = "hidden";
    	        a.style.pixelLeft = 0;
    	        a.style.pixelTop = 0;
    	        a.style.pixelWidth = 0;
    	        a.style.pixelHeight = 0;
    	        a.src = '';
	        } else {
	            a.parentNode.removeChild(a);
	        }
        }
        if (curPopup['fade']) {
            fadeStack.hide();
        }
        if (isLast) {
            showElements();
        }
        a = curPopup['dialog'];
        if (a) {
            a.parentNode.removeChild(a);
            popupIFrame = null;
        }
    }
    if (!popupFrameVisible || isLast) {
        enableScroll();
        if (typeof(paletteInterval) != 'undefined' && paletteInterval) {
            clearInterval(paletteInterval);
            paletteInterval = null;
        }
    }
}

function render_popup_iframe(zIndex)
{
    var e = document.createElement('iframe');
    e.tabIndex = -1;
    e.style.zIndex = zIndex || 8000;
    e.style.visibility = 'hidden';
    e.style.width = '0px';
    e.style.height = '0px';
    e.style.position = 'absolute';
    e.style.border = 'solid 1px #808080';
    e.style.background = '#F4F4F4';
    e.src = '/core/template/empty.html';
    e.frameBorder = 0;
    e.marginWidth = 0;
    e.marginHeight = 0;
    document.body.appendChild(e);

    var e1 = document.createElement('div');
    e1.style.zIndex = zIndex || 8000;
    e1.style.visibility = 'hidden';
    e1.style.width = '0px';
    e1.style.height = '0px';
    e1.style.position = 'absolute';
    e1.style.border = 'solid 1px #808080';
    e1.style.background = '#F4F4F4';
    e1.className = 'popup_div';
    document.body.appendChild(e1);
    return {div: e1, iframe: e};
}

function correctPopupSizesForIE(bodyId, fromTimeout)
{
    if (!is_msie() || (is_msie() >= 8 && !quirksMode)) return;
    if (typeof(bodyId) != 'string') {
        var body = bodyId;
        if (!body.id) {
            body.id = "popupBodyId_" + Math.round(Math.random()*100000);
        }
        bodyId = body.id;
    } else {
        var body = document.getElementById(bodyId);
        if (!body) return;
    }
    if (!fromTimeout && body._ieOnCorrect) return;
    body._ieOnCorrect = true;
    var w = body.offsetWidth;
    var h = body.offsetHeight;
    if (w > 0) {
        var divs = body.getElementsByTagName('div');
        for(var i = 0; i < divs.length; i++) {
            switch (divs[i].className) {
                case 'tc':
                    divs[i].style.width = (w - 32) + 'px';
                    break;
                case 'ml':
                case 'mr':
                    divs[i].style.height = (h - 67) + 'px';
                    break;
                case 'bc':
                    divs[i].style.width = (w - 60) + 'px';
                    break;
            }
        }
    }
    setTimeout('correctPopupSizesForIE("' + bodyId + '", 1)', 500);
}

function FadeStack()
{
    this.stack = Array();
    window.onresize = function() {
        var width = getScrollWidth();
        var height = getScrollHeight();
        if (height < getClientHeight()) height = getClientHeight();
        for(var i = 0; i < fadeStack.stack.length; i++) {
            fadeStack.stack[i].style.width = width+'px';
            fadeStack.stack[i].style.height = height+'px';
        }
    }
}

FadeStack.prototype.show = function(onclick) {
    disableScroll();
    var im = document.createElement('DIV');
    var compStyle = __getComputedStyle(document.body, 'backgroundColor');
    var colorObj = new RGBColor(compStyle);
    if (colorObj.r > 128 || colorObj.g > 128 || colorObj.b > 128) {
        im.style.backgroundColor = '#FFFFFF';
    } else {
        im.style.backgroundColor = '#000000';
        setBlackShadows();
    }
    im.style.opacity = 0.66;
    if (is_msie() && (is_msie() < 9 || quirksMode)) {
        im.style.filter = 'alpha(opacity=66)';
    }
    im.style.display = 'none';
    im.style.position = 'absolute';
    im.style.left = im.style.top = '0px';
    var zIndex = this.stack.length > 0 ? parseInt(this.stack[this.stack.length-1].style.zIndex) + 1: 7500;
    im.style.zIndex = zIndex;
    im.id = 'popupFadeBack' + this.stack.length;
    document.body.appendChild(im);
    im.onclick = typeof(onclick) == 'function'?
            onclick : function() {mouse_cancel_popup();}

    im.style.width = getScrollWidth()+'px';
    var h = getScrollHeight();
    if (h < getClientHeight()) h = getClientHeight();
    im.style.height = h+'px';
    im.style.display = '';
    this.stack.push(im);
    return true;
}

FadeStack.prototype.hide = function() {
    var im = this.stack.pop();
    if (!im) return false;
    im.style.display = 'none';
    im.parentNode.removeChild(im);
    enableScroll();
}

FadeStack.prototype.getUpperFade = function() {
    return this.stack.length > 0 ? this.stack[this.stack.length-1]: false;
}

FadeStack.prototype.getZIndex = function() {
    var fade = this.stack.length > 0 ? this.stack[this.stack.length-1]: '';
    return fade ? parseInt(fade.style.zIndex) + 1 : 7501;
}

FadeStack.prototype.setZIndex = function(value) {
    if (!this.stack.length) return;
    this.stack[this.stack.length-1].style.zIndex = value;
}

FadeStack.prototype.isFadeDisplayed = function() {
    return this.stack.length > 0;
}

fadeStack = new FadeStack();

//addWindowOnLoad(render_popup_iframe);
var calendarCtl    = null,
    calendarDays   = ['Su','Mo','Tu','We','Th','Fr','Sa'],
    calendarMonths = ['January','February','March','April','May','June','July','August','September','October','November','December'],
    calendarParams = new Array(),
    calendarFormat = 'm/d/y';

function calendarDaysInMonth(y, m)
{
    var mdays  = [31,28,31,30,31,30,31,31,30,31,30,31];
    if ((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) mdays[1] = 29;
    return mdays[m - 1];
}

function calendarDateToStr(dt)
{
    var m = (dt[1] > 9 ? '' : '0') + dt[1];
    var d = (dt[2] > 9 ? '' : '0') + dt[2];
    var y = dt[0];
    return calendarFormat.replace('m', m).replace('d', d).replace('y', y);
}

function calendarStrToDate(s, e)
{
    var re = /^([0-9]{1,2})[\-\/]{1}([0-9]{1,2})[\-\/]{1}([0-9]{1,4})$/;
    var mt  = s.match(re);
    if (mt) {
        var y = parseInt(mt[3], 10);
        y += (y < 100) ? (y <= 70 ? 2000 : 1900) : 0;
        var m = parseInt(mt[1], 10);
        m = (m < 1) ? 1 : (m > 12 ? 12 : m);
        var mdcnt = calendarDaysInMonth(y, m),
            d = parseInt(mt[2], 10);
        d = (d < 1) ? 1 : (d > mdcnt ? mdcnt : d);
        return [y, m, d];
    }
    if (e) {
        return !(/[^\s+]/.test(s));
    }
    var dt = new Date();
    return [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
}

function popup_calendar_execute(btn, ctl, format)
{
    calendarFormat = format || 'm/d/y';
    calendarCtl = ctl;
    calendarCtl.value = calendarDateToStr(calendarStrToDate(calendarCtl.value));
    popup_exec_html_simple(popup_calendar_table(), 'Calendar', btn);
}

function popup_insert_date(ctl, code)
{
    hide_popup();
    ctl.value = code;
}

function popup_draw_calendar(dt)
{
    document.getElementById('PopupFrameTableMainCell').innerHTML = popup_calendar_table(dt);
}

function popup_calendar_table(dt)
{
    if (!dt) dt = calendarStrToDate(calendarCtl.value);
    var y = dt[0], m = dt[1], d = dt[2];
    if (m > calendarMonths.length) { m = 1; y++; }
    if (m < 1) { m = calendarMonths.length; y--; }
    var mdcnt  = calendarDaysInMonth(y, m);
    if (d > mdcnt) d = 1;
    if (d < 1) d = mdcnt;
    var out = '';
    out += '<div style="padding-bottom:3px"><div class="popup_hdr">';
    out += '<table cellpadding="0" cellspacing="0"><tr valign="middle">';
    out += '<td><a href="javascript:popup_draw_calendar([' + y + ',' + (m - 1) + ',' + d + '])"><img src="/core/images/calendar/to_left.gif" border="0"/></a></td>';
    out += '<td width="80px" style="border:1px solid #808080"><b>' + calendarMonths[m - 1] + '</b></td>';
    out += '<td><a href="javascript:popup_draw_calendar([' + y + ',' + (m + 1) + ',' + d + '])"><img src="/core/images/calendar/to_right.gif" border="0"/></a></td>';
    out += '<td>&#xA0;&#xA0;&#xA0;</td>';
    out += '<td><a href="javascript:popup_draw_calendar([' + (y - 1) + ',' + m + ',' + d + '])"><img src="/core/images/calendar/to_left.gif" border="0"/></a></td>';
    out += '<td width="40px" style="border:1px solid #808080"><b>' + y + '</b></td>';
    out += '<td><a href="javascript:popup_draw_calendar([' + (y + 1) + ',' + m + ',' + d + '])"><img src="/core/images/calendar/to_right.gif" border="0"/></a></td>';
    out += '</tr></table></div></div>';

    out += '<table cellpadding=0 cellspacing=0 border=1 bordercolor=#808080 style="border-collapse:collapse;background:white">';
    out += '<tr>';
    for (var i = 0; i < calendarDays.length; i++) {
        out += '<td class="popup_cell" style="font-weight:bold;font-size:8pt;background-color:#EFBD99">' + calendarDays[i] + '</td>';
    }
    out += '</tr><tr>';
    var fdom = new Date(y, m - 1, 1).getDay(),
        rows = 6,
        cell = style = '';
    for (var i = 0; i < rows * 7; i++) {
        cell = (i < fdom || i - fdom + 1 > mdcnt) ? '' : (i - fdom + 1);
        style  = (i % 7 == 0) ? 'background-color:#E8E8E8;' : '';
        style += (cell == d)  ? 'border-width:3px;border-color:#A94C1C;' : '';
        out += '<td class="popup_cell"' + (style ? ' style="' + style + '"' : '') + '>';
        if (cell) {
            out += '<div class="popup_slink" onclick="popup_insert_date(calendarCtl, \'' + calendarDateToStr([y, m, cell]) +'\')" ';
            out += 'onmouseover="popup_menu_over(event)" onmouseout="popup_menu_out(event)">' + cell + '</div>';
        } else {
            out += '&#xA0;';
        }
        out += '</td>';
        if (i % 7 == 6) out += '</tr>';
        if (i % 7 == 6 && i < rows * 7 - 1) out += '<tr>';
    }
    out += '</table>';
    return out;
}

function calendarDraw(dt, days, frameId, pageUrl, applyUrl)
{
    this._format = function(n)
    {
        return (n > 9 ? '' : '0') + n.toString();
    }
    this._check = function(dt)
    {
        if (dt[1] > calendarMonths.length) { dt[1] = 1; dt[0]++; }
        if (dt[1] < 1) { dt[1] = calendarMonths.length; dt[0]--; }
    }
    this._check(dt);
    var y = dt[0], m = dt[1], d = dt[2],
        prev = [y, m - 1, d],
        next = [y, m + 1, d];
    this._check(prev);
    this._check(next);
    var currNum = y.toString() + this._format(m),
        currStr = calendarMonths[m - 1] + '&#xA0;&#xA0;' + y,
        prevNum = prev[0].toString() + this._format(prev[1]),
        prevStr = calendarMonths[prev[1] - 1] + '&#xA0;&#xA0;' + prev[0],
        nextNum = next[0].toString() + this._format(next[1]),
        nextStr = calendarMonths[next[1] - 1] + '&#xA0;&#xA0;' + next[0];
    var mdcnt  = calendarDaysInMonth(y, m),
        out = '';
    out += '<table cellpadding="0" cellspacing="0"><tr><td>';
    out += '<table cellpadding="3" cellspacing="0"><tr>';
    out += '<td style="cursor:pointer" title="' + prevStr + '" onclick="AjaxRequest(\'' + pageUrl + prevNum + '\')">';
    out += '<img src="/core/images/calendar/to_left.gif" border="0"/></td>';
    out += '<td><a href="' + applyUrl.replace(/dateNum/, currNum) + '"><b>' + currStr + '</b></a></td>';
    out += '<td style="cursor:pointer" title="' + nextStr + '" onclick="AjaxRequest(\'' + pageUrl + nextNum + '\')">';
    out += '<img src="/core/images/calendar/to_right.gif" border="0"/></td>';
    out += '</tr></table></td></tr><tr><td>';
    out += '<table cellpadding="0" cellspacing="0" style="border-collapse:collapse">';
    out += '<tr>';
    for (var i = 0; i < calendarDays.length; i++) {
        out += '<th class="framed">' + calendarDays[i] + '</th>';
    }
    out += '</tr><tr>';
    var dstr = '|' + days.join('|') + '|',
        fdom = new Date(y, m - 1, 1).getDay(),
        rows = Math.ceil((fdom + mdcnt) / 7),
        cell = style = '';
    for (var i = 0; i < rows * 7; i++) {
        cell = (i < fdom || i - fdom + 1 > mdcnt) ? '' : (i - fdom + 1);
        style  = (i % 7 == 0) ? 'background-color:#F0F0F0;' : '';
        style += (d && cell == d)  ? 'border-color:#000000;font-weight:bold;' : '';
        out += '<td class="framed" style="padding:2px 6px;' + (style ? style : '') + '">';
        if (cell) {
            if (-1 != dstr.indexOf('|' + cell + '|')) {
                out += '<a href="' + applyUrl.replace(/dateNum/, currNum + this._format(cell)) + '">' + cell + '</a>';
            } else {
                out += cell;
            }
        } else {
            out += '&#xA0;';
        }
        out += '</td>';
        if (i % 7 == 6) out += '</tr>';
        if (i % 7 == 6 && i < rows * 7 - 1) out += '<tr>';
    }
    out += '</table></td></tr></table>';
    document.getElementById('framebox_' + frameId).innerHTML = out;
}

function validateCalendarValue(value, allowEmpty)
{
	if (allowEmpty &&  value=='') return true;
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    if (value.match(RegExPattern))
        return true;
    else
        return false;
}

function parseCalendarValue(name)
{
	var date_control = document.getElementById(name);
	var date_value = document.getElementById(name).value;
	var today = new Date();
	var yesterday = new Date();
	yesterday.setDate(yesterday.getDate() - 1);
	var tomorrow = new Date();
	tomorrow.setDate(tomorrow.getDate() + 1);
	var prev_month = new Date();
    prev_month.setMonth(prev_month.getMonth() - 1);
    var next_month = new Date();
    next_month.setMonth(next_month.getMonth() + 1);
	var year_dd = document.getElementById(name+'_year');
    if (year_dd) {
        var start = date_control.getAttribute("data-year_start") ?
            date_control.getAttribute("data-year_start") : today.getFullYear();
        var stop = date_control.getAttribute("data-year_stop") ?
            date_control.getAttribute("data-year_stop") : today.getFullYear();
        if (date_value == 'notset') {
            var opt = document.createElement('OPTION');
            opt.setAttribute('value', 0);
            opt.appendChild(document.createTextNode('[Year]'));
            year_dd.appendChild(opt);
        }
        for (var y = start; y <= stop; y++) {
            var opt = document.createElement('OPTION');
            opt.setAttribute('value', y);
            opt.appendChild(document.createTextNode(y));
            year_dd.appendChild(opt);
        }
    }
    var month_dd = document.getElementById(name+'_month');
    var days_dd = document.getElementById(name+'_day');
    var default_date = date_value;
    if (date_value == 'today') {
            date_value = document.getElementById(name).value =
            ((today.getMonth()+1).toString().length == 1? 0 + (today.getMonth()+1).toString():(today.getMonth()+1)) + '/' +
            (today.getDate().toString().length == 1? 0+today.getDate().toString():today.getDate()) +
             '/' + today.getFullYear();
    } else if (date_value == 'yesterday') {
    	if (days_dd)
    	   date_value = document.getElementById(name).value =
            ((yesterday.getMonth()+1).toString().length == 1? 0 + (yesterday.getMonth()+1).toString():(yesterday.getMonth()+1)) + '/' +
            (yesterday.getDate().toString().length == 1? 0+yesterday.getDate().toString():yesterday.getDate()) +
             '/' + yesterday.getFullYear();
        else
            date_value = document.getElementById(name).value =
            ((prev_month.getMonth()+1).toString().length == 1? 0 + (prev_month.getMonth()+1).toString():(prev_month.getMonth()+1)) + '/' +
            (prev_month.getDate().toString().length == 1? 0+prev_month.getDate().toString():prev_month.getDate()) +
             '/' + prev_month.getFullYear();
    } else if (date_value == 'tomorrow') {
    	if (days_dd)
    	   date_value = document.getElementById(name).value =
            ((tomorrow.getMonth()+1).toString().length == 1? 0 + (tomorrow.getMonth()+1).toString():(tomorrow.getMonth()+1)) + '/' +
            (tomorrow.getDate().toString().length == 1? 0+tomorrow.getDate().toString():tomorrow.getDate()) +
             '/' + tomorrow.getFullYear();
        else
            date_value = document.getElementById(name).value =
            ((next_month.getMonth()+1).toString().length == 1? 0 + (next_month.getMonth()+1).toString():(next_month.getMonth()+1)) + '/' +
            (next_month.getDate().toString().length == 1? 0+next_month.getDate().toString():next_month.getDate()) +
             '/' + next_month.getFullYear();
    } else if (date_value == 'notset') {
    	date_value = document.getElementById(name).value = '';
    }
    var date_parts = date_value.split('/');
    if (year_dd) year_dd.value = date_parts[2] ? date_parts[2] : 0;
    if (month_dd) month_dd.value = date_parts[0] ? date_parts[0] : 0;
    setCalendarDays(name, default_date);
    if (days_dd) days_dd.value = date_parts[1] ? date_parts[1] : 0;
    if (date_value != 'today' && date_value != 'notset')
        document.getElementById(name).value = date_value;
}

function setCalendarValue(name)
{
	var days_dd = document.getElementById(name+'_day');
    var month_dd = document.getElementById(name+'_month');
    var year_dd = document.getElementById(name+'_year');
    if (document.getElementById(name).type == 'hidden') //in dropdown mode only
	    if (month_dd.value != 0 && (days_dd == null || days_dd.value != 0) && year_dd.value != 0)
		   document.getElementById(name).value = month_dd.value + '/' + (days_dd?days_dd.value:'01') + '/' + year_dd.value;
		else
		   document.getElementById(name).value = '';
}

function setCalendarDays(name, default_value)
{
	var days_dd = document.getElementById(name+'_day');
	if (days_dd) {
		var month_dd = document.getElementById(name+'_month');
		var year_dd = document.getElementById(name+'_year');
		var old_date = days_dd.value;
	    days_dd.options.length = 0;
		var date = new Date(year_dd.value, month_dd.value -1, 1);
		var d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
		var lastday = d.getDate();
		var curday;
        if (old_date < lastday) {
            curday = old_date;
        } else {
            curday = lastday.toString().length == 1 ? 0+lastday.toString() : lastday;
        }
		if (default_value == 'notset') {
			var opt = document.createElement('OPTION');
            opt.value = 0;
            opt.appendChild(document.createTextNode('[Day]'));
            opt.selected = curday == opt.value;
            days_dd.appendChild(opt);
		}
		for (i = 1; i <= lastday; i++) {
			var opt = document.createElement('OPTION');
			opt.value = i.toString().length == 1 ? 0+i.toString() : i;
			opt.appendChild(document.createTextNode(i));
			opt.selected = curday == opt.value;
			days_dd.appendChild(opt);
		}
	}
	setCalendarValue(name);
}
function checkAll(f, act)
{
    var frameId = f.getAttribute('attr_frame_id');
    var eId = 'active' == act ? 'check_active_id' : 'check_delete_id';
    if (frameId > 0)  {
        var e = getFrameElementById(frameId, eId);
    } else {
        var e = document.getElementById(eId);
    }
    var checked = 'Click to check all' == e.title ? 0 : 1;
    checked = !checked;
    var els = document.getElementsByName(act + 'IdArr[]');
    for (var i = 0; i < els.length; i++) {
        if (!els[i].disabled) {
            els[i].checked = checked;
        }
    }
    if (checked) {
        e.title = 'Click to uncheck all';
    } else {
        e.title = 'Click to check all';
    }
}

function applyClick(f, act)
{
    if ('apply' == act || 'delete' == act) {
        var checkedItems = 0;
        var els = document.getElementsByName('deleteIdArr[]');
        for (i = 0; i < els.length; i++) {
            if (els[i].checked) {
                checkedItems++;
            }
        }
        if (checkedItems) {
            if (checkedItems == 1) {
                var ok = confirm('You are about to delete ' + checkedItems + ' item. Proceed?');
            } else {
                var ok = confirm('You are about to delete ' + checkedItems + ' items. Proceed?');
            }
            if (!ok) {
                return false;
            }
        }
    }
    if ('function' == typeof submit_click) {
        submit_click();
    }
    f.submitAction.value = act;
    f.submit();
    f.submitAction.value = '';
}

function applyEnter(event, f, submitName)
{
    event = event || window.event;
    if (event.keyCode != 13) return;
    var inputs = f.getElementsByTagName('input');
    for(var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'submit' && inputs[i].name == submitName) {
            inputs[i].click();
            return false;
        }
    }
}

function listApply(form, action, prompt)
{
    if (!action || action == 'apply' || prompt) {
        var checkedItems = deletedItems = 0;
        for (i = 0; i < form.elements.length; i++) {
            if (form.elements[i].tagName == 'INPUT'
            && form.elements[i].type == 'checkbox'
            && form.elements[i].checked) {
                if (form.elements[i].name.substr(0, 6) == "delete") {
                    deletedItems++;
                }
                checkedItems++;
            }
        }
        if (!checkedItems) {
            alert('Please select at least one item.');
            return false;
        }
        if (deletedItems != 0) {
            var ok = confirm('You are about to delete ' + deletedItems + ' item' +
                (deletedItems == 1 ? '' : 's') + '. Proceed?');
            if (!ok) {
                return false;
            }
        } else if (checkedItems != 0 && prompt) {
            var ok = confirm(prompt.replace('%n', checkedItems));
            if (!ok) {
                return false;
            }
        }
    }
    if (action && form.submitAction) {
        form.submitAction.value = action;
    }
    form.submit();
    return true;
}

var listCheckFlag_delete = true;
var listCheckFlag_active = false;
var selCounter = new Array();

function listCheckAll(form, action)
{
    var flag = eval('listCheckFlag_' + action);
    eval('listCheckFlag_' + action + ' = !flag');
    selCounter[action] = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name.substr(0, action.length) == action) {
            form.elements[i].checked = flag;
            if (flag) selCounter[action]++;
        }
    }
    refreshSelCounter(form, action, false);
}

function modifySelCounter(form, action, ctl)
{
    if (!selCounter[action]) selCounter[action] = 0;
    var cur = parseInt(ctl.getAttribute('data-status'));
    if (cur && !ctl.checked) {
        selCounter[action]--;
    } else if (!cur && ctl.checked) {
        selCounter[action]++;
    }
    ctl.setAttribute('data-status', ctl.checked ? 1 : 0);
    refreshSelCounter(form, action, false);
}

function refreshSelCounter(form, action, recalc)
{
    var e = document.getElementById('sel_counter_' + action);
    if (!e) return;
    var c;
    if (recalc) {
        c = 0;
        var els = form.elements;
        for (i = 0; i < els.length; i++) {
            var el = form.elements[i];
            if (el.name.substr(0, action.length) == action && el.checked) {
                c++;
            }
        }
        selCounter[action] = c;
    } else {
        c = selCounter[action];
    }
    e.innerHTML =
        (c == 0 ? 'No' : c.toString()) + ' ' + (c == 1 ? 'item' : 'items') + ' selected.';
}

function treeExpandRow(row)
{
    while (row && row.tagName != 'TR') row = row.parentNode;
	var exp = 1-parseInt(row.getAttribute('data-expanded'));
    row.setAttribute('data-expanded', exp);
    var img = document.getElementById(row.id + '_img');
    if (img) {
        if (img.src.indexOf('bottom') != -1) {
            img.src = exp ? '/core/images/tree/minusbottom.gif' : '/core/images/tree/plusbottom.gif';
        } else {
            img.src = exp ? '/core/images/tree/minus.gif' : '/core/images/tree/plus.gif';
        }
    }
    st = document.getElementById(row.id + '_st');
    if (st) st.value = exp;
    if (row.style.display == 'none') return;
    var level1 = row.getAttribute('data-level');
    var rexp = new Array();
    rexp[level1] = 1;
    while (1) {
    	row = row.nextSibling;
    	if (!row) break;
    	if (row.tagName != 'TR' || row.getAttribute('data-level') == ''
    		|| row.getAttribute('data-level') == null) continue;
    	var level2 = parseInt(row.getAttribute('data-level'));
    	if (level2 <= level1) break;
        var exp1;
        if (!exp) exp1 = 0;
        else {
            rexp[level2] = parseInt(row.getAttribute('data-expanded'));
            exp1 = rexp[level2-1];
        }
        row.style.display = exp1 ? '' : 'none';
    }
}

function treeExpandRows(rows)
{
    for (var i=0; i<rows.length; i++) {
        treeExpandRow(rows[i]);
    }
}

var movedRow = null, moveTarget = null, movedRowIndex = 0,  mPos = '', oldNewRG = null, movedRowCC = 1;
function selMovedRow(row, sel)
{
    rows = row.parentNode.parentNode.rows;
    rowIndex = row.rowIndex;
    while (rows[rowIndex].getAttribute('onmouseover') != '' && rows[rowIndex].getAttribute('cc') != '' && parseInt(rows[rowIndex].getAttribute('cc')) == 0){
        rowIndex--;
    }
    movedRowCC = 1;
    if (rows[rowIndex].getAttribute('cc')){
        movedRowCC = parseInt(rows[rowIndex].getAttribute('cc'));
    }
    for(var j=rowIndex; j<rowIndex+movedRowCC; j++){
        rows[j].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        for (var i = 0; i < row.cells.length; i++) {
            rows[j].cells[i].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        }
    }
}

function startMoving(event)
{
	if (!event) event = window.event;
    movedRow = event.target ? event.target : event.srcElement;
    moveTarget = null;
    while (movedRow && movedRow.tagName != 'TR') movedRow = movedRow.parentNode;
    if (!movedRow) return;
    oldNewRG = null;
    movedRowIndex = movedRow.rowIndex;
    selMovedRow(movedRow, 1);
    document.body.style.cursor = 'move';
    if (is_msie()) {
        document.body.attachEvent("onmouseup", endMoving);
        document.body.attachEvent("onselectstart", movingSelectStart);
    } else {
        addEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function moveRow(event)
{
    if (!movedRow) {
        return;
    }
	if (!event) event = window.event;
	if (mPos == event.clientX + ' ' + event.clientY) {
	    return;
	}
	mPos = event.clientX + ' ' + event.clientY;

    var newRow = event.target ? event.target : event.srcElement;
    while (newRow && newRow.tagName != 'TR') newRow = newRow.parentNode;
    if (!newRow) {
        return;
    }
    if ('prevPageRow' == newRow.id) {
        if ('function' == typeof moveToPrevPage) {
            moveToPrevPage();
        }
        return;
    }
    if ('nextPageRow' == newRow.id) {
        if ('function' == typeof moveToNextPage) {
            moveToNextPage();
        }
        return;
    }
    if (movedRow.rowIndex == newRow.rowIndex){
        oldNewRG = null;
        return;
    }
    moveTarget = newRow;

    var rows = movedRow.parentNode.parentNode.rows;
    // RG - first rowgroup item
    var newRG = newRow.rowIndex;
    while (rows[newRG].getAttribute('onmouseover') != '' && rows[newRG].getAttribute('cc') != ''
    && parseInt(rows[newRG].getAttribute('cc')) == 0) {
        newRG--;
    }
    var movedRG = movedRow.rowIndex;
    while (rows[movedRG].getAttribute('onmouseover') != '' && rows[movedRG].getAttribute('cc') != ''
    && parseInt(rows[movedRG].getAttribute('cc')) == 0) {
        movedRG--;
    }
    if (movedRG == newRG) {
        oldNewRG = null;
        return;
    }
    if (rows[newRG] == oldNewRG || rows[newRG].getAttribute('onmouseover') == null) {
        return;
    }
    oldNewRG = rows[newRG];

    var minRow = Math.min(movedRG, newRG);
    var maxRow = Math.max(movedRG, newRG);
    var maxRowCC = 1;
    if (rows[maxRow].getAttribute('cc')) {
        var maxRowCC = parseInt(rows[maxRow].getAttribute('cc'));
    }
    var first_node = rows[minRow];
    for (j = 0; j < maxRowCC; j++) {
        if (is_msie() && is_msie() < 7) {
            var move_id = rows[maxRow+j].id;
            var statuses = getCheckBoxStatuses(rows[maxRow+j]);
        }
        movedRow.parentNode.insertBefore(rows[maxRow+j], first_node);
        if (is_msie() && is_msie() < 7) {
            setCheckBoxStatuses(document.getElementById(move_id), statuses);
        }
    }
    return;
}

function endMoving(event)
{
    if (!movedRow) return;
	if (!event) event = window.event;
    var table = movedRow.parentNode;
    while (null != table && table.nodeName != 'TABLE') {
        table = table.parentNode;
    }
    document.body.style.cursor = 'auto';
    if (typeof(rowMoved) == "function" && moveTarget
    && moveTarget != movedRow && movedRow.rowIndex != movedRowIndex) {
    	rowMoved(movedRow, moveTarget);
    }
    selMovedRow(movedRow, 0);
    movedRow = null;
    moveTarget = null;
    if (is_msie()) {
        document.body.detachEvent("onmouseup", endMoving);
        document.body.detachEvent("onselectstart", movingSelectStart);
    } else {
        removeEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function getCheckBoxStatuses(Element)
{
    var res = new Array();
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox') {
            res[els[i].name] = els[i].checked;
        }
    }
    return res;
}

function setCheckBoxStatuses(Element, statuses)
{
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox' && statuses[els[i].name] != undefined) {
            els[i].checked = statuses[els[i].name];
        }
    }
}

function movingSelectStart()
{
	return false;
}

var tooltipCtl = null;
var curTipId = '';
function tooltip(ctl, tip_id, event, width, color)
{
    var tw = width ? (width == 'auto' ? 'auto' : width + 'px') : '200px';
    if (!tooltipCtl) {
        tooltipCtl = document.createElement('div');
        tooltipCtl.className = 'tooltip';
        if (color) {
        	tooltipCtl.style.backgroundColor = color;
    	}
        tooltipCtl.style.visibility = 'hidden';
    	tooltipCtl.style.position = 'absolute';
        tooltipCtl.style.zIndex = 10000;
        tooltipCtl.onmouseout = tooltipCtl.onclick = function()
	    {
	        tooltipCtl.style.visibility = 'hidden';
	        showElements();
	        curTipId = '';
	    };
        document.body.appendChild(tooltipCtl);
    }

    if (tip_id && tooltipCtl.style.width != tw) {
        tooltipCtl.style.width = tw;
    }
    if (!tip_id) {
        if (event.clientX + getScrollLeft() > parseInt(tooltipCtl.style.left) &&
            event.clientX + getScrollLeft() < parseInt(tooltipCtl.style.left) + tooltipCtl.clientWidth &&
            event.clientY + getScrollTop() > parseInt(tooltipCtl.style.top) &&
            event.clientY + getScrollTop() < parseInt(tooltipCtl.style.top) + tooltipCtl.clientHeight)
        return;
        tooltipCtl.style.visibility = 'hidden';
        showElements();
        curTipId = '';
    } else {
        var t = document.getElementById(tip_id);
        if (t && t.innerHTML) {
            tooltipCtl.style.visibility = 'visible';
            if (curTipId != tip_id) {
                tooltipCtl.innerHTML = t.innerHTML;
                curTipId = tip_id;
            }
            var left = event.clientX + 20 + getScrollLeft(),
                top = event.clientY + 20 + getScrollTop();
            left = Math.max(Math.min(left, getClientWidth() + getScrollLeft() -
                tooltipCtl.offsetWidth), 0);

            top = Math.max(Math.min(top, getClientHeight() + getScrollTop() -
                tooltipCtl.offsetHeight), 0);
            tooltipCtl.style.left = left + 'px';
            tooltipCtl.style.top = top + 'px';
            hideElements(tooltipCtl);
        }
    }
}

var balloonContainers = new Object();
function showBalloon(id, ctl, direction, container, xofs, yofs)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = '';
        var container = balloonContainers[id];
        container.style.display = '';
        return;
    }
    var ext = is_msie() && is_msie() < 7 ? '.gif' : '.png';
    var bw = container.offsetWidth+28, bh = container.offsetHeight+28, bx, by, x, y;
    switch (direction) {
        case 'lt':ox = 5;oy = 5;break;
        case 'lb':ox = 5;oy = ctl.offsetHeight-5;break;
        case 'rt':ox = ctl.offsetWidth-5;oy = 5;break;
        case 'rb':ox = ctl.offsetWidth-5;oy = ctl.offsetHeight-5;break;
    }
    ox += xofs ? xofs : 0;
    oy += yofs ? yofs : 0;
    var a = getControlPixelPos(ctl, ox, oy, 0, 0), x = a[0], y = a[1];
    switch (direction) {
        case 'lt':bx = x-bw-36;by = y-bh-17;break;
        case 'lb':bx = x-bw-34;by = y+17;break;
        case 'rt':bx = x+37;by = y-bh-17;break;
        case 'rb':bx = x+36;by = y+17;break;
    }
    var parent = document.createElement('DIV');
    parent.id = 'balloon_'+id;
    parent.style.position = 'absolute';
    parent.style.left = parent.style.top = parent.style.width = parent.style.height = '0px';
    document.body.appendChild(parent);
    var back = document.createElement('DIV');
    back.style.position = 'absolute';back.style.left = bx+6+'px';back.style.top = by+6+'px';
    back.style.width = bw-12+'px';back.style.height = bh-12+'px';
    back.style.background = '#fffde1';
    parent.appendChild(back);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/lt' + ext;
    img.style.position = 'absolute';img.style.left = bx+'px';img.style.top = by+'px';
    img.style.width = 12+'px';img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/rt' + ext;
    img.style.position = 'absolute';img.style.left = bx+bw-12+'px';img.style.top = by+'px';
    img.style.width = 12+'px';img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/lb' + ext;
    img.style.position = 'absolute';img.style.left = bx+'px';img.style.top = by+bh-12+'px';
    img.style.width = 12+'px';img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/rb' + ext;
    img.style.position = 'absolute';img.style.left = bx+bw-12+'px';img.style.top = by+bh-12+'px';
    img.style.width = 12+'px';img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/l' + ext;
    img.style.position = 'absolute';img.style.left = bx+'px';img.style.top = by+12+'px';
    img.style.width = 6+'px';img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/t' + ext;
    img.style.position = 'absolute';img.style.left = bx+12+'px';img.style.top = by+'px';
    img.style.width = bw-24+'px';img.style.height = 6+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/r' + ext;
    img.style.position = 'absolute';img.style.left = bx+bw-6+'px';img.style.top = by+12+'px';
    img.style.width = 6+'px';img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/b' + ext;
    img.style.position = 'absolute';img.style.left = bx+12+'px';img.style.top = by+bh-6+'px';
    img.style.width = bw-24+'px';img.style.height = 6+'px';
    parent.appendChild(img);
    container.style.position = 'absolute';
    container.style.left = bx+12+'px';
    container.style.top = by+12+'px';
    container.style.width = bw-24+'px';
    container.style.height = bh-24+'px';
    container.style.background = '#fffde1';
    container.style.zIndex = 10000;
    balloonContainers[id] = container;
    container.style.visibility = 'visible';
    var img = document.createElement('IMG');
    img.style.position = 'absolute';
    switch (direction) {
        case 'lt' :
            img.src = '/core/images/balloons/arrow_rb' + ext;
            img.style.left = x-52+'px';img.style.top = y-36+'px';
            img.style.width = 52+'px';img.style.height = 36+'px';
            break;
        case 'lb' :
            img.src = '/core/images/balloons/arrow_rt' + ext;
            img.style.left = x-52+'px';img.style.top = y+'px';
            img.style.width = 52+'px';img.style.height = 36+'px';
            break;
        case 'rt' :
            img.src = '/core/images/balloons/arrow_lb' + ext;
            img.style.left = x+'px';img.style.top = y-36+'px';
            img.style.width = 52+'px';img.style.height = 36+'px';
            break;
        case 'rb' :
            img.src = '/core/images/balloons/arrow_lt' + ext;
            img.style.left = x+'px';img.style.top = y+'px';
            img.style.width = 52+'px';img.style.height = 36+'px';
            break;
    }
    parent.appendChild(img);
}

function hideBalloon(id)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = 'none';
        var container = balloonContainers[id];
        container.style.display = 'none';
    }
}

var ajaxInRequest = false, ajaxQueue = new Array(), onEndAjaxEvents = new Array();
function AjaxRequest(url)
{
    if (ajaxInRequest) {
        ajaxQueue.push(url);
        return;
    }
    ajaxInRequest = true;
    var head = document.getElementsByTagName('head').item(0);
    var old = document.getElementById("AJAXScript");
    if (old) head.removeChild(old);
    var script = document.createElement("SCRIPT");
    script.src = url + "&ajaxrequest=" + Math.random().toString() +
        "&ajaxqs=" + escape(location.search);
    script.type = "text/javascript"
    script.id = "AJAXScript";
    head.appendChild(script);
}

function AjaxEndRequest()
{
    ajaxInRequest = false;
    if (ajaxQueue.length) {
        var url = ajaxQueue.shift();
        AjaxRequest(url);
    } else {
        if (typeof(hideWaitWnd) == "function") hideWaitWnd();
        if (typeof(hiddedByAjaxRefresh) == "object") {
            for (var i = 0; i < hiddedByAjaxRefresh.length; i++) {
                var ctl = hiddedByAjaxRefresh[i],
                    t = ctl.getAttribute('ajaxDisabled');
                if (t) ctl.disabled = t == 'yes';
                else ctl.disabled = false;
            }
            hiddedByAjaxRefresh = [];
        }
        for(var i = 0; i < onEndAjaxEvents.length; i++) {
        	onEndAjaxEvents[i]();
        }
        onEndAjaxEvents = [];
    }
}

function AjaxRefresh(args)
{
    var url = window.location.href;
    if (args) {
    	url += (-1 == url.indexOf('?') ? '?' : '&') + args;
    }
    AjaxRequest(url);
}

function addOnEndAjaxEvent(func)
{
	if (typeof(func) == 'function') {
		onEndAjaxEvents.push(func);
	}
}

var defaultLocale = {currency_sign: '$', sign_position: 'before', thousand_sep: ',',
    decimal_sep: '.', rate: 1};
var frameLocale = [];

function numberFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale;
    var str = (Math.round(value * 100) / 100).toFixed(2);
    var dot = str.indexOf('.'), v1, v2;
    if (dot != -1) {
        v1 = str.substring(0, dot);
        v2 = str.substring(dot + 1, str.length);
    } else {
        v1 = str;
        v2 = '00';
    }
    var rem = 0;
    var res = '';
    while (v1 >= 1000) {
        rem = v1 % 1000;
        while (rem.toString().length < 3) rem = '0' + rem;
        res = locale.thousand_sep + rem + res;
        v1 = Math.floor(v1 / 1000);
    }
    return v1 + res + locale.decimal_sep + v2;
}

function currencyFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale;
    var res = numberFormat(value*locale.rate, frameId);
    var space = locale.currency_sign.length == 3 ? ' ' : '';
    if (locale.sign_position == 'after') res += space + locale.currency_sign;
    else res = locale.currency_sign + space + res;
    return res;
}

function disableControls(form)
{
    for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].disabled = true;
    }
}

preloadImages = [];
function preloadImage(url)
{
    var im = new Image;
    preloadImages.push(im);
    im.src = url;
}

var fileControlName = '';
var fileControlInfo = new Object();
function fileStoreShow(controlOrFunctionName, default_dir, store_type, type, max_width, max_height,
    max_images, single, enable_java)
{
    // max_images is used to limit number of items in fileds with multiple values
    if (type == 'image') {
        if (!max_images) max_images = 1;
        if (typeof(single) == 'undefined') single = 1;
    }
    fileControlName = controlOrFunctionName;
    fileControlInfo = {max_images: max_images, single: single};
    var f = document.getElementById(controlOrFunctionName + '_file');
    var file_store_url =
        '/' + (typeof current_user != 'undefined' ? current_user : 'core') +
        '/file_store/file_store.php' +
        '?default_dir=' + escape(default_dir) +
        '&select=' + escape(f ? f.value : '') +
        '&store_type=' + escape(store_type) +
        '&type=' + escape(type) +
        '&max_width=' + escape(max_width ? max_width : '') +
        '&max_height=' + escape(max_height ? max_height : '')+
        '&enable_java=' + escape(typeof(enable_java) == 'undefined' ? 1 : (enable_java ? 1 : 0));

    popup_exec_url(file_store_url, null, 800, 500, false, null,
        'Select ' + (type == 'image' ?'an Image':'a File'));
    popup_show_buttons(false);
}

function imageBoxRemoveImage(id)
{
    var box = document.getElementById(id);
    box.parentNode.removeChild(box);
}

function imageBoxAddImage(name, src, value, max_images, single, disabled)
{
    // Retrieve images container
    var imageset = document.getElementById(name);
    if (!imageset) {
        return false;
    }

    var num = imageset.getElementsByTagName('img').length;
    if (max_images == 1) {
        for (i = 0; i < num; i++) {
            imageset.removeChild(imageset.childNodes[i]);
        }
    } else {
        if (num >= max_images) {
            alert('Sorry, you can\'t add more than ' + max_images + ' images.');
            return false;
        }
    }

    // Define current image id and number
    var image_num = imageset.getElementsByTagName('img').length + 1;
    var image_id   = name + '_' + image_num + '_pv';
    var remove_btn_id = name + '_' + image_num + '_remove';

    // Create div containing image
    var image_box = document.createElement('span');
    image_box.id = image_id;
    if (!disabled) {
	    image_box.onmouseover = function() {
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'visible';
	        var box = span.parentNode.getElementsByTagName('img')[0];
	        span.style.left = box.offsetLeft + box.offsetWidth - 25 + 'px';
	        span.style.top = box.offsetTop + 1 + 'px';
	    };

	    image_box.onmouseout = function() {
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'hidden';
	    };
    }
    image_box.className = 'box';

    var image = document.createElement('img');
    image.src = src + '&broken=1';
    image_box.appendChild(image);

    if (!disabled) {
	    // Create remove button
	    var remove_btn = document.createElement('div');
	    remove_btn.id = remove_btn_id;
	    remove_btn.className = 'imageset_add_button';
	    remove_btn.style.visibility = 'hidden';
	    remove_btn.onclick = function() {imageBoxRemoveImage(image_id);};
	    remove_btn.innerHTML = 'X';
	    image_box.appendChild(remove_btn);
    }

    // Create hidden form element
    var hidden = document.createElement('input');
    hidden.type = 'hidden';
    hidden.value = value;
    hidden.name = single ? name : name + '[]';
    hidden.id = name + '_' + image_num;
    image_box.appendChild(hidden);

    imageset.insertBefore(image_box, document.getElementById(name + '_add'));
    imageset.insertBefore(document.createTextNode(' '), document.getElementById(name + '_add'));
}

searchFormInfo = {};
function searchFormClear(name)
{
    var visctl = document.getElementById('sf_vis_' + name);
    document.getElementById(name).value = '';
    document.getElementById('sf_id_' + name).value = '';
    document.getElementById(name + '_c').value = '';
    document.getElementById('sf_id_' + name + '_c').value = '';
    visctl.innerHTML = '';
    visctl.innerHTML = '<div name="_empty_">&lt;' + searchFormInfo[name].empty_value +
        '&gt;</div>';
}

function searchFormChange(ctl)
{
    if (ctl.type == 'checkbox') {
        var cbs = document.getElementsByName(ctl.name);
        var sel = false;
        for (var i = 0; i < cbs.length; i++) {
            if ((cbs[i].value == 'selected' || cbs[i].value == 'all_except_selected')
            && cbs[i].checked) {
                sel = true;
                break;
            }
        }
    } else {
        sel = ctl.value == 'selected' || ctl.value == 'all_except_selected';
    }
    var list = document.getElementById('sf_list_'+ctl.name);
    if (list) list.style.display = sel ? '' : 'none';
    var list1 = document.getElementById('sf_add_'+ctl.name);
    if (list1) list1.style.display = sel ? '' : 'none';
}

function showSearchForm(name)
{
    if (typeof popup_exec_url == 'function') {
        var mode = searchFormInfo[name].mode;
        var closeName = mode == 'multi_nojs' ? 'Cancel' : (mode == 'multi' ? 'Apply' : 'Close');
        popup_exec_url(searchFormInfo[name].url, null, 550, 800, true,
        	searchFormInfo[name]['onClose'] || null, searchFormInfo[name].title, closeName);
        if (mode == 'multi_nojs') {
            var okBtn = getPopupButton('ok');
            okBtn.style.display = '';
            okBtn.onclick = function() {
                applyClick(getPopupForm('fitemsearch'), 'save');
            }
        }
    } else {
        var size = "width=500,height=500,scrollbars=yes,resizable=yes";
        window.open(searchFormInfo[name].url, "search_form", size);
    }
}
/**
 * @param name - form name
 * @param mode - p|c
 * @param ids  - array of ids to add
 * @param items - items array to get title and code
 * @param status - mode, true to select, false to deselect
 * @param page_id
 */
function searchFormMassSelect(name, mode, ids, items, status, page_id)
{
    if (ids.length == 0) return;

    var prod_id;
    if (mode == 'p') {
        prod_id = searchFormInfo[name].key_field;
    } else {
        prod_id = searchFormInfo[name].cat_key_field;
    }

    if (searchFormInfo[name].mode == 'single') {
        var item = items[ids[0]];
        searchFormSelect(name, mode, item[prod_id], item['title'], item['code'], status, page_id);
        return;
    }

    var ctl = null, idctl = null, snp = null;
    if (mode == 'p') {
        ctl = document.getElementById(name);
        idctl = document.getElementById('sf_id_' + name);
    } else {
        ctl = document.getElementById(name + '_' + mode);
        idctl = document.getElementById('sf_id_' + name + '_' + mode);
        snp = document.getElementById(name + '_nested_panel');
    }
    var visctl = document.getElementById('sf_vis_' + name);
    if (!ctl || !idctl || !visctl) return;

    var img = '';
    if (mode == 'p') {
        img = '<img src="/core/images/tree/leaf.gif" width="20" height="20" align="absmiddle" border="0"/>';
    } else if (mode == 'c') {
        img = '<img src="/core/images/tree/folder.gif" width="20" height="20" align="absmiddle" border="0"/>';
    }

    var ev = searchFormInfo[name].empty_value;

    var current_list = ctl.value.split(',');
    var actual_list = new Array();
    // keep only checked items
    if (status) { // add
        actual_list = current_list.concat(ids);
        array_unique(actual_list);
    } else { // substract
        while(current_list.length > 0) {
            var value = current_list.pop();
            var found = false;
            for (var i=0; i < ids.length; i++) {
                if (ids[i] == value) {found = true;break;}
            }
            if (found) continue;
            actual_list.push(value);
        }
    }

    visctl.innerHTML = '';
    inner_html = '';
    for(var i = 0; i < actual_list.length; i++) {
        var item = items[actual_list[i]]
        if (!item) continue;
        title = img + (searchFormInfo[name]['onDisplay'] ?
    	window[searchFormInfo[name]['onDisplay']](actual_list[i], item['title'], item['code']) : item['title']);
        inner_html += '<div name="'+mode+'_'+actual_list[i]+'">'+title+'</div>';
    }
    visctl.innerHTML = inner_html;
    if (actual_list.length == 0)
        visctl.innerHTML = '<div name="_empty_">&lt;'+ev+'&gt;</div>';

    var s = '';
    for (var i = 0; i < actual_list.length; i++)
        if (actual_list[i]) s+= ','+actual_list[i];
    idctl.value = ctl.value = s.substr(1);

    if (snp) snp.style.display = ctl.value ? '' : 'none';
}

function searchFormSelect(name, mode, id, title, code, status, page_id)
{
    var ctl = null, idctl = null, snp = null;
    if (mode == 'p') {
        ctl = document.getElementById(name);
        idctl = document.getElementById('sf_id_' + name);
    } else {
        ctl = document.getElementById(name + '_' + mode);
        idctl = document.getElementById('sf_id_' + name + '_' + mode);
        snp = document.getElementById(name + '_nested_panel');
    }
    var visctl = document.getElementById('sf_vis_' + name);
    if (!ctl || !idctl || !visctl) return;

    var img = '';
    if (mode == 'p') {
        img = '<img src="/core/images/tree/leaf.gif" width="20" height="20" align="absmiddle" border="0"/>';
    } else if (mode == 'c') {
        img = '<img src="/core/images/tree/folder.gif" width="20" height="20" align="absmiddle" border="0"/>';
    }
    title = img + (searchFormInfo[name]['onDisplay'] ?
    	eval(searchFormInfo[name]['onDisplay']+'(id, title, code)') : title);

    if (searchFormInfo[name].mode == 'single') {
        if (mode == 'p') {
            ctl.value = eval(searchFormInfo[name].key_field);
        } else {
            ctl.value = eval(searchFormInfo[name].cat_key_field);
            if (snp) snp.style.display = ctl.value ? '' : 'none';
        }
        if (id) {
            visctl.innerHTML = title;
        } else {
            visctl.innerHTML = '&lt;' + searchFormInfo[name].empty_value + '&gt;';
        }
        idctl.value = id;
    }

    if (searchFormInfo[name].mode == 'multi') {
        var ctl_id = name;
        var ev = searchFormInfo[name].empty_value;
        var prod_id;
        if (mode == 'p') {
            prod_id = eval(searchFormInfo[name].key_field);
        } else {
            prod_id = eval(searchFormInfo[name].cat_key_field);
        }

        var list = ctl.value.split(',');
        var idlist = idctl.value.split(',');
        var idx = -1;
        for (var i=0; i<idlist.length; i++)
            if (idlist[i] == id)
            {
                idx = i;
                break;
            }
        var ectl = null, pctl = null;
        for (var i=0; i<visctl.childNodes.length; i++) {
            if (visctl.childNodes[i].nodeType != 1) continue;
            if (visctl.childNodes[i].getAttribute('name') == '_empty_') {
                ectl = visctl.childNodes[i];
            }
            else if (visctl.childNodes[i].getAttribute('name') == mode+'_'+id) {
                pctl = visctl.childNodes[i];
            }
        }
        if (status && idx == -1)
        {
            idlist[list.length] = id;
            list[list.length] = prod_id;
            if (ectl) visctl.removeChild(ectl);
            if (visctl)
                visctl.innerHTML = visctl.innerHTML+
                    '<div name="'+mode+'_'+id+'">'+title+'</div>';
        }
        else if (!status && idx != -1)
        {
            idlist[idx] = '';
            list[idx] = '';
            if (pctl) visctl.removeChild(pctl);
            if (visctl && visctl.innerHTML == '')
                visctl.innerHTML = '<div name="_empty_">&lt;'+ev+'&gt;</div>';
        }
        var s = '';
        for (var i=0; i<list.length; i++)
            if (list[i])
                s += ','+list[i];
        ctl.value = s.substr(1);
        s = '';
        for (var i=0; i<idlist.length; i++)
            if (idlist[i])
                s += ','+idlist[i];
        idctl.value = s.substr(1);
        if (snp) snp.style.display = ctl.value ? '' : 'none';
    }
}

function searchFormAfterLoad(name, w)
{
    if (!searchFormInfo[name]) return;
    if (searchFormInfo[name].mode == 'multi') {
    	var sxa = new Array('p', 'c');
        var np = 0, nc = 0;
        for (var j=0; j<sxa.length; j++) {
            var sx = sxa[j];
            var idctl, idctl_dis;
            if (sx == 'p') {
                idctl = document.getElementById('sf_id_'+name);
                idctl_dis = document.getElementById('sf_dis_ids_'+name);
            } else {
                idctl = document.getElementById('sf_id_'+name+'_'+sx);
                idctl_dis = document.getElementById('sf_dis_ids_'+name+'_'+sx);
            }
            if (!idctl) continue;

            var list = idctl.value.split(',');
            var c = 0;
            for (var i=0; i<list.length; i++) {
                if (list[i]) {
                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
                    if (cb) cb.checked = true;
                    c++;
                }
            }
            if (sx == 'p') np = c;
            if (sx == 'c') nc = c;

            if (idctl_dis) {
            	var list = idctl_dis.innerHTML.split(',');
	            for (var i=0; i<list.length; i++) {
	                if (list[i]) {
	                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
	                    if (cb) cb.disabled = true;
	                }
	            }
            }
        }
        w.sf_set_numbers(np, nc);
    } else if (searchFormInfo[name].mode == 'single') {
	    var idctl_dis = document.getElementById('sf_dis_ids_'+name+'_c');
        if (idctl_dis) {
	    	var list = idctl_dis.innerHTML.split(',');
	        for (var i=0; i<list.length; i++) {
	            if (list[i]) {
	                var tr = w.document.getElementById('cr_'+list[i]);
	                if (tr) {
		                var a = tr.getElementsByTagName('a');
		                if (a[0]) {
		                	var span = document.createElement('span');
		                	span.innerHTML = a[0].innerHTML;
		                	a[0].parentNode.appendChild(span);
		                	a[0].parentNode.removeChild(a[0]);
		                }
	                }
	            }
	        }
        }
    }
}

dialogWindow = null;
function showDialog(id, fade, position)
{
    // position - to force position to fix editor dropdowns position
    hideDialog();
    var ctl = document.getElementById(id);
    if (ctl) {
        if (fade) fadeStack.show(hideDialog);
        ctl.style.visibility = 'hidden';
        ctl.style.zIndex = fadeStack.getZIndex();
        ctl.style.display = '';
        if (position) {
        	ctl.style.position = position;
        } else if (useAbsPosition) {
            ctl.style.position = 'absolute';
        } else {
            ctl.style.position = 'fixed';
        }
        var isAbs = ctl.style.position == 'absolute';
        ctl.style.left = max((getClientWidth() - ctl.offsetWidth) / 2, 10) + (isAbs ? getScrollLeft() : 0) + 'px';
        ctl.style.top = max((getClientHeight() - ctl.offsetHeight) / 2, 10) + (isAbs ? getScrollTop() : 0) + 'px';
        ctl.style.visibility = 'visible';
        dialogWindow = ctl;
        hideElements(ctl, ctl);
        ctl.onmousedown = function (event) { (event || window.event).cancelBubble = true; };
        if (!fade) dialogAttachEvents();
        enableDialogDragging(dialogWindow);
        disableScroll();
        correctPopupSizesForIE(ctl);
        focusFirstControl(ctl);
        if (window.addEventListener) {
        	// window.addEventListener('focus', dialogFocusHandler, true);
        }
    }
}

function hideDialog()
{
	fadeStack.hide();
    if (typeof hide_popup == 'function') hide_popup();
    var ctl = dialogWindow;
    if (ctl) {
        ctl.style.display = 'none';
        ctl.style.visibility = 'hidden';
        dialogWindow = null;
        showElements();
        disableDialogDragging(ctl);
        if (window.removeEventListener) {
        	// window.removeEventListener('focus', dialogFocusHandler, true);
        }
    }
    enableScroll();
}

function moveDialog()
{
    var ctl = dialogWindow;
    if (ctl) {
    	var isAbs = ctl.style.position == 'absolute';
    	ctl.style.top = max((getClientHeight() - ctl.offsetHeight) / 2, 20) + (isAbs ? getScrollTop() : 0) + 'px';
    }
}

dialogEventsAttached = false;
function dialogAttachEvents()
{
    if (!dialogEventsAttached) {
        dialogEventsAttached = true;
        addHandler(document.body, 'mousedown', hideDialog);
    }
}

function enableDialogDragging(dialogWindow)
{
	if (mobileVersion) return;
	dialogWindow.draggingStarted = false;
	var divs = dialogWindow.getElementsByTagName('DIV');
	var dialogHeader = null, closeButton = null;
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == 'PopupHeader') {
			dialogHeader = divs[i];
		}
		if (divs[i].id.indexOf('PopupCloseDiv') != -1 || divs[i].className == "PopupCloseButton") {
			closeButton = divs[i];
		}
		if (is_msie())
			divs[i].setAttribute('unselectable', 'on');
	}
	if (!dialogHeader) return;

	var upperLayer = document.createElement('DIV');
	upperLayer.className = 'DragLayer';
	if (is_msie() && quirksMode)
	   upperLayer.style.height = dialogWindow.offsetHeight + 'px';
	dialogWindow.appendChild(upperLayer);
	dialogWindow.upperLayer = upperLayer;

	dialogHeader.onmousedown = function(event) {
		event = event || window.event;
		dialogWindow.draggingStarted = true;
		dialogWindow.deltaX = event.clientX - parseInt(dialogWindow.style.left);
		dialogWindow.deltaY = event.clientY - parseInt(dialogWindow.style.top);
		upperLayer.style.zIndex = '100';
	};
	upperLayer.onmousemove = dialogHeader.onmousemove = dialogWindow.onmousemove = function(event) {
        if (is_msie() && closeButton) {
            closeButton.className = '';
            closeButton.className = 'PopupCloseButton';
        }
        if (!dialogWindow.draggingStarted) return;
		event = event || window.event;
		dialogWindow.style.top = event.clientY - dialogWindow.deltaY + 'px';
		dialogWindow.style.left = event.clientX - dialogWindow.deltaX + 'px';
	};
	upperLayer.onmouseup = dialogHeader.onmouseup = dialogWindow.onmouseup = function() {
		if (dialogWindow)
			dialogWindow.draggingStarted = false;
		dialogWindow.upperLayer.style.zIndex = '-1';
	};

	addHandler(document.body, 'mousemove', dialogWindow.onmousemove);
}

function disableDialogDragging(dialogWindow)
{
	if (mobileVersion) return;
	if (dialogWindow.upperLayer) {
        dialogWindow.removeChild(dialogWindow.upperLayer);
	}
	dialogWindow.upperLayer = null;
	removeHandler(document.body, 'mousemove', dialogWindow.onmousemove);
}

// disable scroll event bubbling
function disableScroll()
{
	return;
    if (document.body.style.overflow != 'hidden') {
        document.body.style.overflow = 'hidden';
        var padding = document.body.style.paddingRight ? parseInt(document.body.style.paddingRight) : 0;
        document.body.style.paddingRight = (padding + 17) + 'px';
    }
}

function enableScroll()
{
	return;
	if (!fadeStack.isFadeDisplayed() && document.body.style.overflow == 'hidden') {
        document.body.style.overflow = 'auto';
        document.body.style.paddingRight = (parseInt(document.body.style.paddingRight) - 17) + 'px';
    }
}

var blackShadowsApplied = false;
function setBlackShadows()
{
    if (blackShadowsApplied) return;
    blackShadowsApplied = true;
    var link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', '/core/wf_getcss.php?css=core/css/dialog_dark.css');
    document.getElementsByTagName('head')[0].appendChild(link);
}

function focusFirstControl(parent)
{
    var inputs = parent.getElementsByTagName('*');
    var focus = null;
    for (var i = 0; i < inputs.length; i++) {
    	var input = inputs[i], tag = input.tagName.toLowerCase(), type = input.type;
    	if ((tag == 'input' && type != 'checkbox' && type != 'radio' && type != 'button'
		&& type != 'submit' && type != 'reset' && type != 'hidden' || tag == 'select' || tag == 'textarea')
		&& !input.disabled && input.offsetHeight) {
    		focus = input;
			break;
    	}
    }
    if (!focus) {
	    for (var i = 0; i < inputs.length; i++) {
	    	var input = inputs[i], tag = input.tagName.toLowerCase();
	    	if ((tag == 'input' && input.type != 'hidden' || tag == 'button') && !input.disabled
			&& input.offsetHeight) {
				try { input.focus(); }
				catch (e) { }
				break;
	    	}
	    }
    }
    if (focus) {
		try { focus.focus(); } catch (e) { }
    }
}

var currentFocus = null;
function dialogFocusHandler(event)
{
	var e = event.srcElement;
	while (e.tagName.toLowerCase() != 'body' && e != dialogWindow) {
		e = e.parentElement;
	}
	if (e != dialogWindow) {
		try { currentFocus.focus(); } catch (e) { }
	} else {
		currentFocus = event.srcElement;
	}
}

function turnPage(pageUrl, frame_id)
{
    var result = true;
    if (typeof(doExtraCheck) == 'function') {
        result = doExtraCheck(frame_id);
    }
    if (result)
        setLocation(pageUrl);
}

function _putHelpLabel(label, header, descr) {
    if (el = document.getElementById('help_description_' + label)) {
        try {
            el.innerHTML = '<div style="font-weight: bold; font-size: 10pt; color: #808080; margin-bottom: 10pt">' + header + '</div><div>' + descr + '</div>';
        } catch (e) {}
    }
}

function showRatingStars(id, rating, showEmpty, isAverage, item_id, item_label, title, reviews)
{
	var el = typeof(id) == 'string' ? document.getElementById(id) : id;
	if (!el) return;
	var html = '';
    var intRating, isFirst = true;
    if (rating >= 1 && rating <= 5) {
        intRating = parseInt(rating);
        for (var i = 0; i < intRating; i++) {
            html += '<img src="/core/images/stars/yellow.png" ' +
            	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
            if (isFirst) isFirst = false;
        }
        if (intRating != rating) {
          html += '<img src="/core/images/stars/half.png" ' +
          	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
          if (isFirst) isFirst = false;
          intRating++;
        }
        for (var i = 0; i < (5-intRating); i++) {
          html += '<img src="/core/images/stars/gray.png" ' +
          	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
          if (isFirst) isFirst = false;
        }
    } else if (showEmpty) {
    	for(var i = 0; i < 5; i++) {
    		html += '<img src="/core/images/stars/gray.png" ' +
    			(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
    		if (isFirst) isFirst = false;
    	}
    }

    if (item_id) {
	    if (reviews) {
	    	el.style.cursor = "pointer";
	        el.style.whiteSpace = "nowrap";
	        el.title = "Read "+reviews+" Review" + (reviews > 1 ? "s" : "");
	        el.onclick = new Function("showReviews('"+item_id+"', '"+item_label+"', '"+title.replace('\'','\\\'')+"', 1);");
	    } else if (showEmpty) {
	    	el.title = "0 Reviews";
	    }
    }
    if (isAverage) {
    	// add zeros after dot:
    	var dotInd = rating.toString().indexOf('.');
    	if (dotInd == -1) {
    		rating += ".00";
    	} else {
    		var len = rating.length - dotInd - 1;
    		if (len == 1) rating += "0";
    	}
    	el.title += (el.title ? ", " : "") + "Average Rating: " + rating;
    }
    el.innerHTML = html;
}

// Shows frame with review list.
// Use item_id=-1 for all reviews, item_id=-2 for unapproved reviews.
// Set title if you want to change title of the frame.
// Page is a page number in the review list.
function showReviews(item_id, item_label, title, page)
{
	var url = document.location.href;
	url = url.replace(/\/[a-z0-9_]+\/[^\/]*$/, "/freviews/") + '?popup=1';
	if (page == 0) page = 1;
	url = url+'&item='+item_id+'&reviewsPage='+page;
	popup_exec_url(url, null, 700, 500, true, typeof(refreshList) == 'function' ? 'refreshList' : null,
		item_label + " Reviews: " + title, "Close");
}

// вызов showRatingStars сразу для нескольких TD
// mode: 'simple', 'full'
function showRatingStarsMultiple(mode, item_label)
{
    function getElementsByName_iefix(tag, name)
    {
        var elem = document.getElementsByTagName(tag);
        var arr = new Array();
        for(i = 0,iarr = 0; i < elem.length; i++) {
            att = elem[i].getAttribute("name");
            if (att == name) {
                arr[iarr] = elem[i];
                iarr++;
            }
        }
        return arr;
    }
    var cells = getElementsByName_iefix("td", "rc");
    if (mode == 'simple') {
        for (x in cells) {
            showRatingStars(cells[x], cells[x].innerHTML);
        }
    } else {
        for (x in cells) {
    		var data = cells[x].innerHTML.split(',');
    		var rating = data[0];
    		var reviews = data[1];
    		var item_id = cells[x].id.substring(2);
    		var tc = document.getElementById('tc'+item_id);
    		var title = tc.innerHTML;
    		showRatingStars(cells[x], rating, 0, 1, item_id, item_label, title, reviews);
        }
    }
}

function resetEditorContent(name)
{
	if (typeof(editorExtraParams) == 'undefined' || !editorExtraParams[name]) return;
	var defVal = editorExtraParams[name]['defValue'];
	if (typeof(defVal) == 'undefined') return;

	if (confirm("Are you sure you want to discard your customized field content?")) {
		editor_set_text(name, defVal);
	}
}

var addrErrorBox = null;
function initAddrErrorBoxRef(link)
{
    if (addrErrorBox) return;
    var div = link.parentNode;
    while(div && (div.tagName != 'DIV' || div.className != 'errorbox')) div = div.parentNode;
    addrErrorBox = div;
}

function correctAddressFields(formId, fields, inPopup)
{
    // hide popup if link was clicked from popup
    if (inPopup) {
        hide_popup();
    }

    // close errorBox
    if (!addrErrorBox && (popupFrame = getPopupProp('iframe'))) {
        addrErrorBox = popupFrame.contentWindow.addrErrorBox;
    }
    if (addrErrorBox) {
        addrErrorBox.parentNode.removeChild(addrErrorBox);
        addrErrorBox = null;
    }

    // set new values
    var form = document.getElementById(formId) || getPopupForm(formId);
    var inputs = form.getElementsByTagName('input');
    for(var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'text' && fields[inputs[i].name]) {
            inputs[i].value = fields[inputs[i].name];
        }
    }
    var selects = form.getElementsByTagName('select');
    for(var i = 0; i < selects.length; i++) {
        if (fields[selects[i].name]) {
            selects[i].value = fields[selects[i].name];
        }
    }

    // recalculate shipping on checkout form
    if (formId == 'fclcheckout') {
        ajaxPostSubmit(form, '', true)
    }
}

// if func is not defined in current window => try to call from parent windows
function _call(func_name, func_args)
{
    var w = window;
    while(typeof(w[func_name]) != 'function') {
        if (w == w.parent) return null;
        w = w.parent;
    }
    return w[func_name].apply(w, func_args || []);
}

function callPaypalExpress(frameId)
{
    var f = getFormByFrame(frameId);
    f.submitAction.value = 'call_paypal_express';
    f.submit();
}

var submit_action = '';
function set_submit_action(action_name)
{
    submit_action = action_name;
}
/**
 * Image List Interface js
 */
var imgArr = new Array(),
    pgrArr = new Array(),
    getThumb = 'xx';

function initPager(frameId, limit, numrows, rotate, random, linkUrl, linkIn, changeCur)
{
    pgrArr[frameId] = new Array();
    pgrArr[frameId]['from']     = 0;
    pgrArr[frameId]['limit']    = limit > 0 ? limit : 99;
    pgrArr[frameId]['numrows']  = numrows >= 0 ? numrows : 0;
    pgrArr[frameId]['len']      = 'no' == rotate ? limit : 1;
    pgrArr[frameId]['numpages'] = Math.ceil(pgrArr[frameId]['numrows'] / pgrArr[frameId]['len']);
    pgrArr[frameId]['last']     = (pgrArr[frameId]['numpages'] - 1) * pgrArr[frameId]['len'];
    pgrArr[frameId]['rotate']   = rotate ? rotate : 'no';
    pgrArr[frameId]['random']   = random;
    pgrArr[frameId]['linkurl']  = linkUrl;
    pgrArr[frameId]['linkin']   = linkIn;
    pgrArr[frameId]['chngcur']  = changeCur;
}

function fillImageList(frameId, from)
{
    var pfrom = pgrArr[frameId]['from'];
    pgrArr[frameId]['from'] = from >= 0 ? (from <= pgrArr[frameId]['last'] ? from : 0) : pgrArr[frameId]['last'];
    var i, td, res, len, pos, pager = pgrArr[frameId];
    // prepare pager info
    if ('automatically' != pager['rotate']) {
        var res = '';
        if (pager['numpages'] > 1) {
            // prev page
            res += '<a href="javascript:fillImageList(' + frameId + ',';
            res += (pager['from'] <= 0 ? pager['last'] : (pager['from'] - pager['len'])) + ')">&lt; Prev</a>&#xA0;';
            // pages
            var offset = 0; pos = pager['from'] / pager['len'] - 1;
            for (i = 0; i < pager['numpages']; i++) {
                offset = i * pager['len'];
                if (pager['from'] == offset) {
                    res += '[' + (i + 1) + ']&#xA0;';
                } else if (i < 3 || i >= (pager['numpages'] - 3) || (i > pos - 2 && i < pos + 4)) {
                    res += '<a href="javascript:fillImageList(' + frameId + ',' + offset + ')">' + (i + 1) + '</a>&#xA0;';
                } else if (res.substring(res.length - 9) != '...&#xA0;') {
                    res += '...&#xA0;';
                }
            }
            // next page
            res += '<a href="javascript:fillImageList(' + frameId + ',';
            res += (pager['from'] >= pager['last'] ? 0 : (pager['from'] + pager['len'])) + ')">Next &gt;</a>';
        }
        // draw pager
        td = getFrameElementById(frameId, 'tnav');
        if (td) td.innerHTML = res;
        td = getFrameElementById(frameId, 'bnav');
        if (td) td.innerHTML = res;
    }
    // mark current
    var frameObj = getFrameObjById(frameId);
    var currImgFS = currImgPV = prevImgFS = prevImgPV = 0;
    if (frameObj.isMarkCur) {
        if (frameObj.curItemId != frameObj.pluginObj.curItemId) {
            if (frameObj.pluginObj.curItemId) {
                currImgFS = frameObj.pluginObj.curItemId;
                currImgPV = getPVImage(currImgFS);
            }
            if (frameObj.curItemId) {
                prevImgFS = frameObj.curItemId;
                prevImgPV = getPVImage(prevImgFS);
            }
            frameObj.curItemId = frameObj.pluginObj.curItemId;
        }
    }
    // draw images
    if ('automatically' == pager['rotate'] && pager['random'] == 1) {
        pager['from'] += Math.round(Math.random() * (pager['numrows'] - 1));
        pager['from'] = pager['from'] > pager['numrows'] ? pager['from'] - pager['numrows'] : pager['from'];
        pgrArr[frameId] = pager;
    }
    var res = '';
    for (i = 0; i < pager['limit']; i++) {
        pos = (pager['from'] + i < pager['numrows'] || pager['numrows'] < pager['limit']) ? pager['from'] + i : i - (pager['numrows'] - pager['from']);
        td = getFrameElementById(frameId, 'td_' + (i + 1));
        if (td) {
            if (imgArr[frameId][pos]) {
                res  = '<a' + (pager['linkurl'] && 'new' == pager['linkin'] ? ' target="_blank"' : '') + ' href="';
                if (pager['linkurl'] == 'popup')
                    res += 'javascript:showLargeImage(\'img_'+frameId+'_'+pos+'\')';
                else if (pager['linkurl'])
                    res += pager['linkurl'];
                else
                    res += 'javascript:changeCurrentImage(' + frameId + ',\'' + escape(imgArr[frameId][pos]) + '\')';
                res += '"><img src="' + imgArr[frameId][pos] + '" border="0" id="img_'+frameId+'_'+pos+'"/></a>';
                td.innerHTML = res;
            } else {
                td.innerHTML = '';
            }
            if (currImgFS && imgArr[frameId][pos] == currImgFS || imgArr[frameId][pos] == currImgPV) {
                _resetBorderStyle(td);
                td.style.borderLeft   = '2px dotted';
                td.style.borderTop    = '2px dotted';
                td.style.borderRight  = '2px dotted';
                td.style.borderBottom = '2px dotted';
            } else if (frameObj.isMarkCur) {
                _resetBorderStyle(td);
                var ostyle = td.getAttribute('ostyle');
                if (-1 != ostyle.indexOf('border-left:none'))   td.style.borderLeft   = 'none';
                if (-1 != ostyle.indexOf('border-top:none'))    td.style.borderTop    = 'none';
                if (-1 != ostyle.indexOf('border-right:none'))  td.style.borderRight  = 'none';
                if (-1 != ostyle.indexOf('border-bottom:none')) td.style.borderBottom = 'none';
            }
        }
    }
    // change current
    if (pfrom != pager['from'] && pager['chngcur']) {
        changeCurrentImage(frameId,
            decodeURI(imgArr[frameId][pager['from'] < pager['numrows'] ?
            pager['from'] : pager['from'] - pager['numrows']]));
    }
}

function getFSImage(fn)
{
    var re = /file=([^&]*)/i;
    var m = fn.match(re);
    if (m) {
        return decodeURIComponent(m[1]);
    } else {
        return fn;
    }
}

function getPVImage(fn)
{
    var re = /file=([^&]*)/i;
    if (fn.match(re)) {
        return fn;
    } else {
        return getThumb + encodeURIComponent(fn);
    }
}

function changeCurrentImage(frameId, img)
{
    var imgFS = getFSImage(img),
        imgPV = imgFS == img ? getPVImage(img) : img;
    var frameObj = getFrameObjById(frameId);
    frameObj.pluginObj.curItemId = imgFS;
    for (var i = 0; i < frameObjArr.length; i++) {
        if (frameObj.pluginObj.id == frameObjArr[i].pluginObj.id) {
            var frObj = frameObjArr[i];
            if ('item' == frObj.linkType) {
                for (var j = 0; j < imgArr[frObj.id].length; j++) {
                    if (imgArr[frObj.id][j] == imgFS || imgArr[frObj.id][j] == imgPV) {
                        for (var k = 0; k < pgrArr[frObj.id]['numpages'] - 1; k++) {
                            if (k * pgrArr[frObj.id]['len'] <= j && j < (k + 1) * pgrArr[frObj.id]['len']) {
                                fillImageList(frObj.id, k * pgrArr[frObj.id]['len']);
                                break;
                            }
                        }
                    }
                }
            } else if (frObj.isMarkCur && frObj.curItemId != imgFS) {
                fillImageList(frObj.id, pgrArr[frObj.id]['from']);
            }
        }
    }
}


/**
 * Item List Interface js
 */
/**
 * On load event
 */
function loader()
{
    for (var i = 0; i < frameObjArr.length; i++) {
        frameObjArr[i].onLoad();
    }
}
addWindowOnLoad(loader);

/**
 * RegExp templates
 */
var number_re = new RegExp("[^0-9]", "g"),
    weight_re = new RegExp("([+\-]?)[^0-9\.+\-]*([0-9\.]+)(%?)", "i"),
    price_re  = new RegExp("([+\-]?)[^0-9\.+\-]*([0-9\.]+)(%?)", "i"),
    custom_price_re = new RegExp("[0-9]*\.?[0-9]?[0-9]?");

/**
 * Array of timers
 */
var rotateTimerArr = new Array();
var processItemsTimerArr = new Array();

/**
 * Array of plugin objects, plugin index array, add method, constructor
 */
var pluginObjArr = new Array(),
    _pluginIdArr = new Array();
function addPluginObj(id, curItemId)
{
    if ('undefined' == typeof(_pluginIdArr[id])) {
        var indx = pluginObjArr.length;
        pluginObjArr[indx] = new pluginObj(id, curItemId);
        _pluginIdArr[id] = indx;
    } else {
        var indx = _pluginIdArr[id];
        pluginObjArr[indx].curItemId = curItemId;
    }
    return pluginObjArr[indx];
}
function getPluginObjById(id)
{
    return pluginObjArr[_pluginIdArr[id]];
}
function pluginObj(id, curItemId)
{
    this.id        = id; // id = num
    this.cmdPrefix = 'm' + id + ':';
    this.curItemId = curItemId;
    /**
     * Array of item objects, store
     */
    this.itemObjArr = new Array();
    this._itemIdArr = new Array();
}

/**
 * Item constructor
 */
function itemObj(id, price, weight, minqty, maxqty, options, discount, complex)
{
    this.id     = id;
    this.price  = this.oprice  = price  ? parseFloat(price) : 0;
    this.weight = this.oweight = weight ? parseFloat(weight) : 0;
    this.minqty = minqty ? parseInt(minqty) : 0;
    this.maxqty = maxqty ? parseInt(maxqty) : 999999;
    this.options = options;
    this._checkTimerOptions = function()
    {
        this.hasTimerOptions = false;
        for (var i = 0; i < this.options.length; i++) {
            if ('text' == this.options[i].type || 'price' == this.options[i].type ||
                'number' == this.options[i].type || 'weight' == this.options[i].type)
            {
                this.hasTimerOptions = true;break;
            }
        }
    }
    this._checkTimerOptions();
    this.discount = discount;
    this.complex = complex;
    this.msgArr = new Array();
    /**
     *  Update values
     */
    this.assign = function(price, weight, minqty, maxqty, options, discount, complex)
    {
        if (price)  this.price  = this.oprice  = parseFloat(price);
        if (weight) this.weight = this.oweight = parseFloat(weight);
        if (minqty) this.minqty = parseInt(minqty);
        if (maxqty) this.maxqty = parseInt(maxqty);
        if (options.length > 0) {
            this.options = options;
            this.hasTimerOptions = true;// because oprice can be overwritten by another frame
        }
        if ('object' == typeof(discount)) this.discount = discount;
        if ('object' == typeof(complex))  this.complex  = complex;
        this.msgArr = new Array();
    }
}

/**
 * Option constructor
 */
function optionObj(id, type, required, minsel, maxsel, title, name, grid_dim)
{
    this.id       = id;
    this.type     = type;
    this.required = required;
    this.minsel   = minsel;
    this.maxsel   = maxsel;
    this.title    = title;
    this.name     = name;
    var t = grid_dim.split('/');
    this.grid_dim = t[0] ? parseInt(t[0]) : 0;
    this.grid_dim_max = t[1] ? parseInt(t[1]) : 0;
}

/**
 * Discount constructor
 */
function discountObj(rangesBy, unit, ranges)
{
    this.rangesBy = rangesBy;
    this.unit     = unit;
    this.ranges   = new Array();
    for (var i = 0; i < ranges.length / 3; i++) {
        this.ranges[i] = {rmin: ranges[i * 3], rmax: ranges[i * 3 + 1], amount: ranges[i * 3 + 2]};
    }
    this.calc = function(price, qty)
    {
        if (qty <= 0) return 0;
        var percentv = 0, absv = 0, overv = 0;
        for (var i = 0; i < this.ranges.length; i++) {
            var range = this.ranges[i];
            if ('cost' == this.rangesBy) {
                var inRange = price >= range.rmin && price <= range.rmax;
            } else {
                var inRange = qty >= range.rmin && qty <= range.rmax;
            }
            if (inRange) {
                switch (this.unit) {
                    case '%':percentv += range.amount;break;
                    case '$':absv += range.amount;break;
                    case '$=':overv = range.amount;break;
                }
            }
        }
        if (overv) {
            price = overv;
        } else {
            price = price * (1.0 - percentv / 100.0) - absv;
        }
        if (price < 0) price = 0.00;
        // round to two decimals
        price = Math.round(price * 100) / 100;
        return price;
    }
}

/**
 * Array of frame objects, frame index array, add method, constructor
 */
var frameObjArr = new Array(),
    _frameIdArr = new Array();
function addFrameObj(id, linkType, isMarkCur, pluginObj, multibuy)
{
    if ('undefined' == typeof(_frameIdArr[id])) {
        var indx = frameObjArr.length;
        frameObjArr[indx] = new frameObj(id, linkType, isMarkCur, pluginObj, multibuy);
        _frameIdArr[id] = indx;
    } else {
        var indx = _frameIdArr[id];
    }
    return frameObjArr[indx];
}
function getFrameObjById(id)
{
    return frameObjArr[_frameIdArr[id]];
}
function frameObj(id, linkType, isMarkCur, pluginObj, multibuy)
{
    this.id        = id;
    this.linkType  = linkType;  // Included interface link_type property
    this.isMarkCur = isMarkCur; // Included interface mark_current property
    this.pluginObj = pluginObj;
    this.curItemId = 0;
    this.multibuy  = multibuy ? 1 : 0;
    /**
     * Refresh frame by Ajax
     */
    this.refresh = function(args, shownd, ctrl)
    {
        if (ctrl) {
            showWaitWnd('Please wait...', false);
        } else {
            clearInterval(rotateTimerArr[this.id]);
            clearInterval(processItemsTimerArr[this.id]);
        }
        AjaxFrameRefresh(this.id, args, shownd, false, ctrl);
    }
    /**
     * Array of item objects, links on plugin store
     */
    this.itemObjArr = pluginObj.itemObjArr;
    this._itemIdArr = pluginObj._itemIdArr;
    this.addItemObj = function(id, price, weight, minqty, maxqty, options, discount, complex)
    {
        if ('undefined' == typeof(this._itemIdArr[id])) {
            var indx = this.itemObjArr.length;
            this.itemObjArr[indx] = new itemObj(id, price, weight, minqty, maxqty, options, discount, complex);
            this._itemIdArr[id] = indx;
        } else {
            var indx = this._itemIdArr[id];
            this.itemObjArr[indx].assign(price, weight, minqty, maxqty, options, discount, complex);
        }
        return this.itemObjArr[indx];
    }
    this.getItemObjById = function(itemId)
    {
        return this.itemObjArr[this._itemIdArr[itemId]];
    }
    /**
     * Array of included item objects, complex item support
     */
    this.incItemObjArr = new Array();
    this._incItemIdArr = new Array();
    this.addIncItemObj = function(pid, id, price, weight, minqty, maxqty, qoh, discount)
    {
        if ('undefined' == typeof(this._incItemIdArr[pid])) {
            this.incItemObjArr[pid] = new Array();
            this._incItemIdArr[pid] = new Array();
        }
        if ('undefined' == typeof(this._incItemIdArr[pid][id])) {
            var indx = this.incItemObjArr[pid].length;
            this.incItemObjArr[pid][indx] = new itemObj(id, price, weight, minqty, maxqty, '', discount, '');
            this.incItemObjArr[pid][indx].qoh = qoh ? parseInt(qoh) : 999999;
            this._incItemIdArr[pid][id] = indx;
        } else {
            var indx = this._incItemIdArr[pid][id];
            this.incItemObjArr[pid][indx].assign(price, weight, minqty, maxqty, '', discount, '');
            if (qoh) this.incItemObjArr[pid][indx].qoh = parseInt(qoh);
        }
        return this.incItemObjArr[pid][indx];
    }

    this.clearIncItems = function()
    {
        this.incItemObjArr = new Array();
        this._incItemIdArr = new Array();
    }

    /**
     * Check qty constraints, individual (min amount, qoh) and complex, apply options changing
     */
    this.processItems = function(applyOptions)
    {
        for (var i = 0; i < this.itemObjArr.length; i++) {
            this.processItem(this.itemObjArr[i].id, applyOptions);
        }
    }
    this.processItem = function(itemId, applyOptions)
    {
        var itemObj = this.getItemObjById(itemId);
        if (!itemObj) return true;
        // apply options
        if (itemObj.hasTimerOptions || applyOptions) {this.applyItemOptions(itemObj.id);}
        // prepare qty, msg, price, weight
        var price = itemObj.oprice, weight = itemObj.oweight,
            emsg = getFrameElementById(this.id, 'msg_' + itemObj.id),
            eqty = getFrameElementById(this.id, 'qty_' + itemObj.id);
        if (!emsg || !eqty) return true;
        var msgArr = new Array(),
            qty = parseInt('0' + eqty.value.toString().replace(number_re, ''), 10);
        if (eqty.value != qty) eqty.value = qty;
        // complex support, process included items
        if (this.incItemObjArr[itemObj.id]) {
            var snum = sqty = 0;
            for (var j = 0; j < this.incItemObjArr[itemObj.id].length; j++) {
                var incItemObj = this.incItemObjArr[itemObj.id][j];
                    eiqty = getFrameElementById(this.id, 'qty_' + incItemObj.id + '_' + itemObj.id),
                    iqty = eiqty ? parseInt('0' + eiqty.value.toString().replace(number_re, ''), 10) : 0,
                    siqty = iqty * qty;
                if (eiqty.value != iqty) eiqty.value = iqty;
                snum += iqty > 0 ? 1 : 0;
                sqty += iqty;
                if (incItemObj.minqty > incItemObj.maxqty) {
                    msgArr[msgArr.length] = 'Included #' + (j + 1) + ': Out of stock.';
                } else if (incItemObj.minqty > iqty) {
                    msgArr[msgArr.length] = 'Included #' + (j + 1) + ': Min qty for this item is ' + incItemObj.minqty + '.';
                } else if (iqty > incItemObj.maxqty) {
                    msgArr[msgArr.length] = 'Included #' + (j + 1) + ': Max qty for this item is ' + incItemObj.maxqty + '.';
                } else if (siqty > incItemObj.qoh) {
                    msgArr[msgArr.length] = 'Included #' + (j + 1) + ': Max qty for this item is ' + Math.ceil(incItemObj.qoh / qty) + '.';
                }
                price  += (incItemObj.discount ? incItemObj.discount.calc(incItemObj.oprice, iqty) : incItemObj.oprice) * iqty;
                weight += incItemObj.oweight * iqty;
            }
            with (itemObj.complex) {
                if (minnum && snum < minnum) msgArr[msgArr.length] = '# of Included should be >= ' + minnum + '.';
                if (maxnum && snum > maxnum) msgArr[msgArr.length] = '# of Included should be <= ' + maxnum + '.';
                if (minqty && sqty < minqty) msgArr[msgArr.length] = 'Total Qty should be >= ' + minqty + '.';
                if (maxqty && sqty > maxqty) msgArr[msgArr.length] = 'Total Qty should be <= ' + maxqty + '.';
            }
        }
        // check qty
        if ((!this.multibuy || 0 != qty) && itemObj.maxqty != -2) {
            if (itemObj.minqty > itemObj.maxqty) {
                msgArr[msgArr.length] = 'Out of stock.';
            } else if (itemObj.minqty > qty) {
                msgArr[msgArr.length] = 'Min order qty for this item is ' + itemObj.minqty + '.';
            } else if (qty > itemObj.maxqty) {
                msgArr[msgArr.length] = 'Max order qty for this item is ' + itemObj.maxqty + '.';
            }
        }
        // show message
        if (msgArr.join('') != itemObj.msgArr.join('')) {
            itemObj.msgArr = msgArr;
            emsg.innerHTML = itemObj.msgArr.join('<br/>');
            emsg.style.display = itemObj.msgArr.length ? '' : 'none';
            for (var j = 0; j < 3; j++) {
                var ectl = getFrameElementById(this.id, 'ectl' + j + '_' + itemObj.id);
                if (ectl) {
                    ectl.disabled = itemObj.msgArr.length > 0;
                    ectl.setAttribute('ajaxDisabled', itemObj.msgArr.length > 0 ? 'yes' : 'no');
                }
            }
        }
        // show new price, weight
        if (itemObj.discount) price = itemObj.discount.calc(price, qty > 0 ? qty : 1);
        var eprice  = getFrameElementById(this.id, 'price_' + itemObj.id),
            fprice  = currencyFormat(price, this.id),
            eweight = getFrameElementById(this.id, 'weight_' + itemObj.id),
            fweight = numberFormat(weight, this.id),
            etotal = getFrameElementById(this.id, 'total_' + itemObj.id),
            ftotal = currencyFormat(price*qty, this.id);

        if (eprice && eprice.innerHTML != fprice) {
            eprice.innerHTML = fprice;
        }
        if (eweight && eweight.innerHTML != fweight) {
            eweight.innerHTML = fweight;
        }
        if (etotal && etotal.value != ftotal) {
            etotal.value = ftotal;
        }
        return itemObj.msgArr.length == 0;
    }
    /**
     * Apply new curren item
     */
    this.applyCurItem = function(itemId)
    {
        if (itemId) this.pluginObj.curItemId = itemId;
        this.markCurItem();
        for (var i = 0; i < frameObjArr.length; i++) {
            if (this.pluginObj.id == frameObjArr[i].pluginObj.id && this.id != frameObjArr[i].id) {
                if ('item' == frameObjArr[i].linkType) {
                    frameObjArr[i].refresh('ajaxitem=' + this.pluginObj.curItemId);
                } else {
                    frameObjArr[i].markCurItem();
                }
            }
        }
    }
    /**
     * Highlight current item
     * +-+---+----+---+
     * |#|img|main|img|
     * +-+---+----+---+
     */
    this.markCurItem = function()
    {
        var curItemId = this.pluginObj.curItemId,
            oldItemId = this.curItemId;
        this.curItemId = curItemId;
        if (!this.isMarkCur || curItemId == oldItemId) return;
        var tdArr = new Array(),
            e, borderLeft = 0;
        for (var i = 0; i < 4; i++) {
            tdArr[i] = getFrameElementById(this.id, 'td' + i + '_' + curItemId);
            if (tdArr[i]) {
                _resetBorderStyle(tdArr[i]);
                tdArr[i].style.borderLeft   = 'none';
                tdArr[i].style.borderTop    = '2px dotted';
                tdArr[i].style.borderRight  = 'none';
                tdArr[i].style.borderBottom = '2px dotted';
                if (!borderLeft) {
                    borderLeft = 1;
                    tdArr[i].style.borderLeft = '2px dotted';
                }
            }
            e = getFrameElementById(this.id, 'td' + i + '_' + oldItemId);
            if (e) {
                _resetBorderStyle(e);
                ostyle = e.getAttribute('ostyle');
                if (-1 != ostyle.indexOf('border-left:none'))   e.style.borderLeft   = 'none';
                if (-1 != ostyle.indexOf('border-top:none'))    e.style.borderTop    = 'none';
                if (-1 != ostyle.indexOf('border-right:none'))  e.style.borderRight  = 'none';
                if (-1 != ostyle.indexOf('border-bottom:none')) e.style.borderBottom = 'none';
            }
        }
        if (tdArr[3]) {
            tdArr[3].style.borderRight = '2px dotted';
        } else if (tdArr[2]) {
            tdArr[2].style.borderRight = '2px dotted';
        }
    }
    /**
     * Change weight and price by options changing
     */
    this.applyItemOptions = function(itemId)
    {
        var frameId = this.id,
            itemObj = this.getItemObjById(itemId),
            price   = itemObj.price,
            weight  = itemObj.weight;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i],
                optId = opt.id,
                value = '';
            switch (opt.type) {
                case 'enum':
                case 'tree':
                    var j, vals = new Array();
                    var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                    if (el) {
                        vals.push(el.value);
                    } else {
                        var els = getControlsByFrame(frameId, 'product_options[' + itemId + '][' + optId + '][]');
                        for (j = 0; j < els.length; j++) {
                            if (els[j].checked) {
                                vals.push(els[j].value);
                            }
                        }
                    }
                    if (vals.length == 0) {
                        break;
                    }
                    var a, _price, _weight, k, m, vs, v;
                    for (j = 0; j < vals.length; j++) {
                        a = vals[j].split('||');
                        // calc price
                        if (opt.type == 'tree')
                            _price  = a[2] ? a[2] : 0;
                        else
                            _price  = a[1] ? a[1] : 0;
                        if (_price) {
                            vs = _price.split(':');
                            for (k = 0; k < vs.length; k++) {
                                m = vs[k].match(price_re);
                                if (m) {
                                    v = parseFloat(m[2]);
                                    if ('%' == m[3]) v = price * v / 100;
                                    if (m[1]) {
                                        if ('-' == m[1]) v *= -1.00;
                                        price += v;
                                    } else {
                                        price = v;
                                    }
                                }
                            }
                        }
                        // calc weight
                        if (opt.type == 'tree')
                            _weight = a[3] ? a[3] : 0;
                        else
                            _weight = a[2] ? a[2] : 0;
                        if (_weight)  {
                            var vs = _weight.split(':');
                            for (k = 0; k < vs.length; k++) {
                                m = vs[k].match(weight_re);
                                if (m) {
                                    v = parseFloat(m[2]);
                                    if ('%' == m[3]) v = weight * v / 100;
                                    if (m[1]) {
                                        if ('-' == m[1]) v *= -1.00;
                                        weight += v;
                                    } else {
                                        weight = v;
                                    }
                                }
                            }
                        }
                    }
                    if (opt.type == 'enum' && vals.length && vals[0]) {
                        var a = vals[0].split('||');
					    if (optionImages && optionImages[itemId + ':' + optId + ':' + a[0]]) {
					        var p = optionImages[itemId + ':' + optId + ':' + a[0]];
					        showImageInFields(p[1], p[0]);
					    }
					    if (opt.grid_dim && opt.grid_dim == opt.grid_dim_max && itemObj.maxqty != 999999) {
					        itemObj.maxqty = a[3];
					    }
                    }
                    break;
                case 'price':
                    var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                    if (el) {
                        var m = el.value.match(custom_price_re);
                        value = m ? parseFloat(m) : 0;
                        if (isNaN(value)) value = 0;
                        price += value/frameLocale[this.id].rate;
                        if (el.focused === false) {
                            el.value = formatPrice(value);
                        }
                    }
                    break;
                case 'text':
                    var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                    if (el) price += this.calcTextOptionCost(el, 0);
                    break;
                case 'number':
                    if (opt.minsel < 0) break;
                    var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                    if (el) price += this.calcNumOptionCost(el);
                    break;
                case 'weight':
                    var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                    if (el && el.value != '') weight = parseFloat(el.value);
                    break;
            }
        }
        itemObj.oprice  = price;
        itemObj.oweight = weight;
    }
    /**
     * Check options
     */
    this.checkItemOptions = function(itemId)
    {
        var frameId = this.id,
            itemObj = this.getItemObjById(itemId);
        if (!itemObj) return true;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i],
                optId = opt.id;
            // check for too long text options
            if ('text' == opt.type) {
                var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                if (!this.calcTextOptionCost(el, 1)) {
                    alert('Entered text is too long');
                    el.focus();
                    return false;
                }
            }
            if ('number' == opt.type || 'weight' == opt.type) {
                var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                var parse = 'number' == opt.type ? parseInt : parseFloat;
                if (el.value == '') {
                    alert('Please fill in '+ opt.name + '.');
                    el.focus();
                    return false;
                } else if (isNaN(parse(el.value))) {
                    alert('Please enter a number for '+ opt.name + '.');
                    el.focus();
                    return false;
                } else if (parse(el.value) > opt.maxsel || parse(el.value) < opt.minsel) {
                    alert('Please enter a value between '+opt.minsel+' and '+opt.maxsel+' for '+ opt.name + '.');
                    /*if (parse(el.value) > opt.maxsel)
                        el.value  = opt.maxsel;
                    else if (parse(el.value) < opt.minsel)
                        el.value  = opt.minsel;
                    else
                        el.value = parse(el.value);*/
                    el.focus();
                    return false;
                }
            }

            if ('date' == opt.type) {
                var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                if (!validateCalendarValue(el.value, true)) {
                    alert('Please enter a date in valid format (MM/DD/YYYY) in '+ opt.name + '.');
                    if (el.type != 'hidden')
                        el.focus();
                    else
                        document.getElementById(el.id+'_month').focus();
                    return false;
                } else {
                	var d = new Date();
                	var today_date = new Date(d.getFullYear(),d.getMonth(),d.getDate());
                	var allow_dates = el.getAttribute('data-allow_dates');
                	var start_date = today_date;
                	var stop_date = today_date;
                	var only_month = document.getElementById(el.id+'_day') || el.type != 'hidden' ? false:true;
                	switch (allow_dates) {
                       case 'all':
                           start_date = el.getAttribute('data-year_start')? new Date('01/01/'+el.getAttribute('data-year_start')): today_date;
                           stop_date = el.getAttribute('data-year_stop')? new Date('12/31/'+el.getAttribute('data-year_stop')): today_date;
                           break;
                       case 'past':
                           start_date = el.getAttribute('data-year_start')? new Date('01/01/'+el.getAttribute('data-year_start')): today_date;
                           if (only_month)
                            stop_date =  new Date((stop_date.getMonth()-1)+'/31/'+stop_date.getFullYear());
                           else
                            stop_date = stop_date.setDate(stop_date.getDate() -1);
                           break;
                       case 'past_today':
                           start_date = el.getAttribute('data-year_start')? new Date('01/01/'+el.getAttribute('data-year_start')): today_date;
                           if (only_month)
                            stop_date = new Date((stop_date.getMonth())+'/31/'+stop_date.getFullYear());
                           break;
                       case 'future':
                           if (only_month)
                            start_date = new Date((start_date.getMonth() +1) +'/01/'+el.getAttribute('data-year_start'));
                           else
                            start_date = start_date.setDate(start_date.getDate() +1);
                           stop_date = el.getAttribute('data-year_stop')? new Date('12/31/'+el.getAttribute('data-year_stop')): today_date;
                           break;
                       case 'future_today':
                           if (only_month)
                            start_date = new Date((start_date.getMonth()) +'/01/'+el.getAttribute('data-year_start'));
                           stop_date = el.getAttribute('data-year_stop')? new Date('12/31/'+el.getAttribute('data-year_stop')): today_date;
                           break;
                    }

                	if (el.value != '') {
                		curr_date = new Date(el.value);
                		if (curr_date > stop_date || curr_date < start_date) {
                		  var today = only_month?'this month':'today';

                		  switch (allow_dates) {
                		  	   case 'all':
                		  	       alert('Please enter a date in year range from ' + year_start +' to ' +year_stop + ' to '+ opt.name +'.');
                		  	       return false;
                		  	       break;
                		  	   case 'past':
                		  	       alert('Please enter a date in the past to '+ opt.name +'.');
                		  	       return false;
                		  	       break;
                		  	   case 'past_today':
                		  	       alert('Please enter a date in the past or ' + today + ' to '+ opt.name +'.');
                		  	       return false;
                		  	       break;
                		  	   case 'future':
                		  	       alert('Please enter a date in the future to '+ opt.name +'.');
                		  	       return false;
                		  	       break;
                		  	   case 'future_today':
                                   alert('Please enter a date in the future or ' + today + ' to '+ opt.name +'.');
                                   return false;
                                   break;
                		  }
                		}
                	}
                }
            }

            // check required
            var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId),
                otitle = 'none' == opt.title ? '' : opt.title;
            if (el) {
                if (opt.required || '1' == el.getAttribute('required')) {
                	if ('price' == opt.type) {
                        if (!validatePrice(el.value)) {
                          alert('Please fill in '+ opt.name + '.');
                          el.value = formatPrice(el.value);
                          if ('undefined' != typeof el.focus) el.focus();
                          return false;
                        }
                    }else if ('text' == opt.type) {
                		if (trim(el.value) == '') {
                		  alert('Please fill in '+ opt.name + '.');
                		  if ('undefined' != typeof el.focus) el.focus();
                          return false;
                		}
                	} else if ('file' == opt.type) {
                	    if (el.value == '' && 'hidden' != el.type) {
                	    	alert('Please select a file for ' + opt.name + '.');
                	    	if ('undefined' != typeof el.focus) el.focus();
                            return false;
                	    }
                    } else if ('enum' == opt.type || 'tree' == opt.type) {
                    	var str_to_check = el.value == undefined ? '' :el.value;
		                if ('tree' == opt.type) {
		                    var value_parts = el.value.split('||');
		                    if (value_parts[1])
		                      str_to_check = value_parts[1];
		                }
                    	if ('[' == str_to_check.substr(0, 1) || '1' == el.getAttribute('required')) {
		                    alert('Please select an option  for ' + otitle + '.');
		                    if ('tree' == opt.type) {
		                        var els = document.getElementsByName('option_path_' + itemId + '_' + optId);
		                        el = els[els.length - 1];
		                    }
		                    if ('undefined' != typeof el.focus) el.focus();
	                        return false;
                    	}
                	} else if ('date' == opt.type) {
                        if (!validateCalendarValue(el.value,false)) {
	                        alert('Please fill in '+ opt.name + '.');
	                        if (el.type != 'hidden')
	                            el.focus();
	                        else
	                            document.getElementById(el.id+'_month').focus();
	                        return false;
                        }
                    }
                }
            } else {
                var checked = 0,
                    vals = new Array(),
                    elms = getControlsByFrame(frameId, 'product_options[' + itemId + '][' + optId + '][]');
                for (var j = 0; j < elms.length; j++) {
                    if (elms[j].checked && '[' != elms[j].value.substr(0, 1)) {
                        checked++;
                    }
                }
                var msg = '';
                if (opt.minsel == opt.maxsel && opt.minsel != checked) {
                    msg = 1 == opt.minsel ? 'one option' : opt.minsel + 'options';
                } else if (opt.minsel > 0 &&  opt.maxsel > 0 &&
                    opt.minsel != opt.maxsel && (checked < opt.minsel || checked > opt.maxsel)) {
                    msg = 'between ' + opt.minsel + ' and ' + opt.maxsel + ' options';
                } else if (checked < opt.minsel) {
                    msg = 'at least ' + (1 == opt.minsel ? 'one option' : opt.minsel + ' options');
                } else if (opt.maxsel > 0 && checked > opt.maxsel) {
                    msg = 'no more that ' + (1 == opt.maxsel ? 'one option' : opt.maxsel + ' options');
                }
                if (msg) {
                    msg = 'Please select ' + msg;
                    msg += ' for ' + otitle + '. ';
                    msg += 'You have selected ' + (checked ? (1 == checked ? 'one option.' : checked + ' options.') : 'no options.');
                    alert(msg);
                    if ('undefined' != typeof elms[0].focus) elms[0].focus();
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * Display multi-upload window if needed
     */
    this.checkMultiUpload = function(itemId, f, cmd, ajax)
    {
        var frameId = this.id,
            itemObj = this.getItemObjById(itemId);
        if (!itemObj) return true;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i],
                optId = opt.id;
            if ('file' == opt.type) {
                var id = 'opt_' + itemId + '_' + optId;
                var el = getFrameElementById(frameId, id);
                if (el.type == 'hidden' && el.value == '') {
                    var name = cmd.split('_')[0], text = 'Add to Cart';
                    if ('addToWish' == name) text = 'Add to Wish List';
                    else if ('addToGift' == name) text = 'Add to Gift List';
                    popupUploadFilesShow('opt_' + itemId, optId,
                        {max: parseInt(el.getAttribute('data-max')),
                        enable_java: parseInt(el.getAttribute('data-enable_java')),
                        default_uploader: el.getAttribute('data-default_uploader'),
                        max_size: parseInt(el.getAttribute('data-max_size')),
                        required: parseInt(el.getAttribute('required')),
                        downscale: parseInt(el.getAttribute('data-downscale')),
                        downscale_width: parseInt(el.getAttribute('data-downscale_width')),
                        downscale_height: parseInt(el.getAttribute('data-downscale_height')),
                        allow: el.getAttribute('data-allow'),
                        jpeg_quality: parseInt(el.getAttribute('data-jpeg_quality')),
                        sep_dir: true,
                        button_text: text,
                        title: el.getAttribute('data-title')},
                        function(id, ctl, num) {
                            el.value = num;
                            submitCmd(f, cmd, ajax, num == 0 ? 'Please wait...' : null);
                        } );
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * Are there any files to upload?
     */
    this.hasFiles = function(itemId)
    {
        var frameId = this.id,
            itemObj = this.getItemObjById(itemId);
        if (!itemObj) return false;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i],
                optId = opt.id;
            if ('file' == opt.type) {
                var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
                if (el.value) return true;
            }
        }
        return false;
    }
    /**
     * Callback for upload completion notification
     */
    this.uploadDone = function(itemId)
    {
    }
     /**
     * number price
     */
    this.calcNumOptionCost = function(el)
    {
    	if (el.getAttribute('data-ranges') == '') return 0;
        var ranges = el.getAttribute('data-ranges').split(';');
        var price = 0;
        for (var i = 0; i < ranges.length; i++) {
        	if (ranges[i] == '') continue;
        	var rv = ranges[i].split(':');
        	if (el.value >= rv[0])
        	   price = parseFloat(rv[1])*parseInt(el.value);
        }
        return price;
    }
    /**
     * Word counter, calc option cost
     */
    this.calcTextOptionCost = function(el, validate)
    {
        var frameId = this.id,
            el1 = document.getElementById(el.id + '_counter');
        var s, r, v = el.value, v1 = v, warn = false;
        if ('words' == el.getAttribute('data-calc_cost')) {
            var free_words = el.getAttribute('data-free_words') ? parseFloat(el.getAttribute('data-free_words')) : 0,
                flat_rate  = el.getAttribute('data-flat_rate') ? parseFloat(el.getAttribute('data-flat_rate')) : 0,
                word_cost  = el.getAttribute('data-word_cost') ? parseFloat(el.getAttribute('data-word_cost')) : 0,
                num_words  = el.getAttribute('data-num_words') ? parseFloat(el.getAttribute('data-num_words')) : 0,
                max_words  = el.getAttribute('data-max_words') ? parseInt(el.getAttribute('data-max_words')) : 0,
                max_chars  = el.getAttribute('data-max_chars_w') ? parseInt(el.getAttribute('data-max_chars_w')) : 0,
                num_re = /(^|\W+)\d+(\W+|$)(\d+(\W+|$))+/g,
                m = v.match(num_re),
                num_count = m ? m.length : 0;
            v = v.replace(num_re, ' ');
            m = v.match(/\S(\S+)/g);
            var word_count = m ? m.length : 0;
            m = el._excl_regexp ? v.match(new RegExp('\\b(' + el._excl_regexp + ')\\b', 'ig')) : null;
            var excl_count = m ? m.length : 0,
                words = word_count + num_count * num_words - excl_count;
            s = words.toString() + (words == 1 ? ' word' : ' words');
            if (max_words) {
                s += ' (max ' + max_words.toString() + ')';
                if (words > max_words) warn = true;
            }
            if (max_chars) {
                v1 = v1.replace(/[\r\n]/g, '');
                var chars = v1 ? v1.length : 0;
                s += ', ' + chars.toString() + (chars == 1 ? ' character' : ' characters') +
                    ' (max ' + max_chars.toString() + ')';
                if (chars > max_chars) warn = true;
            }
            r = (words - free_words) * word_cost;
            z = el.value.match(/[\S+]/i);
            if (z && z.length>0)
            {
                r += flat_rate;
            }
        } else if ('chars' == el.getAttribute('data-calc_cost')) {
            var free_chars  = el.getAttribute('data-free_chars') ? parseFloat(el.getAttribute('data-free_chars')) : 0,
                flat_rate   = el.getAttribute('data-flat_rate') ? parseFloat(el.getAttribute('data-flat_rate')) : 0,
                char_cost   = el.getAttribute('data-char_cost') ? parseFloat(el.getAttribute('data-char_cost')) : 0,
                count_chars = el.getAttribute('data-count_chars'),
                max_chars   = el.getAttribute('data-max_chars_c') ? parseInt(el.getAttribute('data-max_chars_c')) : 0;
            if (count_chars == 'an') {
                v = v.replace(/[^a-z0-9]/ig, '');
            } else {
                v = v.replace(/[\r\n]/g, '');
            }
            var chars = v ? v.length : 0;
            s = chars.toString() + (chars == 1 ? ' character' : ' characters');
            if (max_chars) {
                s += ' (max ' + max_chars.toString() + ')';
                if (chars > max_chars) warn = true;
            }
            r = (chars - free_chars) * char_cost;
            if (r < 0) r = 0.00;
            if (chars>0)
            {
                r += flat_rate;
            }
        } else {
            return validate ? 1 : 0.00;
        }

        if (r < 0) r = 0.00;
        s += ', ' + currencyFormat(r, this.id);
        if (el1) {
            if (el1.innerHTML != s) el1.innerHTML = s;
            el1.style.color = warn ? '#ff0000' : '';
        }
        return validate ? !warn : r;
    }
    /**
     * Apply tree option changing
     */
    this.changeTreeOption = function(itemId, optId, ctl)
    {
        var frameId  = this.id,
            value    = ctl.value,
            required = '0';
        if ('!!!' == value.substr(0, 3)) {
            value    = value.substr(3);
            required = '1';
        }
        if ('///' == value.substr(0, 3)) {
            value = value.substr(3);
            var args = 'ajaxParentItem=' + itemId +
                '&ajaxReloadOptions[0]=' + optId + '&ajaxOptions[' + optId + ']=' +
                encodeURIComponent(value);
            this.refresh(args, true, 'div_opt_' + itemId + '_' + optId + '_' + frameId);
        } else {
            var o = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
            o.setAttribute('required', required);
            o.value = value;
            var ctls = getControlsByFrame(frameId, 'option_path_' + itemId + '_' + optId);
            for (var i = 0; i < ctls.length; i++) {
                if (ctls[i].getAttribute('data-level') > ctl.getAttribute('data-level'))
                    ctls[i].style.display = 'none';
            }
            this.processItem(itemId, 1);
        }
    }
    /**
     * Update related options in a grid
     */
    this.updateGrid = function(itemId, optId)
    {
        var frameId  = this.id;
        var args = 'ajaxParentItem=' + itemId;
        var itemObj = this.getItemObjById(itemId);
        var changedDim = 0;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i];
            if (opt.type == 'enum' && opt.grid_dim) {
                var el = getFrameElementById(frameId, 'opt_' + itemId + '_' + opt.id);
				if (!el) { // maybe there are radio buttons instead of selectBox
                	var div = getFrameElementById(frameId, 'div_opt_' + itemId + '_' + opt.id);
                	var inputs = div.getElementsByTagName('input');
                	for (var k = 0; k < inputs.length; k++) {
                		if (inputs[k].type == 'radio' && inputs[k].checked) {
                			el = inputs[k];
                			break;
                		}
                	}
                }
                args += '&ajaxOptions[' + opt.id + ']=' + el.value.split('||')[0];
	            if (opt.id == optId) {
	                changedDim = opt.grid_dim;
	            }
	        }
        }
        if (!changedDim) return;
        var controls = [];
        var j = 0;
        for (var i = 0; i < itemObj.options.length; i++) {
            var opt = itemObj.options[i];
            if (opt.type == 'enum' && opt.grid_dim > changedDim) {
                args += '&ajaxReloadOptions[' + (j++) + ']=' + opt.id;
                controls.push('div_opt_' + itemId + '_' + opt.id + '_' + frameId);
            }
        }
        if (controls.length) {
            this.refresh(args, true, controls);
        }
    }

    this.disableAddToCartByIds = function(ids)
    {
        ids = ',' + ids + ',';
        for (var i = 0; i < this.itemObjArr.length; i++) {
            for (var j = 0; j < 3; j++) {
                var ectl = getFrameElementById(this.id, 'ectl' + j + '_' + this.itemObjArr[i].id);
                if (ectl) {
                    var on = ids.indexOf(',' + this.itemObjArr[i].id + ',') != -1;
                    ectl.disabled = on ? true : false;
                    ectl.setAttribute('ajaxDisabled', on ? 'yes' : 'no');
                }
            }
        }
    }
}

/**
 *
 */
function _resetBorderStyle(e)
{
    e.style.borderWidth = '';
    e.style.borderStyle = '';
    e.style.borderColor = '';
    e.className = e.className;
}

function viewBasketItem(frameId, url)
{
    oFrameId = frameId;
    _call('popup_exec_url', [url, null, 600, 500]);
}

function applyCurItem(frameId, itemId)
{
    getFrameObjById(frameId).applyCurItem(itemId);
}

function refreshFrame(frameId, args, shownd)
{
    getFrameObjById(frameId).refresh(args, shownd);
}

function rotate(frameId, interval, startlbl, stoplbl)
{
    var els = getFrameElementsByName(frameId, 'rotate');
    if (!els[0]) return;
    if (rotateTimerArr[frameId]) {
        clearInterval(rotateTimerArr[frameId]);
        rotateTimerArr[frameId] = 0;
        els[0].innerHTML = startlbl;
    } else {
        rotateTimerArr[frameId] = setInterval('rotateTimer' + frameId + '()', interval);
        els[0].innerHTML = stoplbl;
    }
    for (var i = 1; i < els.length; i++) {
        els[i].innerHTML = els[0].innerHTML;
    }
}

function startOptionSelector(frameId, url, product_id, option_id, w, h)
{
    url += '&option_select=' + frameId + ':' + product_id + ':' + option_id;
    var size = 'width=' + w + ',height=' + h + ',scrollbars=yes,resizable=yes';
    option_wnd = openNamedWindow(url, 'option_wnd', size);
}

function getOptionValue(frameId, itemId, optId)
{
    // TODO: function does not work, need to support names ending with []
    var opts = getControlsByFrame(frameId, 'product_options[' + itemId + '][' + optId + ']');
    var e = opts[0];
    var value = '';
    if (e) {
        if (e.tagName == 'SELECT') {
            value = e.value.split('||')[0];
        } else if (e.tagName == 'INPUT' && e.type == 'radio') {
            for (var i = 0; i < opts.length; i++) {
                if (opts[i].checked) {
                    value = opts[i].value.split('||')[0];
                    break;
                }
            }
        } else {
            value = e.value;
        }
    }
    return value;
}

function setOptionValue(frameId, itemId, optId, value)
{
    // TODO: function does not work, need to support names ending with []
    // TODO: support table-like options
    var opts = getControlsByFrame(frameId, 'product_options[' + itemId + '][' + optId + ']');
    var e = opts[0];
    if (e) {
        if (e.tagName == 'SELECT') {
            value = value.toLower();
            opts = e.options;
            for (var i = 0; i < opts.length; i++) {
                var t = opts[i].value.split('||')[0];
                if (t.toLower() == value) {
                    e.selectedIndex = i;
                    break;
                }
            }
        } else if (e.tagName == 'INPUT' && e.type == 'radio') {
            value = value.toLower();
            for (var i = 0; i < opts.length; i++) {
                var t = opts[i].value.split('||')[0];
                if (t.toLower() == value) {
                    opts[i].checked = true;
                    break;
                }
            }
        } else {
            e.value = value;
        }
    }
}

function changeTreeOption(frameId, itemId, optId, ctl)
{
    getFrameObjById(frameId).changeTreeOption(itemId, optId, ctl);
}

function changeRelated(frameId, itemId)
{
    getFrameObjById(frameId).processItem(itemId, 1);
}

function updateGrid(frameId, itemId, optId)
{
    getFrameObjById(frameId).updateGrid(itemId, optId);
}

function validatePrice(value)
{
	value = trim(value);
	value = value.replace(/,/,'.');
	var price = parseFloat(value);
	if (price <= 0) return false;
	return true;
}

function formatPrice(value)
{
	var price = value;
	if (typeof(value) == 'string') {
		value = trim(value);
	    value = value.replace(/,/,'.');
	    price = parseFloat(value);
	}
    return Math.floor(price).toString()+"."+(Math.floor(price*10)%10).toString()+(Math.floor(price*100)%10).toString();
}

function submitCmd(f, cmd, ajax, wait_message)
{
	wait_message = wait_message || 'Processing files, please wait...';
    var a = cmd.split('_'), name = a[0], itemId = a[1], disable = false;
    if ('addToCart' == name || 'addToCartAddon' == name || 'addToWish' == name
    || 'addToGift' == name || 'apply' == name) {
        var frameId = getFrameByForm(f) || 1;
        var frameObj = getFrameObjById(frameId);
        if ('0' == itemId) {
            // common ctl for multibuy
            // TODO: support file options here
            var iId, eqty, qty, res = false;
            for (var i = 0; i < frameObj.itemObjArr.length; i++) {
                eqty = getFrameElementById(frameObj.id, 'qty_' + frameObj.itemObjArr[i].id);
                if (eqty) {
                    qty = parseInt('0' + eqty.value.toString().replace(number_re, ''), 10);
                    if (eqty.value != qty) eqty.value = qty;
                    if (qty > 0) {
                        res = true;
                        if (!frameObj.processItem(frameObj.itemObjArr[i].id) ||
                            !frameObj.checkItemOptions(frameObj.itemObjArr[i].id)) return false;
                    }
                }
            }
            if (!res) return false;
        } else {
            if (!frameObj.processItem(itemId) ||
                !frameObj.checkItemOptions(itemId) ||
                !frameObj.checkMultiUpload(itemId, f, cmd, ajax)) return false;
            disable = frameObj.hasFiles(itemId);
        }
    }
    if (ajax) {
        ajaxPostSubmit(f, cmd, true, disable ? wait_message : '');
        return;
    }
    f.submitAction.value = cmd;
    try {
        f.submit();
        if (disable) {
            // disableControls(f);
            showWaitWnd(wait_message, true);
        }
    }
    catch (err) {
    	alert('One of file selection fields contains an invalid value.');
    }
}

function changeMultiBuyQty(frameId, id)
{
    var qty = getFrameElementById(frameId, 'qty_'+id);
    var sel = getFrameElementById(frameId, 'sel_'+id);
    if (qty && sel) {
        sel.checked = parseInt(qty.value) > 0;
    }
}

function changeMultiBuySel(frameId, id)
{
    var qty = getFrameElementById(frameId, 'qty_'+id);
    var sel = getFrameElementById(frameId, 'sel_'+id);
    if (qty && sel) {
        if (sel.checked && parseInt(qty.value) == 0) {
            var i = getFrameObjById(frameId).getItemObjById(id);
            qty.value = i ? i.minqty : 1;
        } else if (!sel.checked && parseInt(qty.value) > 0) {
            qty.value = 0;
        }
    }
}

function layoutSelectTab(id, idx)
{
    var i = 1;
    while (true) {
        var tab = document.getElementById('LayoutTab_'+id+'_'+i);
        var body = document.getElementById('LayoutTabBody_'+id+'_'+i);
        if (!tab || !body) return;
        tab.className = i == idx ? 'TabActive' : 'TabInactive';
        body.style.display = i == idx ? '' : 'none';
        i++;
    }
}

var layoutImages = {}, layoutRotPos = {}, layoutTimers = {}, layoutImageFields = new Array();
var layoutVideos = {}, layoutVideoFields = new Array();
var layoutImageFieldsDetails = new Array();

function layoutAddImage(id, image, big_image)
{
    if (typeof(layoutImages[id]) == 'undefined') {
        layoutImages[id] = [ [image, big_image] ];
        layoutRotPos[id] = 0;
    } else {
        layoutImages[id].push([image, big_image]);
    }
    preloadImage(image);
}

function layoutAddImageField(id)
{
	layoutImageFields.push(id);
}

function layoutAddImageFieldDetails(id)
{
    layoutImageFieldsDetails.push(id);
}

function layoutRotate(id, inc)
{
    if (typeof(layoutImages[id]) == 'undefined') return;
    var num = layoutImages[id].length;
    if (num < 2) return;
    var pos = layoutRotPos[id];
    if (inc == 0) {
        var newPos;
		do {
		    newPos = Math.floor(Math.random()*num);
		} while (newPos == pos);
		pos = newPos;
	} else {
		pos += inc;
		if (pos > num-1) pos = pos % num;
		if (pos < 0) pos = num-1;
	}
    layoutRotPos[id] = pos;
    var image = layoutImages[id][pos][0];
    var bigImage = layoutImages[id][pos][1];
    var imctl = document.getElementById('LayoutImage_'+id);
    if (imctl) {
        imctl.setAttribute('data-bigimage', bigImage);
        imctl.src = image;
    }
    var ind = document.getElementById('LayoutRotInd_'+id);
    if (ind) ind.innerHTML = '\xA0\xA0' + (Number(pos)+1).toString() + '\xA0of\xA0' +
        num.toString() + '\xA0\xA0';
}

function layoutStartRotation(id, interval, random)
{
    if (typeof(layoutImages[id]) == 'undefined') return;
    if (!interval) interval = 5;
    random = random || false;
    var inc = random ? 0 : 1;
    layoutTimers[id] = setInterval(function() {layoutRotate(id, inc);}, interval*1000);
}

function layoutStopRotation(id)
{
    if (typeof(layoutTimers[id]) == 'undefined') return;
    clearInterval(layoutTimers[id]);
}

function showLargeImage(id)
{
    var img = document.getElementById(id);
    if (img.getAttribute('data-imagesize') == 'fullsize') {
        var re = /^([^\?]*)/;
    } else {
        var re = /file=([^&]*)/i;
    }
    var m = img.src.match(re);
    var filename = m ? decodeURIComponent(m[1]) : '';
    if (filename) {
	    showPopupWithImage(filename);
    }
}

var imageWindow = null;
function showPopupWithImage(filename)
{
    fadeStack.show();
	if (imageWindow) {
	   imageWindow.parentNode.removeChild(imageWindow);
	}
	var d = document.createElement('div');
	d.className = 'InfoWindow';
	imageWindow = d;
	d.onclick = function () {
	    imageWindow = null;
	    d.parentNode.removeChild(d);
	    var im = fadeStack.getUpperFade();
	    if (im) im.onclick = null;
        fadeStack.hide();
	    showElements();
	}
    var im = fadeStack.getUpperFade();
    if (im) im.onclick = d.onclick;
    var loading = document.createElement('div');
    loading.className = 'loading';
    loading.innerHTML = 'Loading...';
    d.appendChild(loading);
    var image = document.createElement('img');
    image.className = 'large';
    image.style.display = 'none';
    d.appendChild(image);
    if (useAbsPosition) {
        d.style.position = 'absolute';
    } else {
        d.style.position = 'fixed';
    }
    var width = 130;
    var height = 30;
    d.style.left = (getClientWidth() - width) / 2 + 'px';
    d.style.top = (getClientHeight() - height) / 2 + 'px';
    d.style.width = width + 'px';
    document.body.appendChild(d);
    image.onload = function() {
        loading.style.display = 'none';
        image.style.display = '';
	    var width = Math.min(is_msie() ? image.offsetWidth + 30 : image.width + 30,
            getClientWidth() - 40);
	    var height = Math.min(is_msie() ? image.offsetHeight + 30 : image.height + 30,
            getClientHeight() - 40);
        d.style.left = (getClientWidth() - width) / 2 + (useAbsPosition ? getScrollLeft() : 0) + 'px';
        d.style.top = (getClientHeight() - height) / 2 + (useAbsPosition ? getScrollTop() : 0) + 'px';
	    d.style.width = width + 'px';
	    d.style.height = height + 'px';
    }
    image.src = encodeURI(filename);
    hideElements();
}

function videothumb_close_func( frame )
{
    var items = frame.contentWindow.document.getElementsByTagName('object');
    if (!items.length) {
        items = frame.contentWindow.document.getElementsByTagName('embed');
    }
    for (var i = 0; i < items.length; i++) {
       if (typeof(items[i].Reset) == 'function')
           items[i].Reset();
       items[i].parentNode.removeChild(items[i]);
    }
}

function layoutAddVideo(id, image, file, popup_url)
{
    if (typeof(layoutVideos[id]) == 'undefined') {
        layoutVideos[id] = [{'image': image, 'file': file, 'popup_url': popup_url}];
        layoutRotPos[id] = 0;
    } else {
        layoutVideos[id].push({'image': image, 'file': file, 'popup_url': popup_url});
    }
}

function layoutAddVideoField(id)
{
    layoutVideoFields.push(id);
}

function layoutRotateVideo(id, inc)
{
    if (typeof(layoutVideos[id]) == 'undefined') return;
    var num = layoutVideos[id].length;
    if (num < 2) return;
    var pos = layoutRotPos[id];
    pos += inc;
    if (pos < 0) pos = num-1;
    if (pos > num-1) pos = 0;
    layoutRotPos[id] = pos;
    var image = layoutVideos[id][pos]['image'];
    var popup_url = layoutVideos[id][pos]['popup_url'];
    var imctl = document.getElementById('LayoutVideo_'+id);
    if (imctl) {
    	imctl.src = image;
    	if (imctl.parentNode.href != '')
    	   imctl.parentNode.href = popup_url;
    }
    var ind = document.getElementById('LayoutRotInd_'+id);
    if (ind) ind.innerHTML = '\xA0\xA0' + (Number(pos)+1).toString() + '\xA0of\xA0' +
        num.toString() + '\xA0\xA0';
}

function layoutStartVideoRotation(id, interval)
{
    if (typeof(layoutVideos[id]) == 'undefined') return;
    if (!interval) interval = 5;
    layoutTimers[id] = setInterval(function() {layoutRotateVideo(id, 1);}, interval*1000);
}

function showVideoInFields(item_id, new_filename, file_type)
{
	for (var k = 0; k < layoutVideoFields.length; k++) {
        var videoId = layoutVideoFields[k]['id'];
        if (videoId.search(item_id) > -1)
	        if (file_type == "video-flv-player") {
                try {
                    if ($f('flash_' + videoId).getState() > -1) {
                        var autoplay = $f('flash_' + videoId).getCommonClip().autoPlay;
                        $f('flash_' + videoId).setClip({'url': new_filename});
                        if (autoplay) $f('flash_' + videoId).play();
                    }else {
                         if (typeof(window["createVideoPlayer"+videoId]) == "function")
                                   window["createVideoPlayer"+videoId](new_filename);
                    }
                } catch(err) {
                    if (typeof(window["createVideoPlayer"+videoId]) == "function")
                       window["createVideoPlayer"+videoId](new_filename);
                }
	        } else {
	            createVideoPlayer(layoutVideoFields[k], new_filename);
	        }
    }
}

function createVideoPlayer(videoFieldInfo, filename)
{
    if (navigator.appVersion.indexOf('Mac') != -1)
        var playerCode = '<object codebase="http://www.apple.com/qtactivex/qtplugin.cab" '
        + 'classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="'+videoFieldInfo['width']+'" height="'+videoFieldInfo['height']+'">'
        + '<param name="src" value="'+videoFieldInfo['baseurl']+filename+'"/>'
        + '<param name="scale" value="aspect"/>'
        + '<param name="type" value="video/quicktime"/>'
        + '<param name="kioskmode" value="'+(videoFieldInfo['uimode'] == 'full') +'"/>'
        + '<param name="controller" value="'+(videoFieldInfo['uimode'] == 'none') +'"/>'
        + '<param name="autoplay" value="'+videoFieldInfo['autostart'] +'"/>'
        + '<param name="loop" value="'+(videoFieldInfo['loop'] == 1)+'"/>'
        + '<embed pluginspage="http://www.apple.com/quicktime/download/"'
        + 'type="video/quicktime" width="'+videoFieldInfo['width']+'" height="'+videoFieldInfo['height']+'"'
        + 'autoplay="'+videoFieldInfo['autostart'] +'"'
        + 'loop="'+videoFieldInfo['loop']+'"'
        + 'controller="'+(videoFieldInfo['uimode'] == 'none')+'"'
        + 'kioskmode="'+(videoFieldInfo['uimode'] == 'full')+'"'
        + 'scale="aspect" '
        + 'src="'+videoFieldInfo['baseurl']+filename+'">'
        + '</embed>'
        + '</object>';
    if (navigator.appVersion.indexOf('Mac') == -1)
        var playerCode = '<object codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"'
        + 'standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"'
        + 'classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'+videoFieldInfo['width']+'" height="'+videoFieldInfo['height']+'">'
        + '<param name="URL" value="'+videoFieldInfo['baseurl']+filename+'"/>'
        + '<param name="animationatStart" value="true"/>'
        + '<param name="displaySize" value="1"/>'
        + '<param name="stretchToFit" value="1"/>'
        + '<param name="uiMode" value="'+videoFieldInfo['uimode']+'"/>'
        + '<param name="autoStart" value="'+videoFieldInfo['autostart'] +'"/>'
        + '<param name="playCount" value="'+(videoFieldInfo['loop'] == 1 ? 9999 : 1)+'"/>'
        + '<embed pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"'
        + 'type="application/x-mplayer2" width="'+videoFieldInfo['width']+'" height="'+videoFieldInfo['height']+'"'
        + 'AutoStart="'+videoFieldInfo['autostart'] +'"'
        + 'playCount="'+(videoFieldInfo['loop'] == 1 ? 9999 : 1)+'"'
        + 'uiMode="'+videoFieldInfo['uimode']+'"'
        + 'displaysize="1" stretchtofit="1"'
        + 'src="'+videoFieldInfo['baseurl']+filename+'">'
        + '</embed>'
        + '</object>';
    var playerPlace = document.getElementById("player_place_"+videoFieldInfo['id']);
    playerPlace.innerHTML = playerCode;
}

function showImageInFields(item_id, new_filename)
{
    for (var k in layoutImageFields) {
        var imageId = layoutImageFields[k];
        var imctl = document.getElementById('LayoutImage_'+imageId);
        if (!imctl) continue;
        if (imctl.getAttribute('data-imagesize') == 'fullsize') {
            var re = /^([^\?]*)/;
        } else {
            var re = /file=([^&]*)/i;
        }
        if (imageId.search(item_id) > -1) { // find field for proper item
            layoutStopRotation(imageId);
            var position = -1;
            for (var key in layoutImages[imageId]) {
                var m = layoutImages[imageId][key][0].match(re);
                var filename = m ? decodeURIComponent(m[1]) : '';
                if (filename == new_filename) {
                    position = Number(key);
                    break;
                }
            }
            if (position > -1) { // rotate to found position
                layoutRotPos[imageId] = position;
                var num = layoutImages[imageId].length;
                var image = layoutImages[imageId][position][0];
                imctl.setAttribute('data-bigimage', layoutImages[imageId][position][1]);
                imctl.src = image;
                var ind = document.getElementById('LayoutRotInd_'+imageId);
                if (ind) ind.innerHTML = '\xA0\xA0' + (1+Number(position)).toString() + '\xA0of\xA0' +
                    num.toString() + '\xA0\xA0';
            } else { // replace url
                var new_src = '';
                if (imctl.getAttribute('data-imagesize') == 'fullsize') {
                    new_src = encodeURI(new_filename) + '?e=1';
                } else {
                    new_src = imctl.src.replace(re, 'file=' + encodeURIComponent(new_filename));
                }
                if (imctl.src != new_src) {
                    imctl.setAttribute('data-bigimage', encodeURI(new_filename) + '?e=1');
                    imctl.src = new_src;
                }
            }
        }
    }
}

function showImageDetails(item_id)
{
    for (var k in layoutImageFieldsDetails) {
        var imageId = layoutImageFieldsDetails[k];
        if (imageId.search(item_id) > -1) { // find field for proper item
            showLargeImage("LayoutImage_"+imageId);
            break;
        }
    }
}

function showTextBlock(ctl)
{
    var e = document.getElementById(ctl);
    if (!e) return;
    var html = e.value;

    fadeStack.show();
    if (imageWindow) {
       imageWindow.parentNode.removeChild(imageWindow);
    }
    var d = document.createElement('div');
    d.className = 'InfoWindow';
    imageWindow = d;
    var onclick = function () {
        imageWindow = null;
        d.parentNode.removeChild(d);
        var im = fadeStack.getUpperFade();
        if (im) im.onclick = null;
        fadeStack.hide();
        showElements();
    }
    var im = fadeStack.getUpperFade();
    if (im) im.onclick = onclick;
    var content = document.createElement('div');
    content.className = 'content';
    content.innerHTML = html;
    d.appendChild(content);
    var d1 = document.createElement('div');
    d1.className = 'controls';
    var a1 = document.createElement('a');
    a1.innerHTML = 'Close';
    a1.href = 'javascript:undefined';
    a1.onclick = onclick;
    d1.appendChild(a1);
    d.appendChild(d1);
    if (useAbsPosition) {
        d.style.position = 'absolute';
    } else {
        d.style.position = 'fixed';
    }
    d.style.width = '500px';
    document.body.appendChild(d);
    var width = 500;
    var height = Math.min(d.offsetHeight, getClientHeight() - 40);
    d.style.left = (getClientWidth() - width) / 2 + (useAbsPosition ? getScrollLeft() : 0) + 'px';
    d.style.top = (getClientHeight() - height) / 2 + (useAbsPosition ? getScrollTop() : 0) + 'px';
    d.style.height = height + 'px';
    d.style.visibility = 'visible';
    hideElements();
}

function selectOption(frameId, itemId, optId, optValue)
{
    var e = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId);
    if (e) {
        e.value = optValue;
    }
    var opts = getControlsByFrame(frameId, 'product_options[' + itemId + '][' + optId + '][]');
    for (var i = 0; i < opts.length; i++) {
        if (opts[i].value == optValue) {
            opts[i].checked = true;
            break;
        }
    }
    var table = getFrameElementById(frameId, 'opt_' + itemId + '_' + optId + '_table');
    if (table) {
	    var cells = table.getElementsByTagName('TD');
	    for (var i = 0; i < cells.length; i++) {
	        if (cells[i].getAttribute('data-value') == optValue) {
	            cells[i].className = cells[i].getAttribute('data-selclassname');
	        }else {
	            cells[i].className = '';
	        }
	    }
	}
    changeRelated(frameId, itemId);
    var frObj = getFrameObjById(frameId);
    var itemObj = frObj.getItemObjById(itemId);
    for (var i = 0; i < itemObj.options.length; i++) {
    	if (itemObj.options[i].id == optId && itemObj.options[i].type == 'enum'
    	&& itemObj.options[i].grid_dim) {
    		frObj.updateGrid(itemId, optId);
    		break;
    	}
    }
}

var optionImages = {};
function addOptionImage(itemId, optId, optValue, image, ctlid)
{
    optionImages[itemId + ':' + optId + ':' + optValue] = [ image, ctlid ];
}

function goToDetails(id, link)
{
    var qty_control = document.getElementById('qty_'+id);
    if (qty_control)
        setLocation(link + '&qty=' + qty_control.value);
    else
        setLocation(link);
}

function doExtraCheck(frame_id)
{
    var frame = document.getElementById('framebox_' + frame_id);
    var elem = frame.getElementsByTagName("input");

    for(i = 0; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if(att && att.match(/select\[\]/)) {
            if (elem[i].checked) {
                return confirm('You have selected products but have not add them to cart. ' +
                'If you continue, your selection will be lost.');
            }
        }
    }

    for(i = 0; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if(att && att.match(/qty_(\d)*/)) {
            if (elem[i].value > 0) {
                return confirm('You have selected products but have not add them to cart. ' +
                'If you continue, your selection will be lost.');
            }
        }
    }
    return true;

}

function getRandomNextPage(itemCount, cols_per_page, rows_per_page, lastFrom)
{
    var range = itemCount > rows_per_page*cols_per_page ?  itemCount - rows_per_page*cols_per_page + 1 : itemCount;
    lastFrom += 1;
    var from = lastFrom;
    while (from == lastFrom) {
        from = Math.round(Math.random() * range);
        from = from == 0 ? 1 : from;
    }
    return from;
}var sfArr = Array();
function searchCmd(f, name, value)
{
    if (name && f[name]) f[name].value = value;
    f.submitAction.value = 'search';
    f.submit();
}
function resetSelect(ctl)
{
    if (ctl && ctl.options) {
        for (var i = 0; i < ctl.options.length; i++) {
            ctl.options[i].selected = i == 0;
        }
    }
}

function clearSearchCriteria(f)
{
    if (f.keyword) {
        f.keyword.value = '';
    }
    resetSelect(f.group);
    resetSelect(f.itemType);
    resetSelect(f.ownerId);
    resetSelect(f.status);
    resetSelect(f.active);
    if (f.qoh_elt_lt) {
        f.qoh_elt_lt.checked = false;
    }
    var frameId = f.getAttribute('attr_frame_id');
    if (frameId > 0)  {
        var arr = sfArr[frameId];
    } else {
        var arr = sfArr;
    }
    var alias, stype, el, e1, e2;
    for (var i = 0; i < arr.length; i++) {
        alias = arr[i][0];
        switch (arr[i][1]) {
            case 'interval':
                el = f['from_' + alias];
                if (el) el.value = '';
                el = f['to_' + alias];
                if (el) el.value = '';
                break;
            case 'keyword':
                el = f['kw_' + alias];
                if (el) el.value = '';
                break;
            case 'select':
            case 'select2':
            case 'select3':
            case 'keyword2':
                el = f['sel_' + alias];
                if (el) {
                    el.value = '-1';
                    if (el.options) el.options[0].selected  = true;
                    e1 = (frameId > 0) ? getFrameElementById(frameId, 'sel_' + alias + '1') : document.getElementById('sel_' + alias + '1');
                    if (e1) e1.style.display = 'none';
                    e2 = (frameId > 0) ? getFrameElementById(frameId, 'sel_' + alias + '2') : document.getElementById('sel_' + alias + '2');
                    if (e2) e2.style.display = '';
                } else {
                    resetSelect(f['sel_' + alias + '[]']);
                }
                break;
            case 'zipfind':
                el = f['zf_' + alias + '[zip]'];
                if (el) el.value = '';
                el = f['zf_' + alias + '[distance]'];
                if (el) el.value = '';
                break;    
        }
    }
}

function checkSearchFields(f)
{
	var inputs = f.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'text') {
			if(inputs[i].getAttribute('required') == 1) {  
				inputs[i].value = trim(inputs[i].value);
				if (inputs[i].value.length == 0) {
					alert("Please enter values for required fields.");
					return false;
				}
			}
			if(inputs[i].name.match(/^zf_.+\[distance\]$/) && inputs[i].style.display != 'none') {
				if (!inputs[i].value.match(/^\d+$/) || parseInt(inputs[i].value) > 500 || 
					parseInt(inputs[i].value) == 0) {
					alert("Distance value must be between 1 and 500.");
					return false;
				}
			}
		}
	}
	return true;
}

function quick_shipping_calc(url, title)
{
    popup_exec_url(url, null, 580, 500, true, null, title);
}

function show_shopping_cart(url, frameId)
{
    var closeFunc = function(frame) {
        if (frame.cartChanged) {
            AjaxFrameRefresh(frameId, null, true, true);
        }
    };
    popup_exec_url(url + '&first=1', null, 800, 500, true, closeFunc, 'Your Shopping Cart');
}

function showFullCartPopup(mode, params, frameId, modNum)
{
    oFrameId = frameId;
    var url = 'm' + modNum + '.html?form_name=fclfullcart&mode=' + mode;
    switch (mode) {
    case 'shippingCalc':
        _call('popup_exec_url', [url, null, 580, 500, true, null, 'Calculate Shipping']);
        break;

    case 'coupon':
        _call('popup_exec_html', [document.getElementById('coupon_form' + frameId).innerHTML, null, 0, 0, 'Add/Remove Coupon']);
        var wOkButton = _call('getPopupButton', ['ok']);
        if (wOkButton) {
            wOkButton.innerHTML = 'Apply';
            wOkButton.style.display = '';
            var form = params.sender.parentNode;
            while (form && form.tagName != 'FORM') form = form.parentNode;
            wOkButton.onclick = function() {
                var inputs = _call('getPopupProp', ['dialog']).getElementsByTagName('input');
                var value = '';
                var deleted = [];
                for(var i = 0; i < inputs.length; i++) {
                    if (inputs[i].type == 'text' && inputs[i].name == 'code') {
                        value = trim(inputs[i].value);
                    } else if (inputs[i].type == 'checkbox' && !inputs[i].checked) {
                        deleted.push(inputs[i].value);
                    }
                }
                if (!value && deleted.length == 0) {
                    alert('Please enter coupon code.');
                    return;
                }
                form.couponData.value = value + '||' + deleted.join('##');
                ajaxPostSubmit(form, 'applyCoupon');
            };
        }
        break;

    case 'editItem':
        _call('popup_exec_url', [url + '&ind=' + params.ind, null, 700, 400, true, null, params.title]);
        var wOkButton = _call('getPopupButton', ['ok']);
        if (wOkButton) {
            wOkButton.innerHTML = 'Apply';
            wOkButton.onclick = function() {
                // check options
                var popupWin = _call('getPopupProp', ['iframe']).contentWindow;
                if (popupWin.frObj && !popupWin.frObj.checkItemOptions(params.id)) return false;
                applyClick(_call('getPopupForm', ['fclfullcart']), 'editItem');
            };
            wOkButton.style.display = '';
        }
        break;
    }
}

function showCouponError()
{
    var popup = _call('getPopupProp', ['dialog']);
    var divs = popup.getElementsByTagName('div');
    for(var i = 0; i < divs.length; i++) {
        if (divs[i].className == 'errorbox') {
            divs[i].style.display = '';
            break;
        }
    }
}

function assignShippingAmount(amount, frameId)
{
    if (!frameId) {
        // получим список всех frameId расположенных на странице
        if (window['fullCartFrames']) {
            for(var i in window['fullCartFrames']) {
                if (typeof(window['fullCartFrames'][i]) != 'function') {
                    assignShippingAmount(amount, i);
                }
            }
        }
        return;
    }
    var shipping_f = document.getElementById('shipping_amount' + frameId);
    if (shipping_f) {
        shipping_f.innerHTML = '<b>' + currencyFormat(amount, frameId) + '</b>';
    }
    var total_f = document.getElementById('total_amount' + frameId);
    if (total_f) {
        total_f.innerHTML = currencyFormat(cur_total + amount, frameId);
    }
}

function validate_qty(min, max, qoh, ctl, item_name)
{
    var cur = parseInt(ctl.value);
    if (isNaN(cur))  {
        alert('Invalid quantity value for "'+item_name+'"');
        ctl.focus();
    }
    else if (cur) {
        if (cur < min) {
            alert('Minimum order quantity for "'+item_name+'" is '+min);
            ctl.value = min;
            ctl.focus();
        }
        else if (cur > max) {
            alert('Maximum order quantity for "'+item_name+'" is '+max);
            ctl.value = max;
            ctl.focus();
        }
        else if (cur > qoh) {
            if (qoh < min) {
                alert('Item "'+item_name+'" is out of stock');
                ctl.value = 0;
            }
            else {
                alert('Quantity on stock for "'+item_name+'" is '+qoh);
                ctl.value = qoh;
            }
            ctl.focus();
        }
    }
}

function add_free_item(frameId, bonus_item_url_prefix, unique_discount_id, items_str, cats_str)
{
    oFrameId = frameId;
    var url = bonus_item_url_prefix + '&unique_discount_id=' + unique_discount_id +
        '&items=' + items_str + '&cats=' + cats_str;
    _call('popup_exec_url', [url, null, 800, 600]);
}

// type: 'ship', 'bill'
function showEditCustomerFieldsForm(type, frameId, modNum, custId)
{
    oFrameId = frameId;
    var mode = type == 'ship' ? 'onlyShip' : 'onlyBill';
    var title = type == 'ship' ? 'Shipping Address' : 'Billing Address';
    var url = 'm' + modNum + '.html?form_name=fclcustomerinfo2&popup=1&mode=' + mode + '&interfaceId=' + custId;
    _call('popup_exec_url', [url, null, 600, 500, true, null, title]);
    var wOkButton = _call('getPopupButton', ['ok']);
    if (wOkButton) {
        wOkButton.innerHTML = 'Apply';
        wOkButton.style.display = '';
        wOkButton.onclick = function() {
            var form = _call('getPopupForm', ['fclcustomerinfo2']);
            applyClick(form, type == 'ship' ? 'applyShipAddr' : 'applyBillAddr');
        };
    }
}

