
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008)
 * Rev: 5685
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(H(){J w=1b.4M,3m$=1b.$;J D=1b.4M=1b.$=H(a,b){I 2B D.17.5j(a,b)};J u=/^[^<]*(<(.|\\s)+>)[^>]*$|^#(\\w+)$/,62=/^.[^:#\\[\\.]*$/,12;D.17=D.44={5j:H(d,b){d=d||S;G(d.16){7[0]=d;7.K=1;I 7}G(1j d=="23"){J c=u.2D(d);G(c&&(c[1]||!b)){G(c[1])d=D.4h([c[1]],b);N{J a=S.61(c[3]);G(a){G(a.2v!=c[3])I D().2q(d);I D(a)}d=[]}}N I D(b).2q(d)}N G(D.1D(d))I D(S)[D.17.27?"27":"43"](d);I 7.6Y(D.2d(d))},5w:"1.2.6",8G:H(){I 7.K},K:0,3p:H(a){I a==12?D.2d(7):7[a]},2I:H(b){J a=D(b);a.5n=7;I a},6Y:H(a){7.K=0;2p.44.1p.1w(7,a);I 7},P:H(a,b){I D.P(7,a,b)},5i:H(b){J a=-1;I D.2L(b&&b.5w?b[0]:b,7)},1K:H(c,a,b){J d=c;G(c.1q==56)G(a===12)I 7[0]&&D[b||"1K"](7[0],c);N{d={};d[c]=a}I 7.P(H(i){R(c 1n d)D.1K(b?7.V:7,c,D.1i(7,d[c],b,i,c))})},1g:H(b,a){G((b==\'2h\'||b==\'1Z\')&&3d(a)<0)a=12;I 7.1K(b,a,"2a")},1r:H(b){G(1j b!="49"&&b!=U)I 7.4E().3v((7[0]&&7[0].2z||S).5F(b));J a="";D.P(b||7,H(){D.P(7.3t,H(){G(7.16!=8)a+=7.16!=1?7.76:D.17.1r([7])})});I a},5z:H(b){G(7[0])D(b,7[0].2z).5y().39(7[0]).2l(H(){J a=7;1B(a.1x)a=a.1x;I a}).3v(7);I 7},8Y:H(a){I 7.P(H(){D(7).6Q().5z(a)})},8R:H(a){I 7.P(H(){D(7).5z(a)})},3v:H(){I 7.3W(19,M,Q,H(a){G(7.16==1)7.3U(a)})},6F:H(){I 7.3W(19,M,M,H(a){G(7.16==1)7.39(a,7.1x)})},6E:H(){I 7.3W(19,Q,Q,H(a){7.1d.39(a,7)})},5q:H(){I 7.3W(19,Q,M,H(a){7.1d.39(a,7.2H)})},3l:H(){I 7.5n||D([])},2q:H(b){J c=D.2l(7,H(a){I D.2q(b,a)});I 7.2I(/[^+>] [^+>]/.11(b)||b.1h("..")>-1?D.4r(c):c)},5y:H(e){J f=7.2l(H(){G(D.14.1f&&!D.4n(7)){J a=7.6o(M),5h=S.3h("1v");5h.3U(a);I D.4h([5h.4H])[0]}N I 7.6o(M)});J d=f.2q("*").5c().P(H(){G(7[E]!=12)7[E]=U});G(e===M)7.2q("*").5c().P(H(i){G(7.16==3)I;J c=D.L(7,"3w");R(J a 1n c)R(J b 1n c[a])D.W.1e(d[i],a,c[a][b],c[a][b].L)});I f},1E:H(b){I 7.2I(D.1D(b)&&D.3C(7,H(a,i){I b.1k(a,i)})||D.3g(b,7))},4Y:H(b){G(b.1q==56)G(62.11(b))I 7.2I(D.3g(b,7,M));N b=D.3g(b,7);J a=b.K&&b[b.K-1]!==12&&!b.16;I 7.1E(H(){I a?D.2L(7,b)<0:7!=b})},1e:H(a){I 7.2I(D.4r(D.2R(7.3p(),1j a==\'23\'?D(a):D.2d(a))))},3F:H(a){I!!a&&D.3g(a,7).K>0},7T:H(a){I 7.3F("."+a)},6e:H(b){G(b==12){G(7.K){J c=7[0];G(D.Y(c,"2A")){J e=c.64,63=[],15=c.15,2V=c.O=="2A-2V";G(e<0)I U;R(J i=2V?e:0,2f=2V?e+1:15.K;i<2f;i++){J d=15[i];G(d.2W){b=D.14.1f&&!d.at.2x.an?d.1r:d.2x;G(2V)I b;63.1p(b)}}I 63}N I(7[0].2x||"").1o(/\\r/g,"")}I 12}G(b.1q==4L)b+=\'\';I 7.P(H(){G(7.16!=1)I;G(b.1q==2p&&/5O|5L/.11(7.O))7.4J=(D.2L(7.2x,b)>=0||D.2L(7.34,b)>=0);N G(D.Y(7,"2A")){J a=D.2d(b);D("9R",7).P(H(){7.2W=(D.2L(7.2x,a)>=0||D.2L(7.1r,a)>=0)});G(!a.K)7.64=-1}N 7.2x=b})},2K:H(a){I a==12?(7[0]?7[0].4H:U):7.4E().3v(a)},7b:H(a){I 7.5q(a).21()},79:H(i){I 7.3s(i,i+1)},3s:H(){I 7.2I(2p.44.3s.1w(7,19))},2l:H(b){I 7.2I(D.2l(7,H(a,i){I b.1k(a,i,a)}))},5c:H(){I 7.1e(7.5n)},L:H(d,b){J a=d.1R(".");a[1]=a[1]?"."+a[1]:"";G(b===12){J c=7.5C("9z"+a[1]+"!",[a[0]]);G(c===12&&7.K)c=D.L(7[0],d);I c===12&&a[1]?7.L(a[0]):c}N I 7.1P("9u"+a[1]+"!",[a[0],b]).P(H(){D.L(7,d,b)})},3b:H(a){I 7.P(H(){D.3b(7,a)})},3W:H(g,f,h,d){J e=7.K>1,3x;I 7.P(H(){G(!3x){3x=D.4h(g,7.2z);G(h)3x.9o()}J b=7;G(f&&D.Y(7,"1T")&&D.Y(3x[0],"4F"))b=7.3H("22")[0]||7.3U(7.2z.3h("22"));J c=D([]);D.P(3x,H(){J a=e?D(7).5y(M)[0]:7;G(D.Y(a,"1m"))c=c.1e(a);N{G(a.16==1)c=c.1e(D("1m",a).21());d.1k(b,a)}});c.P(6T)})}};D.17.5j.44=D.17;H 6T(i,a){G(a.4d)D.3Y({1a:a.4d,31:Q,1O:"1m"});N D.5u(a.1r||a.6O||a.4H||"");G(a.1d)a.1d.37(a)}H 1z(){I+2B 8J}D.1l=D.17.1l=H(){J b=19[0]||{},i=1,K=19.K,4x=Q,15;G(b.1q==8I){4x=b;b=19[1]||{};i=2}G(1j b!="49"&&1j b!="H")b={};G(K==i){b=7;--i}R(;i<K;i++)G((15=19[i])!=U)R(J c 1n 15){J a=b[c],2w=15[c];G(b===2w)6M;G(4x&&2w&&1j 2w=="49"&&!2w.16)b[c]=D.1l(4x,a||(2w.K!=U?[]:{}),2w);N G(2w!==12)b[c]=2w}I b};J E="4M"+1z(),6K=0,5r={},6G=/z-?5i|8B-?8A|1y|6B|8v-?1Z/i,3P=S.3P||{};D.1l({8u:H(a){1b.$=3m$;G(a)1b.4M=w;I D},1D:H(a){I!!a&&1j a!="23"&&!a.Y&&a.1q!=2p&&/^[\\s[]?H/.11(a+"")},4n:H(a){I a.1C&&!a.1c||a.2j&&a.2z&&!a.2z.1c},5u:H(a){a=D.3k(a);G(a){J b=S.3H("6w")[0]||S.1C,1m=S.3h("1m");1m.O="1r/4t";G(D.14.1f)1m.1r=a;N 1m.3U(S.5F(a));b.39(1m,b.1x);b.37(1m)}},Y:H(b,a){I b.Y&&b.Y.2r()==a.2r()},1Y:{},L:H(c,d,b){c=c==1b?5r:c;J a=c[E];G(!a)a=c[E]=++6K;G(d&&!D.1Y[a])D.1Y[a]={};G(b!==12)D.1Y[a][d]=b;I d?D.1Y[a][d]:a},3b:H(c,b){c=c==1b?5r:c;J a=c[E];G(b){G(D.1Y[a]){2U D.1Y[a][b];b="";R(b 1n D.1Y[a])1X;G(!b)D.3b(c)}}N{1U{2U c[E]}1V(e){G(c.5l)c.5l(E)}2U D.1Y[a]}},P:H(d,a,c){J e,i=0,K=d.K;G(c){G(K==12){R(e 1n d)G(a.1w(d[e],c)===Q)1X}N R(;i<K;)G(a.1w(d[i++],c)===Q)1X}N{G(K==12){R(e 1n d)G(a.1k(d[e],e,d[e])===Q)1X}N R(J b=d[0];i<K&&a.1k(b,i,b)!==Q;b=d[++i]){}}I d},1i:H(b,a,c,i,d){G(D.1D(a))a=a.1k(b,i);I a&&a.1q==4L&&c=="2a"&&!6G.11(d)?a+"2X":a},1F:{1e:H(c,b){D.P((b||"").1R(/\\s+/),H(i,a){G(c.16==1&&!D.1F.3T(c.1F,a))c.1F+=(c.1F?" ":"")+a})},21:H(c,b){G(c.16==1)c.1F=b!=12?D.3C(c.1F.1R(/\\s+/),H(a){I!D.1F.3T(b,a)}).6s(" "):""},3T:H(b,a){I D.2L(a,(b.1F||b).6r().1R(/\\s+/))>-1}},6q:H(b,c,a){J e={};R(J d 1n c){e[d]=b.V[d];b.V[d]=c[d]}a.1k(b);R(J d 1n c)b.V[d]=e[d]},1g:H(d,e,c){G(e=="2h"||e=="1Z"){J b,3X={30:"5x",5g:"1G",18:"3I"},35=e=="2h"?["5e","6k"]:["5G","6i"];H 5b(){b=e=="2h"?d.8f:d.8c;J a=0,2C=0;D.P(35,H(){a+=3d(D.2a(d,"57"+7,M))||0;2C+=3d(D.2a(d,"2C"+7+"4b",M))||0});b-=29.83(a+2C)}G(D(d).3F(":4j"))5b();N D.6q(d,3X,5b);I 29.2f(0,b)}I D.2a(d,e,c)},2a:H(f,l,k){J e,V=f.V;H 3E(b){G(!D.14.2k)I Q;J a=3P.54(b,U);I!a||a.52("3E")==""}G(l=="1y"&&D.14.1f){e=D.1K(V,"1y");I e==""?"1":e}G(D.14.2G&&l=="18"){J d=V.50;V.50="0 7Y 7W";V.50=d}G(l.1I(/4i/i))l=y;G(!k&&V&&V[l])e=V[l];N G(3P.54){G(l.1I(/4i/i))l="4i";l=l.1o(/([A-Z])/g,"-$1").3y();J c=3P.54(f,U);G(c&&!3E(f))e=c.52(l);N{J g=[],2E=[],a=f,i=0;R(;a&&3E(a);a=a.1d)2E.6h(a);R(;i<2E.K;i++)G(3E(2E[i])){g[i]=2E[i].V.18;2E[i].V.18="3I"}e=l=="18"&&g[2E.K-1]!=U?"2F":(c&&c.52(l))||"";R(i=0;i<g.K;i++)G(g[i]!=U)2E[i].V.18=g[i]}G(l=="1y"&&e=="")e="1"}N G(f.4g){J h=l.1o(/\\-(\\w)/g,H(a,b){I b.2r()});e=f.4g[l]||f.4g[h];G(!/^\\d+(2X)?$/i.11(e)&&/^\\d/.11(e)){J j=V.1A,66=f.65.1A;f.65.1A=f.4g.1A;V.1A=e||0;e=V.aM+"2X";V.1A=j;f.65.1A=66}}I e},4h:H(l,h){J k=[];h=h||S;G(1j h.3h==\'12\')h=h.2z||h[0]&&h[0].2z||S;D.P(l,H(i,d){G(!d)I;G(d.1q==4L)d+=\'\';G(1j d=="23"){d=d.1o(/(<(\\w+)[^>]*?)\\/>/g,H(b,a,c){I c.1I(/^(aK|4f|7E|aG|4T|7A|aB|3n|az|ay|av)$/i)?b:a+"></"+c+">"});J f=D.3k(d).3y(),1v=h.3h("1v");J e=!f.1h("<au")&&[1,"<2A 7w=\'7w\'>","</2A>"]||!f.1h("<ar")&&[1,"<7v>","</7v>"]||f.1I(/^<(aq|22|am|ak|ai)/)&&[1,"<1T>","</1T>"]||!f.1h("<4F")&&[2,"<1T><22>","</22></1T>"]||(!f.1h("<af")||!f.1h("<ad"))&&[3,"<1T><22><4F>","</4F></22></1T>"]||!f.1h("<7E")&&[2,"<1T><22></22><7q>","</7q></1T>"]||D.14.1f&&[1,"1v<1v>","</1v>"]||[0,"",""];1v.4H=e[1]+d+e[2];1B(e[0]--)1v=1v.5T;G(D.14.1f){J g=!f.1h("<1T")&&f.1h("<22")<0?1v.1x&&1v.1x.3t:e[1]=="<1T>"&&f.1h("<22")<0?1v.3t:[];R(J j=g.K-1;j>=0;--j)G(D.Y(g[j],"22")&&!g[j].3t.K)g[j].1d.37(g[j]);G(/^\\s/.11(d))1v.39(h.5F(d.1I(/^\\s*/)[0]),1v.1x)}d=D.2d(1v.3t)}G(d.K===0&&(!D.Y(d,"3V")&&!D.Y(d,"2A")))I;G(d[0]==12||D.Y(d,"3V")||d.15)k.1p(d);N k=D.2R(k,d)});I k},1K:H(d,f,c){G(!d||d.16==3||d.16==8)I 12;J e=!D.4n(d),40=c!==12,1f=D.14.1f;f=e&&D.3X[f]||f;G(d.2j){J g=/5Q|4d|V/.11(f);G(f=="2W"&&D.14.2k)d.1d.64;G(f 1n d&&e&&!g){G(40){G(f=="O"&&D.Y(d,"4T")&&d.1d)7p"O a3 a1\'t 9V 9U";d[f]=c}G(D.Y(d,"3V")&&d.7i(f))I d.7i(f).76;I d[f]}G(1f&&e&&f=="V")I D.1K(d.V,"9T",c);G(40)d.9Q(f,""+c);J h=1f&&e&&g?d.4G(f,2):d.4G(f);I h===U?12:h}G(1f&&f=="1y"){G(40){d.6B=1;d.1E=(d.1E||"").1o(/7f\\([^)]*\\)/,"")+(3r(c)+\'\'=="9L"?"":"7f(1y="+c*7a+")")}I d.1E&&d.1E.1h("1y=")>=0?(3d(d.1E.1I(/1y=([^)]*)/)[1])/7a)+\'\':""}f=f.1o(/-([a-z])/9H,H(a,b){I b.2r()});G(40)d[f]=c;I d[f]},3k:H(a){I(a||"").1o(/^\\s+|\\s+$/g,"")},2d:H(b){J a=[];G(b!=U){J i=b.K;G(i==U||b.1R||b.4I||b.1k)a[0]=b;N 1B(i)a[--i]=b[i]}I a},2L:H(b,a){R(J i=0,K=a.K;i<K;i++)G(a[i]===b)I i;I-1},2R:H(a,b){J i=0,T,2S=a.K;G(D.14.1f){1B(T=b[i++])G(T.16!=8)a[2S++]=T}N 1B(T=b[i++])a[2S++]=T;I a},4r:H(a){J c=[],2o={};1U{R(J i=0,K=a.K;i<K;i++){J b=D.L(a[i]);G(!2o[b]){2o[b]=M;c.1p(a[i])}}}1V(e){c=a}I c},3C:H(c,a,d){J b=[];R(J i=0,K=c.K;i<K;i++)G(!d!=!a(c[i],i))b.1p(c[i]);I b},2l:H(d,a){J c=[];R(J i=0,K=d.K;i<K;i++){J b=a(d[i],i);G(b!=U)c[c.K]=b}I c.7d.1w([],c)}});J v=9B.9A.3y();D.14={5B:(v.1I(/.+(?:9y|9x|9w|9v)[\\/: ]([\\d.]+)/)||[])[1],2k:/75/.11(v),2G:/2G/.11(v),1f:/1f/.11(v)&&!/2G/.11(v),42:/42/.11(v)&&!/(9s|75)/.11(v)};J y=D.14.1f?"7o":"72";D.1l({71:!D.14.1f||S.70=="6Z",3X:{"R":"9n","9k":"1F","4i":y,72:y,7o:y,9h:"9f",9e:"9d",9b:"99"}});D.P({6W:H(a){I a.1d},97:H(a){I D.4S(a,"1d")},95:H(a){I D.3a(a,2,"2H")},91:H(a){I D.3a(a,2,"4l")},8Z:H(a){I D.4S(a,"2H")},8X:H(a){I D.4S(a,"4l")},8W:H(a){I D.5v(a.1d.1x,a)},8V:H(a){I D.5v(a.1x)},6Q:H(a){I D.Y(a,"8U")?a.8T||a.8S.S:D.2d(a.3t)}},H(c,d){D.17[c]=H(b){J a=D.2l(7,d);G(b&&1j b=="23")a=D.3g(b,a);I 7.2I(D.4r(a))}});D.P({6P:"3v",8Q:"6F",39:"6E",8P:"5q",8O:"7b"},H(c,b){D.17[c]=H(){J a=19;I 7.P(H(){R(J i=0,K=a.K;i<K;i++)D(a[i])[b](7)})}});D.P({8N:H(a){D.1K(7,a,"");G(7.16==1)7.5l(a)},8M:H(a){D.1F.1e(7,a)},8L:H(a){D.1F.21(7,a)},8K:H(a){D.1F[D.1F.3T(7,a)?"21":"1e"](7,a)},21:H(a){G(!a||D.1E(a,[7]).r.K){D("*",7).1e(7).P(H(){D.W.21(7);D.3b(7)});G(7.1d)7.1d.37(7)}},4E:H(){D(">*",7).21();1B(7.1x)7.37(7.1x)}},H(a,b){D.17[a]=H(){I 7.P(b,19)}});D.P(["6N","4b"],H(i,c){J b=c.3y();D.17[b]=H(a){I 7[0]==1b?D.14.2G&&S.1c["5t"+c]||D.14.2k&&1b["5s"+c]||S.70=="6Z"&&S.1C["5t"+c]||S.1c["5t"+c]:7[0]==S?29.2f(29.2f(S.1c["4y"+c],S.1C["4y"+c]),29.2f(S.1c["2i"+c],S.1C["2i"+c])):a==12?(7.K?D.1g(7[0],b):U):7.1g(b,a.1q==56?a:a+"2X")}});H 25(a,b){I a[0]&&3r(D.2a(a[0],b,M),10)||0}J C=D.14.2k&&3r(D.14.5B)<8H?"(?:[\\\\w*3m-]|\\\\\\\\.)":"(?:[\\\\w\\8F-\\8E*3m-]|\\\\\\\\.)",6L=2B 4v("^>\\\\s*("+C+"+)"),6J=2B 4v("^("+C+"+)(#)("+C+"+)"),6I=2B 4v("^([#.]?)("+C+"*)");D.1l({6H:{"":H(a,i,m){I m[2]=="*"||D.Y(a,m[2])},"#":H(a,i,m){I a.4G("2v")==m[2]},":":{8D:H(a,i,m){I i<m[3]-0},8C:H(a,i,m){I i>m[3]-0},3a:H(a,i,m){I m[3]-0==i},79:H(a,i,m){I m[3]-0==i},3o:H(a,i){I i==0},3S:H(a,i,m,r){I i==r.K-1},6D:H(a,i){I i%2==0},6C:H(a,i){I i%2},"3o-4u":H(a){I a.1d.3H("*")[0]==a},"3S-4u":H(a){I D.3a(a.1d.5T,1,"4l")==a},"8z-4u":H(a){I!D.3a(a.1d.5T,2,"4l")},6W:H(a){I a.1x},4E:H(a){I!a.1x},8y:H(a,i,m){I(a.6O||a.8x||D(a).1r()||"").1h(m[3])>=0},4j:H(a){I"1G"!=a.O&&D.1g(a,"18")!="2F"&&D.1g(a,"5g")!="1G"},1G:H(a){I"1G"==a.O||D.1g(a,"18")=="2F"||D.1g(a,"5g")=="1G"},8w:H(a){I!a.3R},3R:H(a){I a.3R},4J:H(a){I a.4J},2W:H(a){I a.2W||D.1K(a,"2W")},1r:H(a){I"1r"==a.O},5O:H(a){I"5O"==a.O},5L:H(a){I"5L"==a.O},5p:H(a){I"5p"==a.O},3Q:H(a){I"3Q"==a.O},5o:H(a){I"5o"==a.O},6A:H(a){I"6A"==a.O},6z:H(a){I"6z"==a.O},2s:H(a){I"2s"==a.O||D.Y(a,"2s")},4T:H(a){I/4T|2A|6y|2s/i.11(a.Y)},3T:H(a,i,m){I D.2q(m[3],a).K},8t:H(a){I/h\\d/i.11(a.Y)},8s:H(a){I D.3C(D.3O,H(b){I a==b.T}).K}}},6x:[/^(\\[) *@?([\\w-]+) *([!*$^~=]*) *(\'?"?)(.*?)\\4 *\\]/,/^(:)([\\w-]+)\\("?\'?(.*?(\\(.*?\\))?[^(]*?)"?\'?\\)/,2B 4v("^([:.#]*)("+C+"+)")],3g:H(a,c,b){J d,1t=[];1B(a&&a!=d){d=a;J f=D.1E(a,c,b);a=f.t.1o(/^\\s*,\\s*/,"");1t=b?c=f.r:D.2R(1t,f.r)}I 1t},2q:H(t,o){G(1j t!="23")I[t];G(o&&o.16!=1&&o.16!=9)I[];o=o||S;J d=[o],2o=[],3S,Y;1B(t&&3S!=t){J r=[];3S=t;t=D.3k(t);J l=Q,3j=6L,m=3j.2D(t);G(m){Y=m[1].2r();R(J i=0;d[i];i++)R(J c=d[i].1x;c;c=c.2H)G(c.16==1&&(Y=="*"||c.Y.2r()==Y))r.1p(c);d=r;t=t.1o(3j,"");G(t.1h(" ")==0)6M;l=M}N{3j=/^([>+~])\\s*(\\w*)/i;G((m=3j.2D(t))!=U){r=[];J k={};Y=m[2].2r();m=m[1];R(J j=0,3i=d.K;j<3i;j++){J n=m=="~"||m=="+"?d[j].2H:d[j].1x;R(;n;n=n.2H)G(n.16==1){J g=D.L(n);G(m=="~"&&k[g])1X;G(!Y||n.Y.2r()==Y){G(m=="~")k[g]=M;r.1p(n)}G(m=="+")1X}}d=r;t=D.3k(t.1o(3j,""));l=M}}G(t&&!l){G(!t.1h(",")){G(o==d[0])d.4s();2o=D.2R(2o,d);r=d=[o];t=" "+t.6v(1,t.K)}N{J h=6J;J m=h.2D(t);G(m){m=[0,m[2],m[3],m[1]]}N{h=6I;m=h.2D(t)}m[2]=m[2].1o(/\\\\/g,"");J f=d[d.K-1];G(m[1]=="#"&&f&&f.61&&!D.4n(f)){J p=f.61(m[2]);G((D.14.1f||D.14.2G)&&p&&1j p.2v=="23"&&p.2v!=m[2])p=D(\'[@2v="\'+m[2]+\'"]\',f)[0];d=r=p&&(!m[3]||D.Y(p,m[3]))?[p]:[]}N{R(J i=0;d[i];i++){J a=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];G(a=="*"&&d[i].Y.3y()=="49")a="3n";r=D.2R(r,d[i].3H(a))}G(m[1]==".")r=D.5m(r,m[2]);G(m[1]=="#"){J e=[];R(J i=0;r[i];i++)G(r[i].4G("2v")==m[2]){e=[r[i]];1X}r=e}d=r}t=t.1o(h,"")}}G(t){J b=D.1E(t,r);d=r=b.r;t=D.3k(b.t)}}G(t)d=[];G(d&&o==d[0])d.4s();2o=D.2R(2o,d);I 2o},5m:H(r,m,a){m=" "+m+" ";J c=[];R(J i=0;r[i];i++){J b=(" "+r[i].1F+" ").1h(m)>=0;G(!a&&b||a&&!b)c.1p(r[i])}I c},1E:H(t,r,h){J d;1B(t&&t!=d){d=t;J p=D.6x,m;R(J i=0;p[i];i++){m=p[i].2D(t);G(m){t=t.8r(m[0].K);m[2]=m[2].1o(/\\\\/g,"");1X}}G(!m)1X;G(m[1]==":"&&m[2]=="4Y")r=62.11(m[3])?D.1E(m[3],r,M).r:D(r).4Y(m[3]);N G(m[1]==".")r=D.5m(r,m[2],h);N G(m[1]=="["){J g=[],O=m[3];R(J i=0,3i=r.K;i<3i;i++){J a=r[i],z=a[D.3X[m[2]]||m[2]];G(z==U||/5Q|4d|2W/.11(m[2]))z=D.1K(a,m[2])||\'\';G((O==""&&!!z||O=="="&&z==m[5]||O=="!="&&z!=m[5]||O=="^="&&z&&!z.1h(m[5])||O=="$="&&z.6v(z.K-m[5].K)==m[5]||(O=="*="||O=="~=")&&z.1h(m[5])>=0)^h)g.1p(a)}r=g}N G(m[1]==":"&&m[2]=="3a-4u"){J e={},g=[],11=/(-?)(\\d*)n((?:\\+|-)?\\d*)/.2D(m[3]=="6D"&&"2n"||m[3]=="6C"&&"2n+1"||!/\\D/.11(m[3])&&"8q+"+m[3]||m[3]),3o=(11[1]+(11[2]||1))-0,d=11[3]-0;R(J i=0,3i=r.K;i<3i;i++){J j=r[i],1d=j.1d,2v=D.L(1d);G(!e[2v]){J c=1;R(J n=1d.1x;n;n=n.2H)G(n.16==1)n.4q=c++;e[2v]=M}J b=Q;G(3o==0){G(j.4q==d)b=M}N G((j.4q-d)%3o==0&&(j.4q-d)/3o>=0)b=M;G(b^h)g.1p(j)}r=g}N{J f=D.6H[m[1]];G(1j f=="49")f=f[m[2]];G(1j f=="23")f=6u("Q||H(a,i){I "+f+";}");r=D.3C(r,H(a,i){I f(a,i,m,r)},h)}}I{r:r,t:t}},4S:H(b,c){J a=[],1t=b[c];1B(1t&&1t!=S){G(1t.16==1)a.1p(1t);1t=1t[c]}I a},3a:H(a,e,c,b){e=e||1;J d=0;R(;a;a=a[c])G(a.16==1&&++d==e)1X;I a},5v:H(n,a){J r=[];R(;n;n=n.2H){G(n.16==1&&n!=a)r.1p(n)}I r}});D.W={1e:H(f,i,g,e){G(f.16==3||f.16==8)I;G(D.14.1f&&f.4I)f=1b;G(!g.24)g.24=7.24++;G(e!=12){J h=g;g=7.3M(h,H(){I h.1w(7,19)});g.L=e}J j=D.L(f,"3w")||D.L(f,"3w",{}),1H=D.L(f,"1H")||D.L(f,"1H",H(){G(1j D!="12"&&!D.W.5k)I D.W.1H.1w(19.3L.T,19)});1H.T=f;D.P(i.1R(/\\s+/),H(c,b){J a=b.1R(".");b=a[0];g.O=a[1];J d=j[b];G(!d){d=j[b]={};G(!D.W.2t[b]||D.W.2t[b].4p.1k(f)===Q){G(f.3K)f.3K(b,1H,Q);N G(f.6t)f.6t("4o"+b,1H)}}d[g.24]=g;D.W.26[b]=M});f=U},24:1,26:{},21:H(e,h,f){G(e.16==3||e.16==8)I;J i=D.L(e,"3w"),1L,5i;G(i){G(h==12||(1j h=="23"&&h.8p(0)=="."))R(J g 1n i)7.21(e,g+(h||""));N{G(h.O){f=h.2y;h=h.O}D.P(h.1R(/\\s+/),H(b,a){J c=a.1R(".");a=c[0];G(i[a]){G(f)2U i[a][f.24];N R(f 1n i[a])G(!c[1]||i[a][f].O==c[1])2U i[a][f];R(1L 1n i[a])1X;G(!1L){G(!D.W.2t[a]||D.W.2t[a].4A.1k(e)===Q){G(e.6p)e.6p(a,D.L(e,"1H"),Q);N G(e.6n)e.6n("4o"+a,D.L(e,"1H"))}1L=U;2U i[a]}}})}R(1L 1n i)1X;G(!1L){J d=D.L(e,"1H");G(d)d.T=U;D.3b(e,"3w");D.3b(e,"1H")}}},1P:H(h,c,f,g,i){c=D.2d(c);G(h.1h("!")>=0){h=h.3s(0,-1);J a=M}G(!f){G(7.26[h])D("*").1e([1b,S]).1P(h,c)}N{G(f.16==3||f.16==8)I 12;J b,1L,17=D.1D(f[h]||U),W=!c[0]||!c[0].32;G(W){c.6h({O:h,2J:f,32:H(){},3J:H(){},4C:1z()});c[0][E]=M}c[0].O=h;G(a)c[0].6m=M;J d=D.L(f,"1H");G(d)b=d.1w(f,c);G((!17||(D.Y(f,\'a\')&&h=="4V"))&&f["4o"+h]&&f["4o"+h].1w(f,c)===Q)b=Q;G(W)c.4s();G(i&&D.1D(i)){1L=i.1w(f,b==U?c:c.7d(b));G(1L!==12)b=1L}G(17&&g!==Q&&b!==Q&&!(D.Y(f,\'a\')&&h=="4V")){7.5k=M;1U{f[h]()}1V(e){}}7.5k=Q}I b},1H:H(b){J a,1L,38,5f,4m;b=19[0]=D.W.6l(b||1b.W);38=b.O.1R(".");b.O=38[0];38=38[1];5f=!38&&!b.6m;4m=(D.L(7,"3w")||{})[b.O];R(J j 1n 4m){J c=4m[j];G(5f||c.O==38){b.2y=c;b.L=c.L;1L=c.1w(7,19);G(a!==Q)a=1L;G(1L===Q){b.32();b.3J()}}}I a},6l:H(b){G(b[E]==M)I b;J d=b;b={8o:d};J c="8n 8m 8l 8k 2s 8j 47 5d 6j 5E 8i L 8h 8g 4K 2y 5a 59 8e 8b 58 6f 8a 88 4k 87 86 84 6d 2J 4C 6c O 82 81 35".1R(" ");R(J i=c.K;i;i--)b[c[i]]=d[c[i]];b[E]=M;b.32=H(){G(d.32)d.32();d.80=Q};b.3J=H(){G(d.3J)d.3J();d.7Z=M};b.4C=b.4C||1z();G(!b.2J)b.2J=b.6d||S;G(b.2J.16==3)b.2J=b.2J.1d;G(!b.4k&&b.4K)b.4k=b.4K==b.2J?b.6c:b.4K;G(b.58==U&&b.5d!=U){J a=S.1C,1c=S.1c;b.58=b.5d+(a&&a.2e||1c&&1c.2e||0)-(a.6b||0);b.6f=b.6j+(a&&a.2c||1c&&1c.2c||0)-(a.6a||0)}G(!b.35&&((b.47||b.47===0)?b.47:b.5a))b.35=b.47||b.5a;G(!b.59&&b.5E)b.59=b.5E;G(!b.35&&b.2s)b.35=(b.2s&1?1:(b.2s&2?3:(b.2s&4?2:0)));I b},3M:H(a,b){b.24=a.24=a.24||b.24||7.24++;I b},2t:{27:{4p:H(){55();I},4A:H(){I}},3D:{4p:H(){G(D.14.1f)I Q;D(7).2O("53",D.W.2t.3D.2y);I M},4A:H(){G(D.14.1f)I Q;D(7).4e("53",D.W.2t.3D.2y);I M},2y:H(a){G(F(a,7))I M;a.O="3D";I D.W.1H.1w(7,19)}},3N:{4p:H(){G(D.14.1f)I Q;D(7).2O("51",D.W.2t.3N.2y);I M},4A:H(){G(D.14.1f)I Q;D(7).4e("51",D.W.2t.3N.2y);I M},2y:H(a){G(F(a,7))I M;a.O="3N";I D.W.1H.1w(7,19)}}}};D.17.1l({2O:H(c,a,b){I c=="4X"?7.2V(c,a,b):7.P(H(){D.W.1e(7,c,b||a,b&&a)})},2V:H(d,b,c){J e=D.W.3M(c||b,H(a){D(7).4e(a,e);I(c||b).1w(7,19)});I 7.P(H(){D.W.1e(7,d,e,c&&b)})},4e:H(a,b){I 7.P(H(){D.W.21(7,a,b)})},1P:H(c,a,b){I 7.P(H(){D.W.1P(c,a,7,M,b)})},5C:H(c,a,b){I 7[0]&&D.W.1P(c,a,7[0],Q,b)},2m:H(b){J c=19,i=1;1B(i<c.K)D.W.3M(b,c[i++]);I 7.4V(D.W.3M(b,H(a){7.4Z=(7.4Z||0)%i;a.32();I c[7.4Z++].1w(7,19)||Q}))},7X:H(a,b){I 7.2O(\'3D\',a).2O(\'3N\',b)},27:H(a){55();G(D.2Q)a.1k(S,D);N D.3A.1p(H(){I a.1k(7,D)});I 7}});D.1l({2Q:Q,3A:[],27:H(){G(!D.2Q){D.2Q=M;G(D.3A){D.P(D.3A,H(){7.1k(S)});D.3A=U}D(S).5C("27")}}});J x=Q;H 55(){G(x)I;x=M;G(S.3K&&!D.14.2G)S.3K("69",D.27,Q);G(D.14.1f&&1b==1S)(H(){G(D.2Q)I;1U{S.1C.7V("1A")}1V(3e){3B(19.3L,0);I}D.27()})();G(D.14.2G)S.3K("69",H(){G(D.2Q)I;R(J i=0;i<S.4W.K;i++)G(S.4W[i].3R){3B(19.3L,0);I}D.27()},Q);G(D.14.2k){J a;(H(){G(D.2Q)I;G(S.3f!="68"&&S.3f!="1J"){3B(19.3L,0);I}G(a===12)a=D("V, 7A[7U=7S]").K;G(S.4W.K!=a){3B(19.3L,0);I}D.27()})()}D.W.1e(1b,"43",D.27)}D.P(("7R,7Q,43,85,4y,4X,4V,7P,"+"7O,7N,89,53,51,7M,2A,"+"5o,7L,7K,8d,3e").1R(","),H(i,b){D.17[b]=H(a){I a?7.2O(b,a):7.1P(b)}});J F=H(a,c){J b=a.4k;1B(b&&b!=c)1U{b=b.1d}1V(3e){b=c}I b==c};D(1b).2O("4X",H(){D("*").1e(S).4e()});D.17.1l({67:D.17.43,43:H(g,d,c){G(1j g!=\'23\')I 7.67(g);J e=g.1h(" ");G(e>=0){J i=g.3s(e,g.K);g=g.3s(0,e)}c=c||H(){};J f="2P";G(d)G(D.1D(d)){c=d;d=U}N{d=D.3n(d);f="6g"}J h=7;D.3Y({1a:g,O:f,1O:"2K",L:d,1J:H(a,b){G(b=="1W"||b=="7J")h.2K(i?D("<1v/>").3v(a.4U.1o(/<1m(.|\\s)*?\\/1m>/g,"")).2q(i):a.4U);h.P(c,[a.4U,b,a])}});I 7},aL:H(){I D.3n(7.7I())},7I:H(){I 7.2l(H(){I D.Y(7,"3V")?D.2d(7.aH):7}).1E(H(){I 7.34&&!7.3R&&(7.4J||/2A|6y/i.11(7.Y)||/1r|1G|3Q/i.11(7.O))}).2l(H(i,c){J b=D(7).6e();I b==U?U:b.1q==2p?D.2l(b,H(a,i){I{34:c.34,2x:a}}):{34:c.34,2x:b}}).3p()}});D.P("7H,7G,7F,7D,7C,7B".1R(","),H(i,o){D.17[o]=H(f){I 7.2O(o,f)}});J B=1z();D.1l({3p:H(d,b,a,c){G(D.1D(b)){a=b;b=U}I D.3Y({O:"2P",1a:d,L:b,1W:a,1O:c})},aE:H(b,a){I D.3p(b,U,a,"1m")},aD:H(c,b,a){I D.3p(c,b,a,"3z")},aC:H(d,b,a,c){G(D.1D(b)){a=b;b={}}I D.3Y({O:"6g",1a:d,L:b,1W:a,1O:c})},aA:H(a){D.1l(D.60,a)},60:{1a:5Z.5Q,26:M,O:"2P",2T:0,7z:"4R/x-ax-3V-aw",7x:M,31:M,L:U,5Y:U,3Q:U,4Q:{2N:"4R/2N, 1r/2N",2K:"1r/2K",1m:"1r/4t, 4R/4t",3z:"4R/3z, 1r/4t",1r:"1r/as",4w:"*/*"}},4z:{},3Y:H(s){s=D.1l(M,s,D.1l(M,{},D.60,s));J g,2Z=/=\\?(&|$)/g,1u,L,O=s.O.2r();G(s.L&&s.7x&&1j s.L!="23")s.L=D.3n(s.L);G(s.1O=="4P"){G(O=="2P"){G(!s.1a.1I(2Z))s.1a+=(s.1a.1I(/\\?/)?"&":"?")+(s.4P||"7u")+"=?"}N G(!s.L||!s.L.1I(2Z))s.L=(s.L?s.L+"&":"")+(s.4P||"7u")+"=?";s.1O="3z"}G(s.1O=="3z"&&(s.L&&s.L.1I(2Z)||s.1a.1I(2Z))){g="4P"+B++;G(s.L)s.L=(s.L+"").1o(2Z,"="+g+"$1");s.1a=s.1a.1o(2Z,"="+g+"$1");s.1O="1m";1b[g]=H(a){L=a;1W();1J();1b[g]=12;1U{2U 1b[g]}1V(e){}G(i)i.37(h)}}G(s.1O=="1m"&&s.1Y==U)s.1Y=Q;G(s.1Y===Q&&O=="2P"){J j=1z();J k=s.1a.1o(/(\\?|&)3m=.*?(&|$)/,"$ap="+j+"$2");s.1a=k+((k==s.1a)?(s.1a.1I(/\\?/)?"&":"?")+"3m="+j:"")}G(s.L&&O=="2P"){s.1a+=(s.1a.1I(/\\?/)?"&":"?")+s.L;s.L=U}G(s.26&&!D.4O++)D.W.1P("7H");J n=/^(?:\\w+:)?\\/\\/([^\\/?#]+)/;G(s.1O=="1m"&&O=="2P"&&n.11(s.1a)&&n.2D(s.1a)[1]!=5Z.al){J i=S.3H("6w")[0];J h=S.3h("1m");h.4d=s.1a;G(s.7t)h.aj=s.7t;G(!g){J l=Q;h.ah=h.ag=H(){G(!l&&(!7.3f||7.3f=="68"||7.3f=="1J")){l=M;1W();1J();i.37(h)}}}i.3U(h);I 12}J m=Q;J c=1b.7s?2B 7s("ae.ac"):2B 7r();G(s.5Y)c.6R(O,s.1a,s.31,s.5Y,s.3Q);N c.6R(O,s.1a,s.31);1U{G(s.L)c.4B("ab-aa",s.7z);G(s.5S)c.4B("a9-5R-a8",D.4z[s.1a]||"a7, a6 a5 a4 5N:5N:5N a2");c.4B("X-9Z-9Y","7r");c.4B("9W",s.1O&&s.4Q[s.1O]?s.4Q[s.1O]+", */*":s.4Q.4w)}1V(e){}G(s.7m&&s.7m(c,s)===Q){s.26&&D.4O--;c.7l();I Q}G(s.26)D.W.1P("7B",[c,s]);J d=H(a){G(!m&&c&&(c.3f==4||a=="2T")){m=M;G(f){7k(f);f=U}1u=a=="2T"&&"2T"||!D.7j(c)&&"3e"||s.5S&&D.7h(c,s.1a)&&"7J"||"1W";G(1u=="1W"){1U{L=D.6X(c,s.1O,s.9S)}1V(e){1u="5J"}}G(1u=="1W"){J b;1U{b=c.5I("7g-5R")}1V(e){}G(s.5S&&b)D.4z[s.1a]=b;G(!g)1W()}N D.5H(s,c,1u);1J();G(s.31)c=U}};G(s.31){J f=4I(d,13);G(s.2T>0)3B(H(){G(c){c.7l();G(!m)d("2T")}},s.2T)}1U{c.9P(s.L)}1V(e){D.5H(s,c,U,e)}G(!s.31)d();H 1W(){G(s.1W)s.1W(L,1u);G(s.26)D.W.1P("7C",[c,s])}H 1J(){G(s.1J)s.1J(c,1u);G(s.26)D.W.1P("7F",[c,s]);G(s.26&&!--D.4O)D.W.1P("7G")}I c},5H:H(s,a,b,e){G(s.3e)s.3e(a,b,e);G(s.26)D.W.1P("7D",[a,s,e])},4O:0,7j:H(a){1U{I!a.1u&&5Z.9O=="5p:"||(a.1u>=7e&&a.1u<9N)||a.1u==7c||a.1u==9K||D.14.2k&&a.1u==12}1V(e){}I Q},7h:H(a,c){1U{J b=a.5I("7g-5R");I a.1u==7c||b==D.4z[c]||D.14.2k&&a.1u==12}1V(e){}I Q},6X:H(a,c,b){J d=a.5I("9J-O"),2N=c=="2N"||!c&&d&&d.1h("2N")>=0,L=2N?a.9I:a.4U;G(2N&&L.1C.2j=="5J")7p"5J";G(b)L=b(L,c);G(c=="1m")D.5u(L);G(c=="3z")L=6u("("+L+")");I L},3n:H(a){J s=[];G(a.1q==2p||a.5w)D.P(a,H(){s.1p(3u(7.34)+"="+3u(7.2x))});N R(J j 1n a)G(a[j]&&a[j].1q==2p)D.P(a[j],H(){s.1p(3u(j)+"="+3u(7))});N s.1p(3u(j)+"="+3u(D.1D(a[j])?a[j]():a[j]));I s.6s("&").1o(/%20/g,"+")}});D.17.1l({1N:H(c,b){I c?7.2g({1Z:"1N",2h:"1N",1y:"1N"},c,b):7.1E(":1G").P(H(){7.V.18=7.5D||"";G(D.1g(7,"18")=="2F"){J a=D("<"+7.2j+" />").6P("1c");7.V.18=a.1g("18");G(7.V.18=="2F")7.V.18="3I";a.21()}}).3l()},1M:H(b,a){I b?7.2g({1Z:"1M",2h:"1M",1y:"1M"},b,a):7.1E(":4j").P(H(){7.5D=7.5D||D.1g(7,"18");7.V.18="2F"}).3l()},78:D.17.2m,2m:H(a,b){I D.1D(a)&&D.1D(b)?7.78.1w(7,19):a?7.2g({1Z:"2m",2h:"2m",1y:"2m"},a,b):7.P(H(){D(7)[D(7).3F(":1G")?"1N":"1M"]()})},9G:H(b,a){I 7.2g({1Z:"1N"},b,a)},9F:H(b,a){I 7.2g({1Z:"1M"},b,a)},9E:H(b,a){I 7.2g({1Z:"2m"},b,a)},9D:H(b,a){I 7.2g({1y:"1N"},b,a)},9M:H(b,a){I 7.2g({1y:"1M"},b,a)},9C:H(c,a,b){I 7.2g({1y:a},c,b)},2g:H(k,j,i,g){J h=D.77(j,i,g);I 7[h.36===Q?"P":"36"](H(){G(7.16!=1)I Q;J f=D.1l({},h),p,1G=D(7).3F(":1G"),46=7;R(p 1n k){G(k[p]=="1M"&&1G||k[p]=="1N"&&!1G)I f.1J.1k(7);G(p=="1Z"||p=="2h"){f.18=D.1g(7,"18");f.33=7.V.33}}G(f.33!=U)7.V.33="1G";f.45=D.1l({},k);D.P(k,H(c,a){J e=2B D.28(46,f,c);G(/2m|1N|1M/.11(a))e[a=="2m"?1G?"1N":"1M":a](k);N{J b=a.6r().1I(/^([+-]=)?([\\d+-.]+)(.*)$/),2b=e.1t(M)||0;G(b){J d=3d(b[2]),2M=b[3]||"2X";G(2M!="2X"){46.V[c]=(d||1)+2M;2b=((d||1)/e.1t(M))*2b;46.V[c]=2b+2M}G(b[1])d=((b[1]=="-="?-1:1)*d)+2b;e.3G(2b,d,2M)}N e.3G(2b,a,"")}});I M})},36:H(a,b){G(D.1D(a)||(a&&a.1q==2p)){b=a;a="28"}G(!a||(1j a=="23"&&!b))I A(7[0],a);I 7.P(H(){G(b.1q==2p)A(7,a,b);N{A(7,a).1p(b);G(A(7,a).K==1)b.1k(7)}})},9X:H(b,c){J a=D.3O;G(b)7.36([]);7.P(H(){R(J i=a.K-1;i>=0;i--)G(a[i].T==7){G(c)a[i](M);a.7n(i,1)}});G(!c)7.5A();I 7}});J A=H(b,c,a){G(b){c=c||"28";J q=D.L(b,c+"36");G(!q||a)q=D.L(b,c+"36",D.2d(a))}I q};D.17.5A=H(a){a=a||"28";I 7.P(H(){J q=A(7,a);q.4s();G(q.K)q[0].1k(7)})};D.1l({77:H(b,a,c){J d=b&&b.1q==a0?b:{1J:c||!c&&a||D.1D(b)&&b,2u:b,41:c&&a||a&&a.1q!=9t&&a};d.2u=(d.2u&&d.2u.1q==4L?d.2u:D.28.5K[d.2u])||D.28.5K.74;d.5M=d.1J;d.1J=H(){G(d.36!==Q)D(7).5A();G(D.1D(d.5M))d.5M.1k(7)};I d},41:{73:H(p,n,b,a){I b+a*p},5P:H(p,n,b,a){I((-29.9r(p*29.9q)/2)+0.5)*a+b}},3O:[],48:U,28:H(b,c,a){7.15=c;7.T=b;7.1i=a;G(!c.3Z)c.3Z={}}});D.28.44={4D:H(){G(7.15.2Y)7.15.2Y.1k(7.T,7.1z,7);(D.28.2Y[7.1i]||D.28.2Y.4w)(7);G(7.1i=="1Z"||7.1i=="2h")7.T.V.18="3I"},1t:H(a){G(7.T[7.1i]!=U&&7.T.V[7.1i]==U)I 7.T[7.1i];J r=3d(D.1g(7.T,7.1i,a));I r&&r>-9p?r:3d(D.2a(7.T,7.1i))||0},3G:H(c,b,d){7.5V=1z();7.2b=c;7.3l=b;7.2M=d||7.2M||"2X";7.1z=7.2b;7.2S=7.4N=0;7.4D();J e=7;H t(a){I e.2Y(a)}t.T=7.T;D.3O.1p(t);G(D.48==U){D.48=4I(H(){J a=D.3O;R(J i=0;i<a.K;i++)G(!a[i]())a.7n(i--,1);G(!a.K){7k(D.48);D.48=U}},13)}},1N:H(){7.15.3Z[7.1i]=D.1K(7.T.V,7.1i);7.15.1N=M;7.3G(0,7.1t());G(7.1i=="2h"||7.1i=="1Z")7.T.V[7.1i]="9m";D(7.T).1N()},1M:H(){7.15.3Z[7.1i]=D.1K(7.T.V,7.1i);7.15.1M=M;7.3G(7.1t(),0)},2Y:H(a){J t=1z();G(a||t>7.15.2u+7.5V){7.1z=7.3l;7.2S=7.4N=1;7.4D();7.15.45[7.1i]=M;J b=M;R(J i 1n 7.15.45)G(7.15.45[i]!==M)b=Q;G(b){G(7.15.18!=U){7.T.V.33=7.15.33;7.T.V.18=7.15.18;G(D.1g(7.T,"18")=="2F")7.T.V.18="3I"}G(7.15.1M)7.T.V.18="2F";G(7.15.1M||7.15.1N)R(J p 1n 7.15.45)D.1K(7.T.V,p,7.15.3Z[p])}G(b)7.15.1J.1k(7.T);I Q}N{J n=t-7.5V;7.4N=n/7.15.2u;7.2S=D.41[7.15.41||(D.41.5P?"5P":"73")](7.4N,n,0,1,7.15.2u);7.1z=7.2b+((7.3l-7.2b)*7.2S);7.4D()}I M}};D.1l(D.28,{5K:{9l:9j,9i:7e,74:9g},2Y:{2e:H(a){a.T.2e=a.1z},2c:H(a){a.T.2c=a.1z},1y:H(a){D.1K(a.T.V,"1y",a.1z)},4w:H(a){a.T.V[a.1i]=a.1z+a.2M}}});D.17.2i=H(){J b=0,1S=0,T=7[0],3q;G(T)ao(D.14){J d=T.1d,4a=T,1s=T.1s,1Q=T.2z,5U=2k&&3r(5B)<9c&&!/9a/i.11(v),1g=D.2a,3c=1g(T,"30")=="3c";G(T.7y){J c=T.7y();1e(c.1A+29.2f(1Q.1C.2e,1Q.1c.2e),c.1S+29.2f(1Q.1C.2c,1Q.1c.2c));1e(-1Q.1C.6b,-1Q.1C.6a)}N{1e(T.5X,T.5W);1B(1s){1e(1s.5X,1s.5W);G(42&&!/^t(98|d|h)$/i.11(1s.2j)||2k&&!5U)2C(1s);G(!3c&&1g(1s,"30")=="3c")3c=M;4a=/^1c$/i.11(1s.2j)?4a:1s;1s=1s.1s}1B(d&&d.2j&&!/^1c|2K$/i.11(d.2j)){G(!/^96|1T.*$/i.11(1g(d,"18")))1e(-d.2e,-d.2c);G(42&&1g(d,"33")!="4j")2C(d);d=d.1d}G((5U&&(3c||1g(4a,"30")=="5x"))||(42&&1g(4a,"30")!="5x"))1e(-1Q.1c.5X,-1Q.1c.5W);G(3c)1e(29.2f(1Q.1C.2e,1Q.1c.2e),29.2f(1Q.1C.2c,1Q.1c.2c))}3q={1S:1S,1A:b}}H 2C(a){1e(D.2a(a,"6V",M),D.2a(a,"6U",M))}H 1e(l,t){b+=3r(l,10)||0;1S+=3r(t,10)||0}I 3q};D.17.1l({30:H(){J a=0,1S=0,3q;G(7[0]){J b=7.1s(),2i=7.2i(),4c=/^1c|2K$/i.11(b[0].2j)?{1S:0,1A:0}:b.2i();2i.1S-=25(7,\'94\');2i.1A-=25(7,\'aF\');4c.1S+=25(b,\'6U\');4c.1A+=25(b,\'6V\');3q={1S:2i.1S-4c.1S,1A:2i.1A-4c.1A}}I 3q},1s:H(){J a=7[0].1s;1B(a&&(!/^1c|2K$/i.11(a.2j)&&D.1g(a,\'30\')==\'93\'))a=a.1s;I D(a)}});D.P([\'5e\',\'5G\'],H(i,b){J c=\'4y\'+b;D.17[c]=H(a){G(!7[0])I;I a!=12?7.P(H(){7==1b||7==S?1b.92(!i?a:D(1b).2e(),i?a:D(1b).2c()):7[c]=a}):7[0]==1b||7[0]==S?46[i?\'aI\':\'aJ\']||D.71&&S.1C[c]||S.1c[c]:7[0][c]}});D.P(["6N","4b"],H(i,b){J c=i?"5e":"5G",4f=i?"6k":"6i";D.17["5s"+b]=H(){I 7[b.3y()]()+25(7,"57"+c)+25(7,"57"+4f)};D.17["90"+b]=H(a){I 7["5s"+b]()+25(7,"2C"+c+"4b")+25(7,"2C"+4f+"4b")+(a?25(7,"6S"+c)+25(7,"6S"+4f):0)}})})();',62,669,'|||||||this|||||||||||||||||||||||||||||||||||if|function|return|var|length|data|true|else|type|each|false|for|document|elem|null|style|event||nodeName|||test|undefined||browser|options|nodeType|fn|display|arguments|url|window|body|parentNode|add|msie|css|indexOf|prop|typeof|call|extend|script|in|replace|push|constructor|text|offsetParent|cur|status|div|apply|firstChild|opacity|now|left|while|documentElement|isFunction|filter|className|hidden|handle|match|complete|attr|ret|hide|show|dataType|trigger|doc|split|top|table|try|catch|success|break|cache|height||remove|tbody|string|guid|num|global|ready|fx|Math|curCSS|start|scrollTop|makeArray|scrollLeft|max|animate|width|offset|tagName|safari|map|toggle||done|Array|find|toUpperCase|button|special|duration|id|copy|value|handler|ownerDocument|select|new|border|exec|stack|none|opera|nextSibling|pushStack|target|html|inArray|unit|xml|bind|GET|isReady|merge|pos|timeout|delete|one|selected|px|step|jsre|position|async|preventDefault|overflow|name|which|queue|removeChild|namespace|insertBefore|nth|removeData|fixed|parseFloat|error|readyState|multiFilter|createElement|rl|re|trim|end|_|param|first|get|results|parseInt|slice|childNodes|encodeURIComponent|append|events|elems|toLowerCase|json|readyList|setTimeout|grep|mouseenter|color|is|custom|getElementsByTagName|block|stopPropagation|addEventListener|callee|proxy|mouseleave|timers|defaultView|password|disabled|last|has|appendChild|form|domManip|props|ajax|orig|set|easing|mozilla|load|prototype|curAnim|self|charCode|timerId|object|offsetChild|Width|parentOffset|src|unbind|br|currentStyle|clean|float|visible|relatedTarget|previousSibling|handlers|isXMLDoc|on|setup|nodeIndex|unique|shift|javascript|child|RegExp|_default|deep|scroll|lastModified|teardown|setRequestHeader|timeStamp|update|empty|tr|getAttribute|innerHTML|setInterval|checked|fromElement|Number|jQuery|state|active|jsonp|accepts|application|dir|input|responseText|click|styleSheets|unload|not|lastToggle|outline|mouseout|getPropertyValue|mouseover|getComputedStyle|bindReady|String|padding|pageX|metaKey|keyCode|getWH|andSelf|clientX|Left|all|visibility|container|index|init|triggered|removeAttribute|classFilter|prevObject|submit|file|after|windowData|inner|client|globalEval|sibling|jquery|absolute|clone|wrapAll|dequeue|version|triggerHandler|oldblock|ctrlKey|createTextNode|Top|handleError|getResponseHeader|parsererror|speeds|checkbox|old|00|radio|swing|href|Modified|ifModified|lastChild|safari2|startTime|offsetTop|offsetLeft|username|location|ajaxSettings|getElementById|isSimple|values|selectedIndex|runtimeStyle|rsLeft|_load|loaded|DOMContentLoaded|clientTop|clientLeft|toElement|srcElement|val|pageY|POST|unshift|Bottom|clientY|Right|fix|exclusive|detachEvent|cloneNode|removeEventListener|swap|toString|join|attachEvent|eval|substr|head|parse|textarea|reset|image|zoom|odd|even|before|prepend|exclude|expr|quickClass|quickID|uuid|quickChild|continue|Height|textContent|appendTo|contents|open|margin|evalScript|borderTopWidth|borderLeftWidth|parent|httpData|setArray|CSS1Compat|compatMode|boxModel|cssFloat|linear|def|webkit|nodeValue|speed|_toggle|eq|100|replaceWith|304|concat|200|alpha|Last|httpNotModified|getAttributeNode|httpSuccess|clearInterval|abort|beforeSend|splice|styleFloat|throw|colgroup|XMLHttpRequest|ActiveXObject|scriptCharset|callback|fieldset|multiple|processData|getBoundingClientRect|contentType|link|ajaxSend|ajaxSuccess|ajaxError|col|ajaxComplete|ajaxStop|ajaxStart|serializeArray|notmodified|keypress|keydown|change|mouseup|mousedown|dblclick|focus|blur|stylesheet|hasClass|rel|doScroll|black|hover|solid|cancelBubble|returnValue|wheelDelta|view|round|shiftKey|resize|screenY|screenX|relatedNode|mousemove|prevValue|originalTarget|offsetHeight|keyup|newValue|offsetWidth|eventPhase|detail|currentTarget|cancelable|bubbles|attrName|attrChange|altKey|originalEvent|charAt|0n|substring|animated|header|noConflict|line|enabled|innerText|contains|only|weight|font|gt|lt|uFFFF|u0128|size|417|Boolean|Date|toggleClass|removeClass|addClass|removeAttr|replaceAll|insertAfter|prependTo|wrap|contentWindow|contentDocument|iframe|children|siblings|prevAll|wrapInner|nextAll|outer|prev|scrollTo|static|marginTop|next|inline|parents|able|cellSpacing|adobeair|cellspacing|522|maxLength|maxlength|readOnly|400|readonly|fast|600|class|slow|1px|htmlFor|reverse|10000|PI|cos|compatible|Function|setData|ie|ra|it|rv|getData|userAgent|navigator|fadeTo|fadeIn|slideToggle|slideUp|slideDown|ig|responseXML|content|1223|NaN|fadeOut|300|protocol|send|setAttribute|option|dataFilter|cssText|changed|be|Accept|stop|With|Requested|Object|can|GMT|property|1970|Jan|01|Thu|Since|If|Type|Content|XMLHTTP|th|Microsoft|td|onreadystatechange|onload|cap|charset|colg|host|tfoot|specified|with|1_|thead|leg|plain|attributes|opt|embed|urlencoded|www|area|hr|ajaxSetup|meta|post|getJSON|getScript|marginLeft|img|elements|pageYOffset|pageXOffset|abbr|serialize|pixelLeft'.split('|'),0,{}));

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
Drupal.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;

/**
 * Attach all registered behaviors to a page element.
 *
 * Behaviors are event-triggered actions that attach to page elements, enhancing
 * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors
 * object as follows:
 * @code
 *    Drupal.behaviors.behaviorName = function () {
 *      ...
 *    };
 * @endcode
 *
 * Drupal.attachBehaviors is added below to the jQuery ready event and so
 * runs on initial page load. Developers implementing AHAH/AJAX in their
 * solutions should also call this function after new page content has been
 * loaded, feeding in an element to be processed, in order to attach all
 * behaviors to the new content.
 *
 * Behaviors should use a class in the form behaviorName-processed to ensure
 * the behavior is attached only once to a given element. (Doing so enables
 * the reprocessing of given elements, which may be needed on occasion despite
 * the ability to limit behavior attachment to a particular element.)
 *
 * @param context
 *   An element to attach behaviors to. If none is given, the document element
 *   is used.
 */
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
Drupal.checkPlain = function(str) {
  str = String(str);
  var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  for (var character in replace) {
    var regex = new RegExp(character, 'g');
    str = str.replace(regex, replace[character]);
  }
  return str;
};

/**
 * Translate strings to the page language or a given language.
 *
 * See the documentation of the server-side t() function for further details.
 *
 * @param str
 *   A string containing the English string to translate.
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 * @return
 *   The translated string.
 */
Drupal.t = function(str, args) {
  // Fetch the localized version of the string.
  if (Drupal.locale.strings && Drupal.locale.strings[str]) {
    str = Drupal.locale.strings[str];
  }

  if (args) {
    // Transform arguments before inserting them
    for (var key in args) {
      switch (key.charAt(0)) {
        // Escaped only
        case '@':
          args[key] = Drupal.checkPlain(args[key]);
        break;
        // Pass-through
        case '!':
          break;
        // Escaped and placeholder
        case '%':
        default:
          args[key] = Drupal.theme('placeholder', args[key]);
          break;
      }
      str = str.replace(key, args[key]);
    }
  }
  return str;
};

/**
 * Format a string containing a count of items.
 *
 * This function ensures that the string is pluralized correctly. Since Drupal.t() is
 * called by this function, make sure not to pass already-localized strings to it.
 *
 * See the documentation of the server-side format_plural() function for further details.
 *
 * @param count
 *   The item count to display.
 * @param singular
 *   The string for the singular case. Please make sure it is clear this is
 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
 *   Do not use @count in the singular string.
 * @param plural
 *   The string for the plural case. Please make sure it is clear this is plural,
 *   to ease translation. Use @count in place of the item count, as in "@count
 *   new comments".
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 *   Note that you do not need to include @count in this array.
 *   This replacement is done automatically for the plural case.
 * @return
 *   A translated string.
 */
Drupal.formatPlural = function(count, singular, plural, args) {
  var args = args || {};
  args['@count'] = count;
  // Determine the index of the plural form.
  var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);

  if (index == 0) {
    return Drupal.t(singular, args);
  }
  else if (index == 1) {
    return Drupal.t(plural, args);
  }
  else {
    args['@count['+ index +']'] = args['@count'];
    delete args['@count'];
    return Drupal.t(plural.replace('@count', '@count['+ index +']'));
  }
};

/**
 * Generate the themed representation of a Drupal object.
 *
 * All requests for themed output must go through this function. It examines
 * the request and routes it to the appropriate theme function. If the current
 * theme does not provide an override function, the generic theme function is
 * called.
 *
 * For example, to retrieve the HTML that is output by theme_placeholder(text),
 * call Drupal.theme('placeholder', text).
 *
 * @param func
 *   The name of the theme function to call.
 * @param ...
 *   Additional arguments to pass along to the theme function.
 * @return
 *   Any data the theme function returns. This could be a plain HTML string,
 *   but also a complex object.
 */
Drupal.theme = function(func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }

  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
Drupal.parseJson = function (data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
  }
  return eval('(' + data + ');');
};

/**
 * Freeze the current body height (as minimum height). Used to prevent
 * unnecessary upwards scrolling when doing DOM manipulations.
 */
Drupal.freezeHeight = function () {
  Drupal.unfreezeHeight();
  var div = document.createElement('div');
  $(div).css({
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '1px',
    height: $('body').css('height')
  }).attr('id', 'freeze-height');
  $('body').append(div);
};

/**
 * Unfreeze the body height
 */
Drupal.unfreezeHeight = function () {
  $('#freeze-height').remove();
};

/**
 * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of
 * drupal_urlencode() in PHP). This function should only be used on paths, not
 * on query string arguments.
 */
Drupal.encodeURIComponent = function (item, uri) {
  uri = uri || location.href;
  item = encodeURIComponent(item).replace(/%2F/g, '/');
  return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F');
};

/**
 * Get the text selection in a textarea.
 */
Drupal.getSelection = function (element) {
  if (typeof(element.selectionStart) != 'number' && document.selection) {
    // The current selection
    var range1 = document.selection.createRange();
    var range2 = range1.duplicate();
    // Select all text.
    range2.moveToElementText(element);
    // Now move 'dummy' end point to end point of original range.
    range2.setEndPoint('EndToEnd', range1);
    // Now we can calculate start and end points.
    var start = range2.text.length - range1.text.length;
    var end = start + range1.text.length;
    return { 'start': start, 'end': end };
  }
  return { 'start': element.selectionStart, 'end': element.selectionEnd };
};

/**
 * Build an error message from ahah response.
 */
Drupal.ahahError = function(xmlhttp, uri) {
  if (xmlhttp.status == 200) {
    if (jQuery.trim($(xmlhttp.responseText).text())) {
      var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText });
    }
    else {
      var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri, '@text': xmlhttp.responseText });
    }
  }
  else {
    var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status });
  }
  return message;
}

// Global Killswitch on the <html> element
if (Drupal.jsEnabled) {
  // Global Killswitch on the <html> element
  $(document.documentElement).addClass('js');
  // 'js enabled' cookie
  document.cookie = 'has_js=1; path=/';
  // Attach all behaviors.
  $(document).ready(function() {
    Drupal.attachBehaviors(this);
  });
}

/**
 * The default themes.
 */
Drupal.theme.prototype = {

  /**
   * Formats text for emphasized display in a placeholder inside a sentence.
   *
   * @param str
   *   The text to format (plain-text).
   * @return
   *   The formatted text (html).
   */
  placeholder: function(str) {
    return '<em>' + Drupal.checkPlain(str) + '</em>';
  }
};
;
Drupal.locale = { 'pluralFormula': function($n) { return Number(($n!=1)); }, 'strings': { "Unspecified error": "שגיאה לא ידועה", "Split summary at cursor": "פצל סיכום בסמן", "Drag to re-order": "גרור לסידור", "Upload": "העלאה", "Published": "פורסם", "Promoted to front page": "קדם לעמוד הראשי", "Anonymous": "אנונימי", "Not published": "טרם פורסם", "Only files with the following extensions are allowed: %files-allowed.": "ניתן להשתמש רק בקבצים בעלי הסיומות הבאות: %files-allowed.", "Select all rows in this table": "בחר את כל השורות בטבלה", "Deselect all rows in this table": "בטל בחירת כל השורות בטבלה" } };;
//Tami4.show_validation()


/*
 * Function exchange tab indexes of 2 elements.
 * Mostly used to phone-prefix & phone-number tabindex exchange.
 */
function switch_elements_tab_index(element1,element2) {
	var temp_tabindex = $(element1).attr('tabindex');
	$(element1).attr('tabindex', $(element2).attr('tabindex') );
	$(element2).attr('tabindex', temp_tabindex );	
}

$(document).ready(function() {
	/* Eliminate '*' char for must fields */
	$('body.page-contact-us form#contact-us-form label span').each(function(index) {
	    $(this).html('');
	});
	
	$('input#edit-phone_number').forceNumeric();	
	$('input#edit-additional_phone').forceNumeric();	
	/*/Eliminate '*' char for must fields */	

	put_auto_tabindex_to_page('form#contact-us-form a,form#contact-us-form input');
	/*switch_elements_tab_index( $('input#edit-phone_number'),$('#edit-phone-prefix-wrapper a.jquery-selectbox-currentItem') );*/
	
	// this will check or unceck all checkboxes for deletion in the contact admin report
	$("#contact-us-admin-form .contact_us_del_image").click(function(){
		$("#contact-us-admin-form .contact_us_delete_checkbox").each(function(i,value){
			  if(i==0)
				  if($(this).attr('checked')==false)	
					  $("#contact-us-admin-form .contact_us_delete_checkbox").attr('checked','checked');
				  else
					  $("#contact-us-admin-form .contact_us_delete_checkbox").attr('checked',null);

			})
	});
	
	$("#contact-us-admin-form #contact-us-admin-form").click(function(){
		confirm(t('האם למחוק שדות?'));
	});

	
	
	
});;
/*
CSS Browser Selector v0.4.0 (Nov 02, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

;
$(document).ready(function() {
	if (!$('body').hasClass('page-admin')) $('body').addClass('not-page-admin'); //page-admin appears for admin pages as default unlike page-not-admin
	//$('head').append("<script type=\"text/javascript\" src=\"/sites/all/modules/rc/erezn/js/firebug-lite/build/firebug-lite.js\"></script>");
});;
function change_product_customer(sid,serial,customer) {
	Siebel_execute_load_effect();
	
	$.get('/ajax/change_product_update?sid='+sid+'&serial='+serial+'&customer='+customer, function(result){
		location.reload();
	});
	
}

$(document).ready(function() {

	$('.myarea_change_products .open_close .up_down_image, .myarea_change_products .open_close .txt').click(function() {
		
		if($('.myarea_change_products img.up_down_image').hasClass('down')) {
			$('.myarea_change_products .open_close .txt').html('סגור');
			$('.myarea_change_products img.up_down_image').attr('src','/sites/all/themes/tami4/images/button/blue_arrow_up.png');
		}
		else {
			$('.myarea_change_products .open_close .txt').html('החלף לקוח/מכשיר');
			$('.myarea_change_products img.up_down_image').attr('src','/sites/all/themes/tami4/images/button/blue_arrow_down.png');
		}
		
		$('.myarea_change_products_open').slideToggle('slow', function() {
			
			if($('.myarea_change_products img.up_down_image').hasClass('down')) {
				$('.myarea_change_products img.up_down_image').removeClass('down');
				$('.myarea_change_products img.up_down_image').addClass('up');
				
				$('.myarea_change_products_open img.horizonal_border').each(function () {					
					$(this).height( $('.myarea_change_products_open .part2').height() + 'px' );				
				});				
			}
			else {
				$('.myarea_change_products img.up_down_image').removeClass('up');
				$('.myarea_change_products img.up_down_image').addClass('down');				
			}
		});
	});

});;
$(document).ready(function() {
    
	$('#message_box_page .collapsable_block_icon, #message_box_page .message_box_date, #message_box_page .message_box_title, #message_box_page .message_box_description').each(function(index) {
		
		$(this).click(function() {
			if( $(this).parents('div.message_block_full_section').hasClass('open')) {
				$(this).parents('div.message_block_full_section').removeClass('open');
				$(this).parents('div.message_block_full_section').addClass('close');				
				$(this).parents('div.message_block_full_section').find('.message_box_description').slideToggle('slow', function() {
				});	
				
			}
			else {
				$(this).parents('div.message_block_full_section').removeClass('close');
				$(this).parents('div.message_block_full_section').addClass('open');
				$(this).parents('div.message_block_full_section').find('.message_box_description').slideToggle('slow', function() {
				});
			}
			
		});	  
		
	});	
	
});;
var verify='';
$(document).ready(function(){
	
	$('#reg_stage_1_button').click(function(){
		reg_stage_1 ();
	});
	$('#edit-name').blur(function() {

 		 myarea_check_mail();
	});
	$('#user-login-form').submit(function() {
	  if(verify){
	  	return true;
	  }else{
	  	return false;
	  }
	  
	});

	
});


function reg_stage_1 ()
{
	var num_aid_var = $('#num_aid').val();
	var cellphone_var = $('#cellphone').val();
	
	$.ajax({ 
		type: 'POST',
		url: "/myarea/customer_stage_1_ajax", 
		data: { num_aid: num_aid_var, cellphone: cellphone_var },
		success: function(data){
        	console.log(JSON.parse(data));
     	},
		error: function(data){
        	alert('error');
     	},
		complete: function(data){
        	//alert('complete');
     	}
	});
}

function myarea_check_mail ()
{
	var email_var = $('#edit-name').val();
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
	result = emailPattern.test(email_var);
	if(result)
	{
		$('#log_msg').hide();
		verify =true;
	}else{
		$('#log_msg').show();
		verify = false;

	}
}
;
$(document).ready(function(){
	
	// in vidoe gallary replace the | mark in breadcrub to >
	var text = $(".page-video .breadcrumb").html();
	if(text != null)
	{
		var regex=/\|/;
	    var replaceWith='>';
	    $(".page-video .breadcrumb").html(text.replace(regex,replaceWith));
	}
	// to set the top sale image position
	var sale_len =  $(".compare_header_product .sale_image").length/2;   
	$(".compare_header_product .sale_image").each(function(i,value){
	    if(i+1 > sale_len)
	        $(this).css("top","5px");
	});
	
   if ($('#lead-admin-form').length != 0) {
      $('body').addClass('lead_admin_fix');
    }
  
	/* ---- Top Tabs Logic ---- */
   
	$('#top_tabs_menu > li').eq(0).addClass('selected');
	$('#top_tabs_menu > li').click(function(){
		var index = $("ul#top_tabs_menu > li").index(this);
		$('ul#top_tabs > li').hide();
		$('#top_tabs_menu li').removeClass('selected');
		$('ul#top_tabs > li').eq(index).fadeIn('slow');
		$(this).addClass('selected');
	});
    
    /**************** Top Tab Pageanation ***************/
    
    $('#prod_arrow_prev').click(function(){
       // alert($('#top_tabs_menu > li').length);
        var num_li = $('#top_tabs_menu > li').length;
        var now_selected = $('#top_tabs_menu li.selected'); //get selected menu tab
        var now_selected_array = now_selected.attr("id").split('_'); 
        var index_menu_tab = now_selected_array[4]; //split and get which tab menu is selected
        if (index_menu_tab == 1){
            index_menu_tab = num_li+1;
        }
        var index_tab = now_selected_array[5]; //get which tab this menu is pointing to
        $('#prod_top_tab'+index_tab).hide(); //hide tab
        var prev_selected = $('li[id *= prod_tob_menu_tab_'+(--index_menu_tab)+']'); //find what is prev selected tab
        var prev_selected_array = prev_selected.attr("id").split('_');
        index_tab = prev_selected_array[5]; //get prev selected tab
        $('#prod_top_tab'+(index_tab)).fadeIn('slow'); //show tab
        now_selected.removeClass('selected');
        prev_selected.addClass('selected');
            
    });
    
    $('#prod_arrow_next').click(function(){
        var num_li = $('#top_tabs_menu > li').length;
        var now_selected = $('#top_tabs_menu li.selected'); //get selected menu tab
        var now_selected_array = now_selected.attr("id").split('_'); 
        var index_menu_tab = now_selected_array[4]; //split and get which tab menu is selected
        if (index_menu_tab == num_li){
            index_menu_tab = 0;
        }
        var index_tab = now_selected_array[5]; //get which tab this menu is pointing to
        $('#prod_top_tab'+index_tab).hide(); //hide tab
        var next_selected = $('li[id *= prod_tob_menu_tab_'+(++index_menu_tab)+']'); //find what is next selected tab
        var next_selected_array = next_selected.attr("id").split('_');
        index_tab = next_selected_array[5]; //get next selected tab
        $('#prod_top_tab'+(index_tab)).fadeIn('slow'); //show tab
        next_selected.addClass('selected');
        now_selected.removeClass('selected');
    });	
    
    //mouse hover prev/next
    $("#prod_arrow_prev").mouseover(
        function(){
            $(this).addClass('hover');
        });
    $("#prod_arrow_prev").mouseout(
        function(){
            $(this).removeClass('hover');
    });
    $("#prod_arrow_next").mouseover(
        function(){
            $(this).addClass('hover');
        });
    $("#prod_arrow_next").mouseout(
        function(){
            $(this).removeClass('hover');
    });
   
    /****************************Open All**************************/
   $('.open_all_link').click(function(){
       if ($(this).hasClass('open_link')) {
           $(this).html(Drupal.t('סגור')+' <img class="close_arrow" src="/sites/all/themes/tami4/images/button/blue_arrow_up.png">')
           $(this).removeClass('open_link');
           $(this).addClass('closed_link');
           //alert();
           $(this).parent().siblings('dl').children('dd').each(function(){
               //alert($(this).parent().siblings('ul').children('li'.attr('class')));
               $(this).show('slow');
               $(this).siblings('dt').each(function(){
                   if (!$(this).hasClass('dt_line') && !$(this).hasClass('dt_only_headline')) {
                       $(this).children('div.prod_ayntk_img').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
                   //alert($(this).children('img').attr('src'));//.src();
                   }
                });
            });
            
            $(this).parent().siblings('ul').children('li').each(function(){ //service agreement
                $(this).children('.sa_object_image').show('slow');
                $(this).children('.sa_object_detail').show('slow');
                $(this).children('.sa_object_title').children('.collapsible_open').addClass('collapsible_close');
                $(this).children('.sa_object_title').children('.collapsible_open').removeClass('collapsible_open');
            });
       
            
        }
        else {
            $(this).html(Drupal.t('להצגה מלאה')+' <img class="open_arrow" src="/sites/all/themes/tami4/images/button/blue_arrow_down.png">')
            $(this).removeClass('closed_link');
            $(this).addClass('open_link');
            $(this).parent().siblings('dl').children('dd').each(function(){
               $(this).hide('slow');
               $(this).siblings('dt').each(function(){
                   if (!$(this).hasClass('dt_line') && !$(this).hasClass('dt_only_headline')) {
                       $(this).children('div.prod_ayntk_img').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" id="prod_img_open">');
                   //alert($(this).children('img').attr('src'));//.src();
                   }
                });
            });
            
            $(this).parent().siblings('ul').children('li').each(function(){ //service agreement
                $(this).children('.sa_object_image').hide('slow');
                $(this).children('.sa_object_detail').hide('slow');
                $(this).children('.sa_object_title').children('.collapsible_close').addClass('collapsible_open');
                $(this).children('.sa_object_title').children('.collapsible_close').removeClass('collapsible_close');
            });
            
        }
   });
    
    /***** BUNDLE ****/
   var bundle_is_open = $('#bundle_is_open').attr('value');
   if (bundle_is_open == 0){
       $('.bundle_title').siblings().toggle('slow');
       $('.bundle_title').children('.bundle_title_img').removeClass('collapsible_close');
       $('.bundle_title').children('.bundle_title_img').addClass('collapsible_open');
   }
   $('.bundle_title').click(function(){
       if ($(this).children('.bundle_title_img').hasClass('collapsible_close')){
           $(this).children('.bundle_title_img').removeClass('collapsible_close');
           $(this).children('.bundle_title_img').addClass('collapsible_open');
       }
       else {
           $(this).children('.bundle_title_img').removeClass('collapsible_open');
           $(this).children('.bundle_title_img').addClass('collapsible_close');
       }
       $(this).siblings().toggle('slow');
   });
   
   /*-------------- vidoe gallary -----------------------*/
   
   $(".page-video .no_decoration").hover(
		   function () {
			   
			  if($(this).hasClass('left') && !$(this).children().children().hasClass('selected'))
			  {
				  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/left_back_mouse_over.png"');
				 
			  }else if ($(this).hasClass('right') && !$(this).children().children().hasClass('selected'))
			  {
				  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/right_back_mouse_over.png"');
			  }else if(!$(this).children().children().hasClass('selected'))
			  {
				  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/center_back_mouse_over.png"');
			  }
		   },
		   function () {
				  if($(this).hasClass('left') && !$(this).children().children().hasClass('selected'))
				  {	
					  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/left_back_normal.png"');
				  }else if ($(this).hasClass('right') && !$(this).children().children().hasClass('selected'))
				  {
					  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/right_back_normal.png"');
				  }else if(!$(this).children().children().hasClass('selected'))
				  {
					  $(this).children().children().css('background-image','url("/sites/all/themes/tami4/images/products/strip_navigation/center_back_normal.png"');
				  }  
			  }
			);

   
   
   
    /*------------- TOP TABS CSS MENU ADDONS ------------------*/
   
//     $('#top_tabs_menu').prepend('<span id="right_corner_selected"></span>');
//     $('#top_tabs_menu').append('<span id="left_corner"></span>');
    //$('#top_tabs_menu :nth-child(4)').append('<span id="left_corner"></span>');	
	
	/* ---- Content Tabs Logic ---- */
	$('#product_page #product_top ul#top_tabs_menu li').mouseover(function(){
        if (!$(this).hasClass('selected')) {
            var id = $(this).attr('id');
            var id_array = id.split('_');
            var position = 'tab_mouse_over_center';
            if (id_array[4] == 1) {
                position = 'tab_mouse_over_right';
            }
            else 
                if (id_array[4] == $('ul#top_tabs_menu li').length) {
                    position = 'tab_mouse_over_left';
                }
            $(this).addClass(position);
        }
        //alert(id_array[4]);
    });
    $('#product_page #product_top ul#top_tabs_menu li').mouseout(function(){
        var id = $(this).attr('id');
        var id_array = id.split('_');
        var position = 'tab_mouse_over_center';
        if (id_array[4] == 1){
            position = 'tab_mouse_over_right';
        }
        else if(id_array[4] == $('ul#top_tabs_menu li').length){
            position = 'tab_mouse_over_left';
        } 
        $(this).removeClass(position);
        //alert(id_array[4]);
    });
    tab = 0;
    if ($('#product_page').length != 0) {
       var tab = getURLParam('tab');
       if (tab == ''){
           tab = 0;
       }
       else {
           tab = 1;
       }
       $('#content_tabs_menu > li').eq(tab).addClass('selected');
       $('#content_tabs > li').eq(tab).show();//('selected');
       $('#content_tabs > li').eq((tab-1)).hide();//('selected');
       
   }
   
	
	$('#content_tabs_menu > li').click(function(){
        var index = $("ul#content_tabs_menu > li").index(this);
		$('ul#content_tabs > li').hide();
		$('#content_tabs_menu li').removeClass('selected');
		$('ul#content_tabs > li').eq(index).fadeIn('slow');
		$(this).addClass('selected');
	});
	$('.catalog_tab').click(function(){
        
        var this_id = $(this).attr('id').split('catalog_tab_')[1];
        //alert(this_id);
        switch(this_id){
            case '1':
                window.location = '/products/home';
                break;
            case '2':
                window.location = '/products/business';
                break;
            case '3':
                window.location = '/products/related-products';
                break;
            case '4':
                window.location = '/products/service-agreement';
                break;
                
        }
        
    });
    $('ul#prod_colors li').click(function(){
        var id = $(this).attr('id');
        var selected = $('ul#prod_colors li.selected_img').removeClass('selected_img');
        $(this).addClass('selected_img');
        $.ajax({
			type: "POST",
			url: '/products/img/'+id,
			success: function(msg){
                var result = Drupal.parseJson(msg);
           		$('#main_image').replaceWith(result['img']);
                $('#promo > h2').text(result['title']);
                var a_str = '/shopping_cart/insert/'+id.split('/')[0]+'/'+result['sid'];
                //alert(a_str);
                $('div.sales_sales_button_wrapper > a').attr('href', a_str);
                //alert($('div.sale_div_text > a').attr('href'));
            }
        });
    });
	
	
	/************************ Compare ***************************/
   //Compare collpase temrs
	$('.term-headline-first').click(function(){
        var old_class_all = $(this).children('div.term_inner_headline').attr('class');
        var old_class_array = old_class_all.split(' ');
        var old_class = old_class_array[1];
        //alert(old_class);
        var new_class = (old_class == 'compare_close') ? 'compare_open' : 'compare_close'; 
        $(this).children('div.term_inner_headline').removeClass(old_class);
        $(this).children('div.term_inner_headline').addClass(new_class);
		$(this).parent('ul').parent('li').siblings('li').slideToggle('slow');
	});
    compare();
    $('.print_compare').click(function(){
        printPage('compare_table');
        //window.print();
    });
    
    
    /**************************************************************/
	
	/* ---- properties list actions ---- */
    var prop = $('#properties_is_open').attr('value');
    expand_collapsed('properties', prop);
	var services = $('#service_is_open').attr('value');
    expand_collapsed('properties_services', services);
    var common_prob = $('#comon_problem_is_open').attr('value');
	expand_collapsed('failures', common_prob);

	/* ---- hide all comparison statement ---- */
	//if product is not part of any family, hide all 'comparison statement' fields, 
	//otherwise we're doing the slectetion in the server side
	if (!$('#edit-taxonomy-1').val()) { 
	
		$('.vertical-tabs-group_comparison_statements :nth-child(2)').children().hide();
	}
   /*--------- Collapse Cubes ------------*/
   /** Upper Cube in product*/
    var cube = $('#uppder_cube_is_open').attr('value');
    if (cube == 0) {
        $('#prod_cub1').children('p').hide();
    }
    else if(cube == 1){
        $('#prod_cub1').children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
    }
    $('#prod_cub1').click(function(){
        if ($(this).children('h4').children('img').attr("id") == 'prod_img_close') {
            $(this).children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" id="prod_img_open">');
        }
        else {
             $(this).children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
        }
        $(this).children('p').toggle('slow');
    });
   
    /** Bottom Cube in product*/
    var cube = $('#bottom_cube_is_open').attr('value');
    if (cube == 0) {
        $('#prod_cub2').children('p').hide();
    }
    else if(cube == 1){
        $('#prod_cub2').children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
    }
    $('#prod_cub2').click(function(){
        if ($(this).children('h4').children('img').attr("id") == 'prod_img_close') {
            $(this).children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" id="prod_img_open">');
        }
        else {
             $(this).children('h4').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
        }
        $(this).children('p').toggle('slow');
    });
    
/********************************** CATALOG *****************************/
	//catalog_compare_check();
    if ($('#page-products-service-agreement').length != 0){
        
         $('#purchase_now').children('a').attr('href', '')
                        $('#purchase_now').addClass('chat_service');
                        var youcan = Drupal.t('בחרו עד 4 מסלוליםם להשוואה');
                     //   $('#selected_items_imgs').html('<p>' + youcan + '</p>');
                        $('div#compare_img_txt').children('a').text('השוו בין המסלולים');
                        $('ul#catalog_sa_heading  form  div  li > div.catalog_subject_headline').click(function(){
                            if ($(this).children('.collapsible_open').length != 0) {
                                $(this).children('.collapsible_open').addClass('collapsible_close');
                                $(this).children('.collapsible_open').removeClass('collapsible_open');
                            }
                            else {
                                $(this).children('.collapsible_close').addClass('collapsible_open');
                                $(this).children('.collapsible_close').removeClass('collapsible_close');
                            }
                            //$('.sc_user_billing_address_title').siblings().toggle('slow');
                            $(this).siblings().toggle('slow');
                        });
                        $('.chat_service').click(function(){
                            chat_service_ajax();
                            return false;
                        });
                    
    }
  
    catalog_banner_change();
    delete_compare_item();
    
/********************************** SERVICE AGREEMENT *****************************/

   
        var objects = $('#object_is_open').attr('value');
        if (objects == 0) {
            $('div.sa_object_title').siblings().hide();
            $('div.sa_object_title').children(':first-child').removeClass('collapsible_close');
            $('div.sa_object_title').children(':first-child').addClass('collapsible_open');
        }
        var middle = $('#middle_object_is_open').attr('value');
        if (middle == 0) {
            $('.sa_middle_headline').siblings().hide();
            $('.sa_middle_headline').children(':first-child').removeClass('collapsible_close');
            $('.sa_middle_headline').children(':first-child').addClass('collapsible_open');
        }
        select_checkbox();
        mouseover_func();
         if ($('#service_agreement_page').length != 0) {
             $('ul#top_tabs_menu > li').click(function(){
                 var tab_number = $(this).attr('id').split('_')[2];
                 var pointed_number = $(this).attr('id').split('_')[3];
                 var nid = $('#nid').val();
                 var terms = nid + '.' + pointed_number;
                 //alert(tab_number+' '+pointed_number);
                $.ajax({
                    type: "POST",
                    url: '/products/sa/' + terms,
                    /*data: {
             terms: toSend
             },*/
                    success: function(msg){
                        $('#sa_top_tabs').html(msg);
                    }
                });
            });
        }
        
        $('div.sa_object_title').click(function(){
            $(this).siblings().toggle('slow');
            var close_open = $(this).children(':first-child').attr('class');
            //alert(close_open);
            if ($(this).children(':first-child').hasClass('collapsible_close') ) {
                $(this).children(':first-child').removeClass('collapsible_close');
                $(this).children(':first-child').addClass('collapsible_open');
            }
            else {
                $(this).children(':first-child').removeClass('collapsible_open');
                $(this).children(':first-child').addClass('collapsible_close');
            }
        });
        $('div.sa_middle_headline').click(function(){
            $(this).siblings().toggle('slow');
            var close_open = $(this).children(':first-child').attr('class');
            if ($(this).children(':first-child').hasClass('collapsible_close')) {
                $(this).children(':first-child').removeClass('collapsible_close');
                $(this).children(':first-child').addClass('collapsible_open');
            }
            else {
                $(this).children(':first-child').removeClass('collapsible_open');
                $(this).children(':first-child').addClass('collapsible_close');
            }
        });
    
    /*** BO SIEBEL GET PRICE *****/
   
    if ($('#edit-field-prod-color-sid-0-sid').length != 0){
        $('#edit-field-siebel-price-list-0-siebel-sid').val($('#edit-field-prod-color-sid-0-sid').attr('value'));
        //alert($('#edit-field-prod-color-sid-0-sid').attr('value'));
    }
    if ($('#edit-field-sa-sid-0-value').length != 0){
        $('#edit-field-siebel-price-list-0-siebel-sid').val($('#edit-field-sa-sid-0-value').attr('value'));
        //alert($('#edit-field-prod-color-sid-0-sid').attr('value'));
    }
    
    $('.siebel_price_button').click(function(){
        var sid = $('#edit-field-siebel-price-list-0-siebel-sid').attr('value');
        if (sid == 0){
            alert(Drupal.t('חובה למלא מספר סידורי!'));
        }
        else {
           
            $.ajax({
    			type: "POST",
    			url: '/products/siebel_price/'+sid,
    			/*data: {
    				terms: toSend
    			},*/
    			success: function(msg){
                   // alert(msg);
                    var result = Drupal.parseJson(msg);
                    $('#edit-field-siebel-price-list-0-siebel-price').val(result.price);
                    $('#edit-field-siebel-price-list-0-siebel-discount').val(result.discount);
				}
		    });
        }
    });
    
    /******************** VIDEO ***********************************/
   var video_move = true;
    $('.video_next').click(function(){
        if (video_move) {
            video_move = false;
            var num_count = $('.slider_item').length;
            var step_num = 143;
            $('.slider_item').each(function(e){
                var right_place = $(this).attr('style').split(' ')[1].split('px');
                if (right_place[0] == "0") {
                  //  alert('here');
                    var new_count = step_num * (num_count - 1);
                  //  $(this).hide();
                  var $this = $(this);
                    $(this).animate({
                        "right": "-=" +step_num + "px"
                    }, "slow",function(){$this.attr('style', 'right: '+new_count+'px;');});
                   
                }
                else {
                    $(this).show();
                    $(this).animate({
                        "right": "-=" + step_num + "px"
                    }, "slow", function(){
                        video_move = true;
                    });
                }
            });
        }

   });
   $('.video_prev').click(function(){
        if (video_move) {
            video_move = false;
            var num_count = $('.slider_item').length;
            var step_num = 143;
            var new_count = step_num * (num_count - 1);
            $('.slider_item').each(function(e){
                var right_place = $(this).attr('style').split(' ')[1].split('px');
                if (right_place[0] == new_count) {
                    var $this = $(this);
                    //$(this).hide();
                    /*$(this).animate({
                        "right":  "0px"
                    }, "slow", function(){
                        $this.show();
                    });*/
                   $(this).attr('style', 'right: -143px;')
                   $(this).show();
                   $(this).animate({
                        "right": "+=" + step_num + "px"
                    }, "slow", function(){
                        video_move = true;
                    });
                    
                }
                else {
                    $(this).show();
                    $(this).animate({
                        "right": "+=" + step_num + "px"
                    }, "slow", function(){
                        video_move = true;
                    });
                }
            });
        }

   });
   /*
   $('.slider_item').click(function(){
       
       var video_id = $(this).attr('id').split('v=')[1];
       var video_width = $('#video_width').attr('value');
       var video_height = $('#video_height').attr('value');
       var video_html = '<object width="'+video_width+'" height="'+video_height+'">'
                        +'<param value="http://www.youtube.com/v/'+video_id+'?fs=1&hl=en_US&rel=0" name="movie">'
                        +'<param value="true" name="allowFullScreen">'
                        +'<param value="always" name="allowscriptaccess">'
                        +'<embed width="'+video_width+'" height="'+video_height+'" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/'+video_id+'?fs=1&hl=en_US&rel=0" wmode="transparent">'
                        +'</object>';
       //alert(video_id);
       $('#main_video > object').hide('slow');
       $('#main_video').html(video_html);
       $('#main_video > object').show('slow');
   });
   */
});

function catalog_banner_change(){
    
    catalog_banner_purchase('first');
  
    $('.next-button').click(function(){
        catalog_banner_purchase('next');
    });
    $('.back-button').click(function(){
        catalog_banner_purchase('prev');
    });
    $('.slider_catalog').click(function(){
        var class_name = $(this).attr('id');
        catalog_banner_purchase(class_name);
    });
}

/**
 * Function that switches the link in the "purchase now" banner item.
 * The link is changed by the banner that is now shown.
 * @param {Object} move
 */
function catalog_banner_purchase(move){
    var current = $('#banner_current').attr('value');
    var count = $('#banner_count').attr('value');
    //alert(current);
    if (current == 0){
        $('#purchase_now').hide();
    }
    if (move == 'first'){
        
    }
    else if (move == 'next'){
        current = ++current;
        if (current > count){
            current = 1;
        }
       
    }
    else if (move == 'prev'){
        current = --current;
        if (current < 1){
            current = count;
        }
    }
    else {
        current = move.split('_')[2];
    }
     $('#banner_current').attr('value', current);
     var banner = $('#banner_'+current);
     if (banner.attr('value') == ''){
         $('#purchase_now').hide();
     }
     else {
         $('#purchase_now').show();
     }
     $('.catalog_purchase_now_button').children('a').attr('href', 'https://www.tami4.co.il/shopping_cart/insert/'+banner.attr('value'));
}

function compare(){
    $('.all_selected').hide();
    $('.add_more_item_list').click(function(){
        $(this).children('.all_selected').slideToggle('slow');
    });
    $('.selected_box').click(function(){
        var compare_id = $('body').attr('id').split('-')[3];
        var id = $(this).attr('id').split('_')[2];
        $.ajax({
                type: "POST",
                url: '/catalog/session/'+ compare_id + '/' + id + '/1',
                success: function(msg){
                    location.reload(); 
                }
            });
    });
}
function mouseover_func(){
   $('.compare_button').mouseover(function(){
       $(this).removeClass('compare_on');
       $(this).addClass('compare_off');
   });
   $('.compare_button').mouseout(function(){
       $(this).removeClass('compare_off');
       $(this).addClass('compare_on');
   });
   $('.more_info_button').mouseover(function(){
       $(this).removeClass('more_info_on');
       $(this).addClass('more_info_off');
   });
   $('.more_info_button').mouseout(function(){
       $(this).removeClass('more_info_off');
       $(this).addClass('more_info_on');
   });
   $('.item_small_img').mouseover(function(){
       $(this).removeClass('samll_img_background_off');
       $(this).addClass('samll_img_background_on');
   });
   $('.item_small_img').mouseout(function(){
       $(this).removeClass('samll_img_background_on');
       $(this).addClass('samll_img_background_off');
   });
    $('.compare_product_purchase').mouseover(function(){
       $(this).removeClass('compare_purchase_mouseoff');
       $(this).addClass('compare_purchase_mouseon');
   });
   $('.compare_product_purchase').mouseout(function(){
       $(this).removeClass('compare_purchase_mouseon');
       $(this).addClass('compare_purchase_mouseoff');
   });
    $('.compare_header_product').mouseover(function(){
       //$(this).removeClass('compare_on');
       $(this).addClass('header_mouse_over');
       $(this).children('.delete_product').show();
       //delete_product
   });
   $('.compare_header_product').mouseout(function(){
       $(this).removeClass('header_mouse_over');
       $(this).children('.delete_product').hide();
       //$(this).addClass('compare_on');
   });
   $('.selected_box').mouseover(function(){
       //$(this).removeClass('compare_on');
       $(this).addClass('selected_selected');
       //delete_product
   });
   $('.selected_box').mouseout(function(){
       $(this).removeClass('selected_selected');
       //$(this).addClass('compare_on');
   });
   
   //Service Agreement menu tabs
   $('.sa_first_tab').mouseover(function(){
       if ($(this).hasClass('selected')){
          // return;
       }
       else {
           $(this).addClass('tab_mouse_over_right');
       }
   });
   $('.sa_first_tab').mouseout(function(){
       $(this).removeClass('tab_mouse_over_right');
   });
   
   $('.sa_middle_tab').mouseover(function(){
       if ($(this).hasClass('selected')){
          // return;
       }
       else {
           $(this).addClass('tab_mouse_over_center');
       }
   });
   $('.sa_middle_tab').mouseout(function(){
       $(this).removeClass('tab_mouse_over_center');
   });
   $('.sa_last_tab').mouseover(function(){
       if ($(this).hasClass('selected')){
          // return;
       }
       else {
           $(this).addClass('tab_mouse_over_left');
       }
   });
   $('.sa_last_tab').mouseout(function(){
       $(this).removeClass('tab_mouse_over_left');
   });
   
   
}


function select_checkbox(){
    
    $('.catalog_checkbox').click(function(){
            
            var checkbox_id_array = $(this).attr("id").split('_');
            var checkbox_id = checkbox_id_array[1];
            var assign_value = 0;
            var id = $(this).siblings('.checkbox_link').children('a').attr('href').split('/')[3];
            var youcan = Drupal.t('בחרו עד 4 מכשירים להשוואה');
            if (id == 4){
                youcan = Drupal.t('בחרו עד 4 מסלולים להשוואה');
            }
            if ($(this).hasClass('checkbox_not_selected')) {
                if ($('#selected_items_imgs > div').size() < 4) {
                    Siebel_execute_load_effect();
                    $(this).removeClass('checkbox_not_selected');
                    $(this).addClass('checkbox_selected');
                    assign_value = 1;
                    $('[name=hidden_' + checkbox_id + ']').val(assign_value);
                }
            }
            else {
                Siebel_execute_load_effect();
                $(this).removeClass('checkbox_selected');
                $(this).addClass('checkbox_not_selected');
                $('[name=hidden_' + checkbox_id + ']').val(assign_value);
            }
            var catalog_id = $('#catalog_id').attr('value');
            $.ajax({
                type: "POST",
                url: '/catalog/session/' + catalog_id +'/'+ checkbox_id + '/' + assign_value,
                success: function(msg){
                    var result = Drupal.parseJson(msg);
                    $('#selected_items_imgs').html('<p>' + youcan + '</p>');
                    for (var i in result) {
                        $('#selected_items_imgs').append(result[i]);
                        mouseover_func();
                        // alert(result[i]);
                    //alert(i);
                    }
                    Siebel_execute_unload_effect();
                //alert(result);
                }
            })
        
    });
}

function small_image_hover(){
    $('.item_small_img')
}

function prodcuts_goto(path){
    
    location.href='../'+path;
    return false;
}
/**
 * Ajax function to change products comparison statemtns
 * @param {Object} context
 */
Drupal.behaviors.ajx = function(context){
	if ($('.vertical-tabs-group_comparison_statements').length != 0) {
        $('#edit-taxonomy-1').change(function(){
            $('.vertical-tabs-group_comparison_statements').children().show();
            $('.vertical-tabs-group_comparison_statements :nth-child(2)').children().show();
            var terms = [];
            terms = $.map($('#edit-taxonomy-1 :selected'), function(e){
                return e.value;
            });
           $.ajax({
                type: "GET",
                url: '/products/ajax/' + terms,
                success: function(msg){
                    var result = Drupal.parseJson(msg);
                    var statements = result.data;
                    for(var i in statements){
                        var str = statements[i];
                        str = str.replace(/_/g,'-');
                        $('div[id*=%s]'.replace('%s',str)).hide();
                   } 
                }
            });
            
        });
    }
}

Drupal.behaviors.addToggle = function (context) {
$('div#catalog_content > div').click(function(){
            $(this).next().toggle('slow');
        }
    );
};

function delete_compare_item(){
    //alert("here");
    $('.delete_product').click(function(){
        var compare_id = $('body').attr('id').split('-')[3];
       // alert(compare_id);
        var nid = $(this).attr('id').split('_')[1];
        $.ajax({
			type: "POST",
			url: '/products/remove_item_from_comapre/' + nid + '/' +compare_id,
			success: function(msg){
               // alert(msg);
                var counter = $('span#count_products').text();
                counter--;
                if (counter){
                    $('span#count_products').text(counter);
                }
                else{
                    var text_count = Drupal.t('לא בחרת מוצרים להשוואה');
                    $('div.compare_count').text(text_count);
                }
           		$('#products_compare_table').html(msg);
                
                delete_compare_item();
                mouseover_func();
                compare();
                location.reload();
            }
        });
        //alert(id);
    });
    
}

function catalog_compare_check(){
    
    $('div.checkbox > a, #compare_box ').click(function(){
        var sizes = $('div#selected_items_imgs > p').siblings().size();
        if (!sizes) {
            // append div with id fade into the bottom of body tag
            // and we allready styled it in our step 2 : CSS
            $('body').append('<div id="fade"></div>');
            $('#fade').css({'filter' : 'alpha(opacity=80)'}).show();
            $('body').append('<div style="width: 100xp; height: 100px; color: blue; margin-top: 100px;"></div>');
            
            //centering
            var windowWidth = document.documentElement.clientWidth;      
            var windowHeight = document.documentElement.clientHeight;  
            var popupHeight = $(".checkbox_box").height();  
            var popupWidth = $(".checkbox_box").width();  
            var pagePosition = $(window).scrollTop();  
            $(".checkbox_box").css({  
            //"position": "absolute",  
            "top": (windowHeight/2-popupHeight/2) + $(window).scrollTop() -300,  
            "left": windowWidth/2-popupWidth/2-80  
            });  
            
            $('.checkbox_box').show();
            //exit image
            $('.catalog_error_exit_image').click(function(){
                $('.checkbox_box').fadeOut();
                $('#fade'). hide();
            });
            return false;
               
        }
        else{
           
        }
    });
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

/**
 * A generic function that gets an id and number of default open dd 
 * @param {string} id
 * @param {int} num_open
 */

function expand_collapsed(id,num_open){
	$('dl#'+id+' dd').hide();
	var i;
	for (i = 0; i < num_open; i++){
		$('dl#'+id+' dd').eq(i).show();
        $('dl#'+id+' dd').eq(i).prev('dt').children('div.prod_ayntk_img').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
	}
	$('dl#'+id+' dt').click(function(){
        if (!$(this).hasClass('dt_only_headline')) {
            if ($(this).children('div.prod_ayntk_img').children('img').attr("id") == 'prod_img_close') {
                $(this).children('div.prod_ayntk_img').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" id="prod_img_open">');
            }
            else {
                $(this).children('div.prod_ayntk_img').children('img').replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" id="prod_img_close">');
            }
            $(this).next('dd').toggle('slow');
        }
	});
}

function printPage(id){
   var html="<html>";
   html+= '<link href="/sites/all/modules/rc/products/products.css" media="all" rel="stylesheet" type="text/css">' 
           + '<link href="/sites/all/modules/rc/products/catalog.css" media="all" rel="stylesheet" type="text/css">'
           +'<link href="/sites/all/themes/tami4/css/register.css" media="all" rel="stylesheet" type="text/css">'
           +'<link href="/sites/all/modules/rc/shopping_cart/shopping_cart.css" media="all" rel="stylesheet" type="text/css">'
           +'<link href="/sites/all/themes/tami4/css/tami4-rtl.css" media="all" rel="stylesheet" type="text/css">';
   html+= document.getElementById(id).innerHTML;
   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=1,status=0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
};
jQuery.fn.Exists = function () {
	    return ($(this).length > 0);
	};
jQuery.isHomePage = function (){
		return $("body").hasClass("front");
};
var register = function(){
	return {
		form_submit_try_again:form_submit_try_again,
		select_contact_submit :select_contact_submit,
		page_back : page_back,
		product_number_location_click :product_number_location_click,
		send_activation : send_activation
	};
	function send_activation ()
	{
		$("#register-activation-link").submit();
	}
	
	function form_submit_try_again (el){
		//$(el).closest("form").submit();
		$("#try_again").submit();
	}
	function select_contact_submit  (contact_row_id,form_id)
	{
		if(contact_row_id.length > 0){
			$("#" + form_id).append("<input type='hidden' value='" + contact_row_id + "' name='contact' id='contact_selected' />");
		}
		Siebel_execute_load_effect();
		$("form#" + form_id).submit();
	}
	function page_back(step,form_id)
	{
		switch(step)
		{
			case "register-select_contact":
				$('body').append("<form id='register-select_contact' action='/myarea/registration' method='post'><input type='hidden' value='back' name='back' id='back' /></form>");
				$("#edit-user-register").clone().appendTo("#register-select_contact");
				$("input[name='form_build_id']").clone().appendTo("#register-select_contact");
				$("form#register-select_contact").submit();
				break;
			case "register-login":	
				location.href = "/myarea/registration";
				break;
		}
	}
	function product_number_location_click(select_id,image_wrapper,images)
	{
		$select  = $(select_id);
		var val = $select.val();
		for(i = 0;i< images.length;i++)
		{
			if(images[i].nid == val)
			{
				var src = images[i].source;
				$(image_wrapper).fadeOut(750,function (){
					$(this).find("img").remove();
					$("<img src='/" + src + "' />").appendTo(image_wrapper);
					$(image_wrapper).fadeIn(750);
					return;
				});
			}
		}
		
	}
	 
		
}();

var update_details = function (){
	return {
		delete_zipcode : delete_zipcode
	};
	function delete_zipcode (city,street,zipcode,num,appertment,entrence,floor)
	{
		$('#' + city + ",#" + street).focus(function (){
			$(this).data("value",$(this).val());
		}).blur(function (){
			if ($(this).data("value") != $(this).val()){ 
				$("#" + zipcode).val("");
				$("#" + num).val("");
				$("#" + appertment).val("");
				$("#" + entrence).val("");
				$("#" + floor).val("");
			}
		});
		
	}
}();

var login = function (){
	return {
		//transmit_up_lead_on_homepage : transmit_up_lead_on_homepage,
		//transmit_down_lead_on_homepage : transmit_down_lead_on_homepage,
		transmit_lead_on_homepage : transmit_lead_on_homepage
	};
	function transmit_lead_on_homepage (){
		if ($.isHomePage() && $("#block-lead-0").Exists()){
			if ($(".login-content-display").hasClass("content-visible")){
				transmit_up_lead_on_homepage ();
			}else{
				transmit_down_lead_on_homepage ();
			}
		}
	}
	function transmit_up_lead_on_homepage (){
		
			$("#block-lead-0").animate({marginTop:'-135'},700,function (){});
		
	}
	function transmit_down_lead_on_homepage (){
		
			$("#block-lead-0").animate({marginTop:'-36'},700,function (){});	
		
	}
}();
(function($) {
	
	$.fn.tami_select = function (options){
		var defaults =  {
			"width" : "100",
			"w_class" : "",
			"tabIndex" : 3,
			"selected" : 0,
			"factor" : 13,
			"payments" :false,
			'callback': undefined
		};
		var options = $.extend(defaults, options); 
	    return this.each(function() {
	    	var $this = $(this);
	    	
	    	$this.addClass(options.w_class);
	    	$this.addClass('tami-select-wrapper');
	    	var $select = $this.find("select");
	    	$select.selectbox({"payments" : options.payments , "callback" : options.callback });
	    	 //@todo add width to the select box options.width - 15;
	    	 $result = $this.find(".jquery-selectbox");
	    	 $result.css("width",(options.width * 1) - options.factor);
	    	 $result.attr("tabIndex",options.tabindex);
	    	// var position = $result.position();
	    	// $result.find(".jquery-selectbox-list").css({"width":(options.width * 1) - factor,"top" : (position.top * 1) + 25,"left" : position.left - 5 });
	    	 $result.find(".jquery-selectbox-list").css({"width":(options.width * 1) - options.factor,"top" : "auto" ,"left" :"auto","margin-top" : 17});
	    	 $result.wrap("<div class='select_fld_wrp'><div class='txtfld_top_left'>"+
                  			"<div class='txtfld_top_right'>"+
                  				"<div class='txtfld_bottom_left'>"+
                  					"<div class='txtfld_bottom_right' style='height:24px;padding-right:4px;'>");
	    	 $this.css("width",options.width *1); 
	    	 $select.val(options.selected);
	    	 $result.find(".jquery-selectbox-currentItem").html(options.selected);
	    	//return $select.html();
        });
	};
	$.fn.input_changed =  function (options){
		var defaults = {
			'aggregate_class' : '',
			'input_name' : 'hidden'	
		};
		var options = $.extend(defaults,options);
		return this.each(function (){
			$(this).find("input[type=text]").keyup(function (){
				$form =  $(this).parents("form");
				result = $form.find("input[name=" + options.input_name + "]");
				if (result.length < 1){
					var input  = "<input type='hidden' name='" + options.input_name +  "' id='" + options.input_name + "' value='1' />";
					$form.append(input);
				}
			});
			$(this).find('input[type=checkbox]').click(function (){
				$form =  $(this).parents("form");
				result = $form.find("input[name=" + options.input_name + "]");
				if (result.length < 1){
					var input  = "<input type='hidden' name='" + options.input_name +  "' id='" + options.input_name + "' value='1' />";
					$form.append(input);
				}
				}
			);
			
			
		});
	};
	
	$.fn.lead_bind_open_form = function (){
		$(this).bind('focus',function (){
		$(".lead-frame-expose").toggle_lead();
		});
	};
	$.fn.lead_unbind_open_form = function (){
		$(this).unbind('focus');
	};
	
	$.fn.toggle_lead = function (){
		var status = $(this).attr("status");
		var target = status == 2 ? "lead-open-status" : "lead-form";
		if($(this).hasClass("lead-box-open")){
			//close the lead-box
			$("." + target).slideUp(500);
			$(this).html("&#9660;");
			if(status == 2){
				$("#edit-lead-name").lead_bind_open_form();
			}
		}
		else{
			//open the lead-box
			$("." + target).slideDown(500);
			$(this).html("&#9650;");
			if (status == 2){
				$("#edit-lead-name").lead_unbind_open_form();
			}
		}
		$(this).toggleClass("lead-box-open");
	};
	$.fn.close_lead_icon = function(){
		if ($(this).find(".lead-block-close").length == 0){
			$(this).prepend('<div style="width:7px;height:7px;background-color:red;" class="lead-block-close"></div>');
			$this = $(this);
			$(this).find(".lead-block-close").click(function (){
				$this.slideUp(750);
			});
		}
	};
	
})(jQuery);
$(document).ready(function (){
	if ($("html").hasClass('chrome') &&  $.browser.version < 534 && $("html")){ 
		$("html").addClass('chrome533');
	}
	$(".login-content-display").click(function (){
		$this = $(this);
		login.transmit_lead_on_homepage();
		if( $this.hasClass("content-visible")){
			$this.html("&#9660;");
		}else{
			$this.html("&#9650;");
		}
		$(".login-content").slideToggle(700,function (){
			if( $this.hasClass("content-visible")){
//				login.transmit_up_lead_on_homepage();
				$this.removeClass("content-visible");
				$this.addClass("content-not_visible");
				
			}
			else{
	
				$this.removeClass("content-not_visible");	
				$this.addClass("content-visible");
				
			}
			
		});
	});
	
});
/*
 * 	$("<div class='v-wrapper' style=''>"
	    			 		+"<div class='x-top'>"
						+"		<div class='f-left ct-right v-layout'></div>"
						+"		<div class='f-left xt-border h-border' style='width:" + options.width + "'></div>"
						+"		<div class='f-right ct-left v-layout'></div>"	
						+"	</div>"
						+"	<div class='v-center'>"
						+"		<div class='f-left'></div>"
						+"		<div class='f-left'></div>"
						+"		<div class='f-right'></div>"	 		
						+"	</div>"
						+"	<div class='x-bot'>"
						+"		<div class='f-left cb-right v-layout'></div>"
						+"		<div class='f-left xb-border h-border' style='width:" + options.width + "'></div>"
						+"		<div class='f-right cb-left v-layout'></div>"
						+"	</div>"
						+"</div><div class='clear'></div>")
 */
;
$(document).ready(function(){
    
    $('input#edit-user_id').forceNumeric();
    $('input#edit-phone_number').forceNumeric();
    $('input#edit-additional_phone_number').forceNumeric();
    $('input#edit-house_number').forceNumeric();
    $('input#edit-zip').forceNumeric();
    
   // put_auto_tabindex_to_page('form#shopping-cart-form a,form#shopping-cart-form input,form#shopping-cart-form textarea');*/
    
    /***************** ADMIN ORDERS REPORT *****************/
    $('#sc_order_send_delimeters').click(function(){
        window.location = '/admin/reports/shopping_cart_orders?status=1';
        //alert('here');
    });
    $('.sc_orders_line_cell_send_again').click(function(){
        Siebel_execute_load_effect();
        //alert('test');
        //var $this = this;
        var row_id = $(this).children('div').attr('id').split('_')[1];
        $.ajax({
            type: "POST",
            url: '/shopping_cart/send_order_to_siebel_again/' + row_id,
            success: function(msg){
              window.location.reload();
                
            }
        });
    });
    $('.sc_orders_line_cell_delete').click(function(){
        Siebel_execute_load_effect();
        //alert('test');
        //var $this = this;
        var row_id = $(this).children('div').attr('id').split('_')[1];
        $.ajax({
            type: "POST",
            url: '/shopping_cart/delete_order_local_db/' + row_id,
            success: function(msg){
              window.location.reload();
                
            }
        });
    });
    $('.sc_line_coll').click(function(){
        $(this).parents('.sc_orders_line').siblings().toggle('slow');
        if ($(this).hasClass('collapsible_open')){
            $(this).removeClass('collapsible_open');
            $(this).addClass('collapsible_close');
        }
        else {
            $(this).removeClass('collapsible_close');
            $(this).addClass('collapsible_open');
        }
    });
     /*****************END ADMIN ORDERS REPORT *****************/
    
    var step = $('#edit-step').attr('value'); //current step of the form
    if (step == 5){
        $.ajax({
            type: "POST",
            url: '/shopping_cart/unset_payments',
            success: function(msg){
               // $('#sc_photo').append(msg);
              //  alert(msg);
                
            }
    });
    }
    /**
     * Payments details more info
     */
    $('.err_code_msg_span').click(function(){
			$('.sc_error_more_info_msg').toggle('slow');
		});
    
    /**
     * Form Checkbox
     * @param {Object} msg
     */
    $('.sc_checkbox_pic').click(function(){
        if($(this).hasClass('sc_uncheck')){
            $(this).removeClass('sc_uncheck');
            $(this).addClass('sc_check');
            $(this).siblings('#edit-mail-advertisment').attr('value', 1);
        }
        else {
            $(this).removeClass('sc_check');
            $(this).addClass('sc_uncheck');
            $(this).siblings('#edit-mail-advertisment').attr('value', 0);
        }
    });
    if (step == 2){
        var checkbox_value = $('#edit-mail-advertisment').attr('value');
        if (checkbox_value == 0){
            if ($('.sc_checkbox_pic').hasClass('sc_check')){
                $('.sc_checkbox_pic').removeClass('sc_check');  
                $('.sc_checkbox_pic').addClass('sc_uncheck');
            }
        }
        else {
             if ($('.sc_checkbox_pic').hasClass('sc_uncheck')){
                $('.sc_checkbox_pic').removeClass('sc_uncheck');  
                $('.sc_checkbox_pic').addClass('sc_check');
            }
        }
    }
    /** FORM NEXT BUTTON**/
    $.ajax({
            type: "POST",
            url: '/shopping_cart/get_sc_blue_amount',
            success: function(msg){
                $('#sc_photo').append(msg);
              //  alert(msg);
                
            }
    });
    $('#sum_button').click(function(){
        //var id = $(this).attr('id').split("_");
        //alert('hello2');
        $.ajax({
			type: "POST",
			url: '/shopping_cart/part2',
			success: function(msg){
                var result = Drupal.parseJson(msg);
               $('#sc_content').html(result.content);
  		    }
		});
    });
    if ($('#page-products-cart').length != 0) {
        $.ajax({
            type: "POST",
            url: '/shopping_cart/set_additional_address',
            success: function(msg){
               // alert(msg);
                if (msg == 0) {
                    $('.sc_user_billing_address_title').siblings().hide();
                }
                if (msg == 1){
                    $('.collapsible_open').addClass('collapsible_close');
                    $('.collapsible_close').removeClass('collapsible_open');
                }
            }
        });
    }
    //$('.sc_user_billing_address_title').siblings().hide();
    $('.sc_user_billing_address_title').click(function(){
        if($(this).children('.collapsible_open').length != 0){
            $('.collapsible_open').addClass('collapsible_close');
            $('.collapsible_close').removeClass('collapsible_open');
            $.ajax({
            type: "POST",
            url: '/shopping_cart/set_additional_address/1',
            success: function(msg){
              //  alert(msg);
                
            }
        });
        }
        else {
            $('.collapsible_close').addClass('collapsible_open');
            $('.collapsible_open').removeClass('collapsible_close');
            $.ajax({
                type: "POST",
                url: '/shopping_cart/set_additional_address/0',
                success: function(msg){
                    //alert(msg);
                    
                }
            });
        }
        $('.sc_user_billing_address_title').siblings().toggle('slow');
    });
    
    $('#edit-phone-prefix-wrapper').focus(function(){
        $('.error_phone_prefix').hide();
    });
    
    
    $('.shipping_removing_danger').click(function(){
        if ($('.sc_installment_warning_div').length == 0) {
            sc_shipping_warning_execute_load_effect($(this).attr('href'));
        }
        else {
            $('.sc_installment_warning_background').fadeIn('slow');
            $('.sc_installment_warning_div').show();
        }
        //alert($(this).attr('href'));
        return false;
    });
    
/************* MOVE BUTTON ****************/
$(window).keypress(function(e) {
    if(e.keyCode == 13) {
        if ($('#page-products-cart').length != 0) {
            var sc_form = document.getElementById('edit-next');
            sc_form.click();
        }
    }
    if (e.keyCode == 27){
        
         $('#sc_photo').children('.sc_floating_box').fadeOut('slow', 
             function(){
                    is_open_sc_photo = true;
            });
            
    }
});


$('.sc_next').click(function(){
  _gaq.push(['_trackEvent', 'Shopping Cart', 'click', 'Next Step']);
  var sc_form = document.getElementById('edit-next');
	sc_form.click();
    
});    

/******* PAYMENTS CHANGE IN SUM BOX *****/
   
    //alert($("#payments_select").attr("id"));
    //alert(document.getElementById("payments_select").selectedIndex);
    
    
    if ((step == 4) || (step == 5)){
         //alert(step);
        $('.sc_next').hide();
        $('.sumbox_amount_payments').text((document.getElementById("payments_select").selectedIndex+1));
    }
    
    
/*******************************Cart Hover Logo*******************************/
    
    //$('#sc_floating_box').hide();
    // $('.sc_floating_box').show();
    $('#sc_photo').click(function(){
      _gaq.push(['_trackEvent', 'Shopping Cart', 'click', 'Enter Shopping Cart']);
      window.location = '/products/cart';
    });
    var is_open_sc_photo = true;
    $('#sc_photo').mouseover(function(){
        if (is_open_sc_photo ) {
            
            //$(this).children('.sc_floating_box').fadeIn('slow', function(){is_open_sc_photo = false;});
            if ($('.sc_floating_box').length == 0) {
                $.ajax({
                    type: "POST",
                    url: '/shopping_cart/get_sc_header',
                    success: function(msg){
                        if ($('.sc_floating_box').length == 0) {
                            $('#sc_photo').append(msg);
                        }
                        $('.sc_floating_box').fadeIn('slow', function(){
                            is_open_sc_photo = false;
                        });
                        $('.delete_icon').click(function(){
                            $('#sc_photo').children('.sc_floating_box').fadeOut('slow', function(){
                                is_open_sc_photo = true;
                            });
                            $('.sc_floating_box').fadeOut('slow');
                            return false;
                        });
                    }
                });
            }
            else {
                $('.sc_floating_box').fadeIn('slow', function(){
                            is_open_sc_photo = false;
                        });
            }
        }
    });
  /* $('#sc_photo').hover(
        function () {
            $(this).children('.sc_floating_box').fadeIn('slow');
        }, 
        function () {
           $(this).children('.sc_floating_box').fadeOut();
        }
    );*/
    
    $('#sc_sum_box_details').hide();
    /*$('#sc_details_link').click(function(){
        $(this).children('.sc_floating_box').fadeIn('slow');
     
    });*/
    $('#sc_details_link').hover(
        function () {
            $(this).children('.sc_floating_hover_box').fadeIn('slow');
        }, 
        function () {
            $(this).children('.sc_floating_hover_box').fadeOut('slow');
           // $('.sc_detail_floating_box').fadeOut('slow');
        }
    );
  
    
/********************************* Autocomplete fields ***************************************/
    
    if ($('#edit-city').length != 0){
        if ($('#edit-city').attr('value') != 0){
            //alert($('#edit-city').attr('value'));
            var city = $('#edit-city').val();
            var str = city.replace(' ', '_');
            $('#edit-street-autocomplete').attr('value', '/shopping_cart/autocomplete/street/'+encodeURI(str));
            //alert($('#edit-street-autocomplete').attr('value'));
            $("#edit-street").unbind('keydown');
            $("#edit-street").unbind('keyup');
            $("#edit-street").unbind('blur');
            $('#edit-street-autocomplete').removeClass('autocomplete-processed');
            Drupal.behaviors.autocomplete(document);
        }
    }
    $('#edit-city').blur(function(){
        //alert('bla');
       // alert($('#edit-street-autocomplete').attr('value');
        var city = $('#edit-city').val();
        var str = city.replace(' ', '_');
        $('#edit-street-autocomplete').attr('value', '/shopping_cart/autocomplete/street/'+encodeURI(str));
        //alert($('#edit-street-autocomplete').attr('value'));
        $("#edit-street").unbind('keydown');
        $("#edit-street").unbind('keyup');
        $("#edit-street").unbind('blur');
        $('#edit-street-autocomplete').removeClass('autocomplete-processed');
        Drupal.behaviors.autocomplete(document);
        //alert(str);
      /*  $.ajax({
			type: "POST",
			url: '/shopping_cart/street/'+str,
			success: function(msg){
                var result = Drupal.parseJson(msg);
                var form = result.form;
                var splitArray = form.split('<div>');
                var split2 = splitArray[1].split('<input type="hidden" name="form_build_id"');
               // alert(split2[0]);
                //$('#edit-street-wrapper').html('');
               // $('#edit-street-wrapper').html(split2[0]);
               //$('#edit-street-wrapper').replaceWith(split2[0]);
               Drupal.behaviors.autocomplete(document);
  		    }
		});*/
        
    });
    
    //alert($('#edit-bill_city').attr('value'));
    if ($('#edit-bill_city').length != 0) {
        if ($('#edit-bill_city').attr('value') != 0) {
        
            var city = $('#edit-bill_city').val();
            var str = city.replace(' ', '_');
            $('#edit-bill_street-autocomplete').attr('value', '/shopping_cart/autocomplete/street/' + encodeURI(str));
            //alert($('#edit-street-autocomplete').attr('value'));
            $("#edit-bill_street").unbind('keydown');
            $("#edit-bill_street").unbind('keyup');
            $("#edit-bill_street").unbind('blur');
            $('#edit-bill_street-autocomplete').removeClass('autocomplete-processed');
            Drupal.behaviors.autocomplete(document);
        }
    }
    
    $('#edit-bill_city').blur(function(){
        
        var city = $('#edit-bill_city').val();
        var str = city.replace(' ', '_');
        $('#edit-bill_street-autocomplete').attr('value', '/shopping_cart/autocomplete/street/'+encodeURI(str));
        //alert($('#edit-street-autocomplete').attr('value'));
        $("#edit-bill_street").unbind('keydown');
        $("#edit-bill_street").unbind('keyup');
        $("#edit-bill_street").unbind('blur');
        $('#edit-bill_street-autocomplete').removeClass('autocomplete-processed');
        Drupal.behaviors.autocomplete(document);
       // alert('bla');
      
        
    });
    
    
    /***************************** Change Product Picture by Color *******************/
    $('.color_picker_line').click(function(){
          var line_id = $(this).attr('id');
          var selected = line_id.split('/')[0]; //get serial id of product
          var product_parent = $(this).parents('.sc_full_product'); //get full product main div
          if (product_parent.hasClass('sc_empty_prod')) { //if we are at "empty cart" page
              var product_picture = $(this).parents('.sc_full_product_info_wrapper').siblings('.sc_full_product_picture');
              var lnk = $(this).parents('.sc_full_product_info_wrapper').siblings('.sc_full_link').children('a');//.attr('href', 'this');
          }
          else{ //we are in "product in cart page"
              var product_picture = $(this).parents('.sc_full_product_info_wrapper').siblings('.sc_full_product_picture');
              var lnk = $(this).parents('.sc_color_select_box').siblings('.sc_add_link').children('a');//product_picture.children('a');//.attr('href', 'this');
          }
          var values = '../shopping_cart/change_color/' + line_id;
          var this_img_src = $(this).children('img');
          var img_to_be_changed = $(this).parent().siblings('.color_picker_main').find('.color_picker_selected_color').children('img');
          var line_parent = $(this).parent();
          $.ajax({
              type: "POST",
              url: values,
              success: function(msg){
                  var nid = lnk.attr('href').split('/')[3]; //get nid
                  var reflnk = '/shopping_cart/insert/' + nid + '/' + selected;
                  product_picture.html(msg);
                  lnk.attr('href', reflnk);
                  img_to_be_changed.attr('src', this_img_src.attr('src'));
                  line_parent.toggle();
              }
          });
      });
 
    
    /*********************************Progress Bar*******************************/
    
    $('#edit-next3').click(function() {
 
 
        // Here we will describe a variable popupid which gets the
        // rel attribute from the clicked link							
        var popupid = $(this).attr('rel');
 
 
        // Now we need to popup the marked which belongs to the rel attribute
        // Suppose the rel attribute of click link is popuprel then here in below code
        // #popuprel will fadein
        $('#' + popupid).fadeIn();
 
 
        // append div with id fade into the bottom of body tag
        // and we allready styled it in our step 2 : CSS
        $('body').append('<div id="fade"></div>');
        $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
 
 
        // Now here we need to have our popup box in center of 
        // webpage when its fadein. so we add 10px to height and width 
        var popuptopmargin = ($('#' + popupid).height() + 10) / 2;
        var popupleftmargin = ($('#' + popupid).width() + 10) / 2;
         
 
        // Then using .css function style our popup box for center allignment
        $('#' + popupid).css({
        'margin-top' : -popuptopmargin,
        'margin-left' : -popupleftmargi
        });
           
      /*$.ajax({
			type: "POST",
			url: '/shopping_cart/fade',
			success: function(msg){
                $('#fade').remove();
                $('#' + popupid).fadeOut();
                $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeOut();
  		    }
		});*/
             
    });
});
function sc_shipping_warning_execute_load_effect(src) {
            
	$('body').append('<div class="sc_installment_warning_background" style="display:none;"></div><div class="sc_installment_warning_div"><div class="catalog_error_exit_image"><img src="/sites/all/themes/tami4/images/products/shopping_cart/white_X.PNG">'
                        +'</img></div><div class="sc_warning_title white_color">'+Drupal.t('כדאי לדעת!')+'</div><div class="sc_warning_text white_color"><span>'+Drupal.t('ללא הובלה והתקנה לא נוכל להבטיח אחריות מלאה על המכשיר ועל ההתקנה.')+'<br/>'+Drupal.t('אנא הקליקו לבחירה:') +'</div>'
                        +'<div class="sc_warning_buttons"><div class="sc_warning_buttons_button sc_warning_buttons_continue pointer"><span>'+Drupal.t('ללא הובלה והתקנה')+'</span></div><div class="sc_warning_buttons_button sc_warning_buttons_cancel pointer"><span>'+Drupal.t('אחריות מלאה')+'</span></div></div></div>');
     var windowWidth = document.documentElement.clientWidth;      
    var windowHeight = document.documentElement.clientHeight;  
    var popupHeight = $(".sc_installment_warning_div").height();  
    var popupWidth = $(".sc_installment_warning_div").width();  
    var pagePosition = $(window).scrollTop();  
    $(".sc_installment_warning_div").css({  
        "top": (windowHeight/2-popupHeight/2) + $(window).scrollTop(),  
        "left": windowWidth/2-popupWidth/2  
    });  
    $('.sc_installment_warning_background').fadeIn('slow');
    $('.catalog_error_exit_image').click(function(){
                $('.sc_installment_warning_div').fadeOut();
                $('.sc_installment_warning_background'). hide();
    });
   // var return_value 
    $('.sc_warning_buttons_cancel').click(function(){
        $('.sc_installment_warning_div').fadeOut();
        $('.sc_installment_warning_background'). hide();
    });
     $('.sc_warning_buttons_continue').click(function(){
        window.location = src;
    });
}

function payments_select(a){
     //$('div.sumbox_amount_payments a.jquery-selectbox-item').click(function(){
     //   alert('hi');
        var payments = this.innerHTML; //$("#payments_select").val();
        var total_amount = $('.amount_number').text();
        total_amount = +total_amount.replace(/[^\d\.-]/g,'');
        var new_per_month = (total_amount / payments);
        $.ajax({
			type: "POST",
			url: '/shopping_cart/set_payments/'+payments,
			success: function(msg){
                
  		    }
		});
        $('.payments_per_month').text(new_per_month.toFixed(2));
//            //alert(new_per_month.toFixed(2));*/
}
;
/**
 * 
 * Add Siebel load effect jquery to html 
 * 
 */
function add_Siebel_load_effect_html() {
	if(!$('#SiebelsendingProcess').html())  $('body').append('<div id="SiebelsendingProcess"><img src="/sites/all/themes/tami4/images/ajax-loader.gif"><br>אנא המתן</div>');
}


/**
 * 
 * Execute client side effect load effect when Siebel function is called
 * Execute load effects work for every time this function called
 */
function Siebel_execute_load_effect(is_login) {	
	//if (is_login || $('body').hasClass('logged-in') || $('body').hasClass('section-myarea-registration') || $('body#page-products-cart').html() || $('body').hasClass('page-about-strauss-water-contact') ) { //load Siebel effect only for logged-in users, except register page & shopping cart page	
		if(!$('#SiebelsendingProcess').html())  $('body').append('<div id="SiebelsendingProcess"><img src="/sites/all/themes/tami4/images/ajax-loader.gif"><br>אנא המתן</div>');
		$('#SiebelsendingProcess').css('display','block');		
	//}	
}

/**
 * 
 * Unload client side effect after Siebel function is called 
 * 
 */
function Siebel_execute_unload_effect() {
	$('#SiebelsendingProcess').css('display','none');
}

/**
 * 
 * add onclick event for Siebel links 
 * 
 */
function add_siebel_effect_for_element (element) {	
	$(element).click(function () { 
		Siebel_execute_load_effect();
	});	
}

/**
 * 
 * get all Siebel urls. Should be added manually. 
 * 
 */
function get_siebel_urls() {
	var url_array=new Array();
	
	url_array.push( '/myarea/personal-information' );
	url_array.push( '/myarea/message-box' );
	url_array.push( '/myarea/personal-information-confirmation' );
	url_array.push( '/myarea/payment' );
	url_array.push( '/myarea/payment-confirmation' );
	url_array.push( '/myarea/payment/change_cc');
	url_array.push( '/myarea/payment/standing_order');	
	url_array.push( '/myarea/invoices-history' );	
	url_array.push( '/myarea/invoice' );	
	url_array.push( '/myarea/service-agreement' );
	url_array.push( '/myarea/log-shipping' );
	url_array.push( '/myarea/device-operations' );
	url_array.push( '/users/details' );
	if( $('body').hasClass('logged-in') ) url_array.push( '/myarea' ); //Path appears for loading effect. Doesn't appear for redirection
	if( $('body').hasClass('logged-in') ) url_array.push( '/service/help' ); //Path appears for loading effect. Doesn't appear for redirection
	
	return url_array;
}

/**
 * 
 * Add Siebel loading effect for all href of current page according to Siebel URLs list 
 * 
 */
function add_Siebel_loading_effect_for_all_href()
{	
	var siebel_urls_array = get_siebel_urls();
	
	$('a').each(function () {		
		for(var s in siebel_urls_array) {
			if($(this).attr('href') != undefined) {
				//if( ($(this).attr('href').search(siebel_urls_array[s]) === 0) || ($(this).attr('href').search( (siebel_urls_array[s]+'/') ) === 0)  ) add_siebel_effect_for_element( $(this) );
				//if( ($(this).attr('href').search(siebel_urls_array[s]) === 0) ) add_siebel_effect_for_element( $(this) );
				if( ($(this).attr('href') == siebel_urls_array[s]) || ($(this).attr('href') == siebel_urls_array[s+'/']) ) { 
					add_siebel_effect_for_element( $(this) );
					if( $(this).parent('li').parents('.primary-menu.level_1').html() ) add_siebel_effect_for_element( $(this).parent('li') ); //relevant to primary menu level-1 links only
				}
			}
		}
		
		/*if ( jQuery.inArray( $(this).attr('href'),get_siebel_urls() ) != -1 )		
			add_siebel_effect_for_element( $(this) );*/
	});
}

/**
 * 
 * Load important Siebel integrations to cache 
 * 
 */
function ajax_load_siebel_to_cache() {
	
	var path;
	path = location.href;
	var path_length = path.length;
	var s = '/myarea'
	var s_length = s.length;
	var pos = path.search(s);
	
	if (s_length + pos == path_length) { //execute ajax only at "myarea" path
		
	  $.get('/myarea/ajax/ajax_load_siebel_to_cache', function(result){
		  //alert('ok');
	  });
	}
}

$(document).ready(function() {

	add_Siebel_load_effect_html();	
	
	//if ( $('body').hasClass('logged-in') || $('body').hasClass('section-myarea-registration') || $('body#page-products-cart').html() || $('body').hasClass('page-about-strauss-water-contact') ) { //load Siebel effect only for logged-in users, except register page & shopping cart page
	{
		$('.onclick_loading_effect').each(function () {
			add_siebel_effect_for_element( $(this) );
		});
	
		add_Siebel_loading_effect_for_all_href();	
	}
	
	ajax_load_siebel_to_cache();	
});;
/**
* @author: tom.bran[]gmail-com
* @version: 0.9.8
* edited: August '10
* plugin name: CarouSlide
*/
(function($){$.fn.CarouSlide=function(userConfig){$.fn.CarouSlide.config={slideTime:5000,animTime:1000,autoAnim:false,animInfinity:false,alwaysNext:false,animType:"fade",showSlideNav:true,showBackNext:false,showPauseButton:false,sliderHolder:".slider-holder",navContainer:".slider-nav",hoverLinks:false,easingStyle:null};function methods(){this.props={};var $m=this;this.gotoSlide=function(pos,direct,dir){pos=parseInt(pos);if(pos!=$m.props.currentSlide){$m.props.animReady=false;$m.props.prevSlide=$m.props.currentSlide;$m.props.direction=dir;$m.props.direct=direct;$m.props.animQueue=null;$m.props.oldPos=$m.props.currentSlide;$m.props.newPos=null;if($m.props.direct){if($m.props.autoAnim&&$m.props.animState=="play"){$m.resetTimer();}
$m.props.currentSlide=pos;}
else{$m.props.currentSlide+=dir;if($m.props.currentSlide>=$m.props.sCount){$m.props.currentSlide=pos=0;}
if($m.props.currentSlide<0){$m.props.currentSlide=pos=$m.props.sCount-1;}}
if($m.props.showSlideNav){$m.setNavActive($m.props.currentSlide);}
switch($m.props.animType){case"none":newPos=$m.slideAnimSetup($m.props.sWidth,"right",pos);$m.props.sUL.css({"right":newPos+"px"});$m.props.direct=null;$m.props.animReady=true;break;case"slide":newPos=$m.slideAnimSetup($m.props.sWidth,"right",pos);$m.props.sUL.animate({"right":newPos+"px"},$m.props.animTime,$m.props.easingStyle,$m.transAnimCallback);break;case"slide-vertical":newPos=$m.slideAnimSetup($m.props.sHeight,"top",pos);$m.props.sUL.animate({"top":newPos+"px"},$m.props.animTime,$m.props.easingStyle,$m.transAnimCallback);break;case"fade":var $current=$m.props.sUL.find("> li:eq("+$m.props.currentSlide+")");var $prev=$m.props.sUL.find("> li:eq("+$m.props.prevSlide+")");$current.css("z-index","100").animate({"opacity":"1"},$m.props.animTime,$m.transAnimCallback);$prev.css("z-index","10");if($m.props.prevSlide!==null){setTimeout(function(){$prev.css("opacity","0");},$m.props.animTime);}
break;default:}}};this.slideAnimSetup=function(dim,dir,pos){var output;var minus=dir=="top"?0:1;if($m.props.animInfinity){if($m.props.direct){$m.resetAllSlidePositions();$m.props.sUL.css(dir,-(dim*$m.props.oldPos)+"px");output=-(dim*$m.props.currentSlide);}else{output=-dim+(dim*-$m.props.direction);}}else if($m.props.alwaysNext){$(".s-id-"+$m.props.oldPos,$m.props.sUL).remove().prependTo($m.props.sUL);$(".s-id-"+$m.props.currentSlide,$m.props.sUL).remove().insertAfter($(".s-id-"+$m.props.oldPos,$m.props.sUL));var listItem=$(".s-id-"+$m.props.oldPos,$m.props.sUL);$m.props.sUL.css(dir,"0px");output=($m.props.sUL.css(dir).split("px")[0]-dim);}
else{output=(dim*-pos);}
return output;};this.transAnimCallback=function(){if($m.props.animInfinity){if($m.props.direct){$m.setSlideOrder($m.props.currentSlide);}
if($m.props.direction==1){var firstSlide=$(".slide:first",$m.props.sUL);firstSlide.remove().appendTo($m.props.sUL);}
else if($m.props.direction==-1){var lastSlide=$(".slide:last",$m.props.sUL);lastSlide.remove().prependTo($m.props.sUL);}
if($m.props.animType=="slide"){$m.props.sUL.css("right",-$m.props.sWidth+"px");}
if($m.props.animType=="slide-vertical"){$m.props.sUL.css("top",-$m.props.sHeight+"px");}}
$m.props.direct=null;$m.props.animReady=true;if($m.props.animQueue!==null){$m.gotoSlide($m.props.animQueue,true,null);}};this.setNavActive=function(id){$("li",$m.props.navContainer).removeClass("active");$("> li:eq("+id+")",$m.props.navContainer).addClass("active");};this.timerFunc=function(){$m.gotoSlide($m.props.currentSlide+1,false,1);};this.resetTimer=function(startNow){clearInterval($m.props.timer);$m.props.timer=setInterval($m.timerFunc,$m.props.slideTime+$m.props.animTime);if(startNow){$m.timerFunc();}};this.resetAllSlidePositions=function(){for(var i=0;i<$m.props.sCount;i++){$(".s-id-"+i,$m.props.sUL).remove().appendTo($m.props.sUL);}};this.setSlideOrder=function(focusOn){var firstSlide=(focusOn-1<0?$m.props.sCount-1:focusOn-1);for(var i=0;i<$m.props.sCount;i++){var thisSlide=firstSlide+i;if(thisSlide>=$m.props.sCount){thisSlide-=$m.props.sCount;}
$(".s-id-"+thisSlide,$m.props.sUL).remove().appendTo($m.props.sUL);}};this.buildBackNextLinks=function(){var backNextNav='<ul class="slideshow-back-next">';backNextNav+='<li class="back-button"><a href="javascript:;">Back</a></li>';backNextNav+='<li class="next-button"><a href="javascript:;">Next</a></li>';backNextNav+='</ul>';$($m.props.sContainer).append(backNextNav);};this.buildPauseButton=function(){var pauseButton='<p class="pause-button playing"><a href="javascript:;">Pause</a></p>';$($m.props.sContainer).append(pauseButton);};this.buildNav=function(){var $nav=$m.props.sUL.after('<ul class="'+$m.props.navContainerTitle+'" />');var $slides=$m.props.sUL.find("> li");var slideNavContent="";for(var i=0;i<$m.props.sCount;i++){var ref=$slides.attr("id");slideNavContent+='<li><a href="#'+ref+'">Slide '+(i+1)+'</a></li>';}
$("."+$m.props.navContainerTitle,$m.props.sContainer).append(slideNavContent);}
this.init=function(root){$m.props.sContainer=root;$($m.props.sliderHolder,$m.props.sContainer).wrap("<div class='slider-wrapper' />");$m.props.sWrapper=($(".slider-wrapper",root));$("> ul",$m.props.sWrapper).addClass("s-active "+$m.props.animType);$m.props.timer=null;$m.props.prevSlide=null;$m.props.currentSlide=0;$m.props.backNextContainer=".slideshow-back-next";$m.props.pauseContainer=".pause-button";$m.props.sRef=$($(".CarouSlide")).index($m.props.sContainer);$m.props.animReady=true;$m.props.animState=!$m.props.autoAnim?"pause":"play";$m.props.sUL=$(".s-active",$m.props.sWrapper);$m.props.sUL.find("> li",$m.props.sWrapper).each(function(id){$(this).addClass("slide").addClass("s-id-"+id);});$m.props.sCount=$(".s-active > li",$m.props.sWrapper).size();$m.props.sWidth=$(".s-active > li",$m.props.sWrapper).outerWidth();$m.props.sHeight=$(".s-active > li",$m.props.sWrapper).outerHeight();$m.props.navContainerTitle=$m.props.navContainer.split(".")[1];if($m.props.hoverLinks==true){$m.props.animType="none"}
if($m.props.showSlideNav&&!$m.props.sContainer.find($m.props.navContainer).size()){$m.buildNav();}
$m.props.navContainer=$m.props.sContainer.find($m.props.navContainer);if($m.props.animType=="none"){$m.props.animInfinity=false;$m.props.alwaysNext=false;}else{$m.props.hoverLinks=false;}
if($m.props.alwaysNext&&$m.props.animType=="fade"){$m.props.animType="slide";}
if($m.props.animType=="fade"&&($m.props.animInfinity||$m.props.alwaysNext)){$m.props.animInfinity=false;$m.props.alwaysNext=false;}
if($m.props.alwaysNext&&$m.props.animInfinity){alert("DEVELOPER NOTICE:\n\nProperties 'alwaysNext' and 'aninInfinity' cannot both be active.\n'animInfinity' has been disabled.");$m.props.animInfinity=false;}
if($m.props.animInfinity){$(".slide:last",$m.props.sUL).remove().prependTo($m.props.sUL);}
if($m.props.showSlideNav){$("> li:first",$m.props.navContainer).addClass("active");}else{$($m.props.navContainer).hide();}
if($m.props.autoAnim&&$m.props.showPauseButton){$m.buildPauseButton();}
if($m.props.showBackNext){$m.buildBackNextLinks();}
switch($m.props.animType){case"fade":$("> li",$m.props.sUL).css({"opacity":"0","position":"absolute","right":0,"top":0,"z-index":10});$("> li:first",$m.props.sUL).css({"z-index":"100","opacity":"1"});break;case"none":$(".s-active",$m.props.sWrapper).width(($m.props.sWidth*$m.props.sCount)+"px");break;case"slide":if($m.props.animInfinity){$($m.props.sUL).css("right",-$m.props.sWidth+"px");}
$(".s-active",$m.props.sWrapper).width(($m.props.sWidth*$m.props.sCount)+"px");break;case"slide-vertical":if($m.props.animInfinity){$($m.props.sUL).css("top",-$m.props.sHeight+"px");}
$("> ul",$m.props.sWrapper).height(($m.props.sHeight*$m.props.sCount)+"px");break;default:}
if($m.props.autoAnim){$m.resetTimer();}};}
return this.each(function(id,root){var $m=new methods();$m.props=$.extend({},$.fn.CarouSlide.config,userConfig);$m.init($(this));function slideLinkAction(){var pos=$(this).attr("rel");if($m.props.animReady){$m.gotoSlide(pos,true,null);}else{$m.props.animQueue=pos;}}
if($m.props.showSlideNav){$("> li a",$m.props.navContainer).each(function(pos){var $events=$m.props.hoverLinks?"mouseover click":"click";$(this).attr({"href":"javascript:;","rel":pos}).bind($events,slideLinkAction);});}
var $allSlides=$("li.slide",$m.props.sContainer);for(var i=0;i<$allSlides.length;i++){var s=$(".s-id-"+i,$m.props.sContainer);var ref=s.attr("id");$("a[href=#"+ref+"]").attr({"href":"javascript:;","rel":i}).bind("click",slideLinkAction);};if($m.props.showBackNext){$(".next-button",$m.props.sContainer).click(function(){var nextPos=$m.props.currentSlide+1>=$m.props.sCount?0:$m.props.currentSlide+1;if($m.props.animReady){if($m.props.animState=="play"){$m.resetTimer();}
$m.gotoSlide(nextPos,false,1);}});$(".back-button",$m.props.sContainer).click(function(){var prevPos=$m.props.currentSlide-1<0?$m.props.sCount-1:$m.props.currentSlide-1;if($m.props.animReady){if($m.props.animState=="play"){$m.resetTimer();}
$m.gotoSlide(prevPos,false,-1);}});}
if($m.props.autoAnim&&$m.props.showPauseButton){$($m.props.pauseContainer,$m.props.sContainer).click(function(){if($m.props.animState=="pause"){$m.props.animState="play";$m.resetTimer(true);$(this).addClass("playing").find("a").text("pause");}
else if($m.props.animState=="play"){$m.props.animState="pause";clearInterval($m.props.timer);$(this).removeClass("playing").find("a").text("play");}});}});};})(jQuery);;
/**
 * ezMark - A Simple Checkbox and Radio button Styling plugin. 
 * This plugin allows you to use a custom Image for Checkbox or Radio button. Its very simple, small and easy to use.
 * 
 * Copyright (c) Abdullah Rubiyath <http://www.itsalif.info/>.
 * Released under MIT License
 * 
 * Files with this plugin:
 * - jquery.ezmark.js
 * - ezmark.css
 * 
 * <usage>
 * At first, include both the css and js file at the top
 * 
 * Then, simply use: 
 * 	$('selector').ezMark([options]);
 *  
 * [options] accepts following JSON properties:
 *  checkboxCls - custom Checkbox Class
 *  checkedCls  - checkbox Checked State's Class
 *  radioCls    - custom radiobutton Class
 *  selectedCls - radiobutton's Selected State's Class
 *  
 * </usage>
 * 
 * View Documention/Demo here:
 * http://www.itsalif.info/content/ezmark-jquery-checkbox-radiobutton-plugin
 * 
 * @author Abdullah Rubiyath
 * @version 1.0
 * @date June 27, 2010
 */

(function($) {
  $.fn.ezMark = function(options) {
	options = options || {};
	var defaultOpt = { 
		checkboxCls   	: options.checkboxCls || 'ez-checkbox' , radioCls : options.radioCls || 'ez-radio' ,	
		checkedCls 		: options.checkedCls  || 'ez-checked'  , selectedCls : options.selectedCls || 'ez-selected' , 
		hideCls  	 	: 'ez-hide'
	};
	
    return this.each(function() {
    	var $this = $(this);
    	var wrapTag = $this.attr('type') == 'checkbox' ? '<div class="'+defaultOpt.checkboxCls+'">' : '<div class="'+defaultOpt.radioCls+'">';
    	// for checkbox
    	if( $this.attr('type') == 'checkbox') {    		
    		$this.addClass(defaultOpt.hideCls).wrap(wrapTag).click(function() { //event modified from "change" to "click"    			

    			/* my addition to switch checkbox hidden value */
    			if( $(this).val() == 1) {
    				$(this).attr('checked',false);
    				$(this).val(0);
    			}
    			else { 
    				$(this).attr('checked',true);
    				$(this).val(1);
    			}
    			/*/my addition to switch checkbox hidden value */
    			
    			if( $(this).is(':checked') ) { 
    				$(this).parent().addClass(defaultOpt.checkedCls); 
    			} 
    			else {	$(this).parent().removeClass(defaultOpt.checkedCls); 	}
    		});
    		
    		if( $this.is(':checked') ) {
				$this.parent().addClass(defaultOpt.checkedCls);    		
    		}
    	} 
    	else if( $this.attr('type') == 'radio') {
    		$this.addClass(defaultOpt.hideCls).wrap(wrapTag).click(function() { //event modified from "change" to "click"
    			// radio button may contain groups! - so check for group
   				$('input[name="'+$(this).attr('name')+'"]').each(function() {
   	    			if( $(this).is(':checked') ) {
   	    				$(this).parent().addClass(defaultOpt.selectedCls); 
   	    			} else {
   	    				$(this).parent().removeClass(defaultOpt.selectedCls);     	    			
   	    			}
   				});
    		});
    		
    		if( $this.is(':checked') ) {
				$this.parent().addClass(defaultOpt.selectedCls);    		
    		}    		
    	}
    });
  }
})(jQuery);;
/*
 * jQuery validation plug-in pre-1.5.2
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6243 2009-02-19 11:40:49Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {
		
		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}
		
		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}
		
		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator); 
		
		if ( validator.settings.onsubmit ) {
		
			// allow suppresing validation by adding a cancel class to the submit button
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});
		
			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();
					
				function handle() {
					if ( validator.settings.submitHandler ) {
						validator.settings.submitHandler.call( validator, validator.currentForm );
						return false;
					}
					return true;
				}
					
				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}
		
		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = false;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid |= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function(index, value) {
			result[value] = $element.attr(value);
			$element.removeAttr(value);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];
		
		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}
		
		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);
		
		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}
		
		return data;
	}
});

// Custom selectors
$.extend($.expr[":"], {
	// http://docs.jquery.com/Plugins/Validation/blank
	blank: function(a) {return !$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/filled
	filled: function(a) {return !!$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/unchecked
	unchecked: function(a) {return !a.checked;}
});


$.format = function(source, params) {
	if ( arguments.length == 1 ) 
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};

// constructor for validator
$.validator = function( options, form ) {
	this.settings = $.extend( {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: [],
		ignoreTitle: false,
		onfocusin: function(element) {
			this.lastActive = element;
				
			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass );
				this.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			if ( element.name in this.submitted )
				this.element(element);
		},
		highlight: function( element, errorClass ) {
			$( element ).addClass( errorClass );
		},
		unhighlight: function( element, errorClass ) {
			$( element ).removeClass( errorClass );
		}
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},

	messages: {
		required: "שדה זה הוא שדה חובה.",
		remote: "Please fix this field.",
		email: "חובה להזין כתובת אימייל תקינה.",
		url: "Please enter a valid URL.",
		date: "Please enter a valid date.",
		dateISO: "Please enter a valid date (ISO).",
		dateDE: "Bitte geben Sie ein gültiges Datum ein.",
		number: "חובה להזין מספר טלפון תקין.",
		numberDE: "Bitte geben Sie eine Nummer ein.",
		digits: "Please enter only digits",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.format("Please enter no more than {0} characters."),
		minlength: $.format("Please enter at least {0} characters."),
		rangelength: $.format("Please enter a value between {0} and {1} characters long."),
		range: $.format("Please enter a value between {0} and {1}."),
		max: $.format("Please enter a value less than or equal to {0}."),
		min: $.format("Please enter a value greater than or equal to {0}.")
	},
	
	autoCreateRanges: false,
	
	prototype: {
		
		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();
			
			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});
			
			function delegate(event) {
				var validator = $.data(this[0].form, "validator");
				validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] );
			}
			$(this.currentForm)
				.delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate)
				.delegate("click", ":radio, :checkbox", delegate);

			if (this.settings.invalidHandler)
				$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},
		
		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid(); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.clean( element );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide = this.toHide.add( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},
		
		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},
		
		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},
		
		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},
		
		valid: function() {
			return this.size() == 0;
		},
		
		size: function() {
			return this.errorList.length;
		},
		
		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		},
		
		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},
		
		elements: function() {
			var validator = this,
				rulesCache = {};
			
			// select all valid inputs inside the form (no submit or reset buttons)
			// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
			
				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;
				
				rulesCache[this.name] = true;
				return true;
			});
		},
		
		clean: function( selector ) {
			return $( selector )[0];
		},
		
		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},
		
		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.formSubmitted = false;
			this.currentElements = $([]);
		},
		
		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().add( this.containers );
		},
		
		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},
	
		check: function( element ) {
			element = this.clean( element );
			
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}
			
			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
					
					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;
					
					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}
					
					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method");
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},
		
		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;
			
			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();
			
			return meta && meta.messages && meta.messages[method];
		},
		
		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},
		
		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},
		
		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},
		
		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method );
			if ( typeof message == "function" ) 
				message = message.call(this, rule.parameters, element);
			this.errorList.push({
				message: message,
				element: element
			});
			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},
		
		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle = toToggle.add( toToggle.parents( this.settings.wrapper ) );
			return toToggle;
		},
		
		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},
		
		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},
		
		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},
		
		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass().addClass( this.settings.errorClass );
			
				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow = this.toShow.add(label);
		},
		
		errorsFor: function(element) {
			return this.errors().filter("[for='" + this.idOrName(element) + "']");
		},
		
		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},
		
		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},
		
		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},
	
		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},
	
		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},
		
		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},
		
		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},
		
		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make sure pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			}
		},
		
		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", previous = {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}
		
	},
	
	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},
	
	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},
	
	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},
	
	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);
		
		for (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}
		
		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}
		
		return rules;
	},
	
	metadataRules: function(element) {
		if (!$.metadata) return {};
		
		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},
	
	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},
	
	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});
		
		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});
		
		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});
		
		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}
		
		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages
		}
		
		return rules;
	},
	
	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},
	
	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message;
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				var options = $("option:selected", element);
				return options.length > 0 && ( element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			
			var previous = this.previousValue(element);
			
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			param = typeof param == "string" && {url:param} || param; 
			
			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						if ( response ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] =  response || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						}
						previous.valid = response;
						validator.stopRequest(element, response);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
		},
        
		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateDE
		dateDE: function(value, element) {
			return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/numberDE
		numberDE: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/accept
		accept: function(value, element, param) {
			param = typeof param == "string" ? param : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			return value == $(param).val();
		}
		
	}
	
});

})(jQuery);

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() 
;(function($) {
	var ajax = $.ajax;
	var pendingRequests = {};
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
		var port = settings.port;
		if (settings.mode == "abort") {
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return (pendingRequests[port] = ajax.apply(this, arguments));
		}
		return ajax.apply(this, arguments);
	};
})(jQuery);

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target 

// provides triggerEvent(type: String, target: Element) to trigger delegated events
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});
	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);

jQuery.validator.addMethod( 
	  "selectNone", 
	  function(value, element) { 
	    if (element.value == "none") 
	    { 
	      return false; 
	    } 
	    else return true; 
	  }, 
	  "שדה זה הוא שדה חובה." 
	);
		  ;
/**
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof SuszyÅ„ski (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.6.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectbox
 * @author Krzysztof SuszyÅ„ski <k.suszynski@wit.edu.pl>
**/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'jquery-selectbox',
		animationSpeed: "normal",
		listboxMaxSize: 10,
		replaceInvisible: false,
		payments : false,
		callback : undefined,
		tabindex : undefined
	};
	
	
	
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideDown(settings.animationSpeed, function(){
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		jQuery(document).bind('click', onBlurList);
		//$(listObj).mousedown(function(){
		/*$(listObj).find('a:first').focus(
					function (e){
								$(this).parent("div").mousedown();
								e.stopPropagation();
							});*/
		//(function (){$(this).focus()});
		//});
		
		return listObj;
	};
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideUp(settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
		});
		jQuery(document).unbind('click', onBlurList);
		return listObj;
	};
	var onBlurList = function(e) {
		var trgt = e.target;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	};
	/***
	 * Ohad Sadan changed the span to a at class currentItem
	 */
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	
	if(settings.tabindex == undefined || typeof(settings.tabindex) == 'NaN' || typeof(settings.tabindex) !='number') {
		var tabindex = ' ';		
	}
	else {		 
		var tabindex = ' tabindex= '+settings.tabindex;		
	}
	
	/* Wrapping all passed elements */
	return this.each(function() {
		var _this = jQuery(this);
		var href = settings.payments ? "" : "href=\"javascript:void(0)\" rel=\"nofollow\"";
			
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;		
		
		var replacement = jQuery(
			'<div class="' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" />' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<a ' + href + ' class="' + settings.className + '-currentItem"' +tabindex+' />' +
			'</div>'
		);
		jQuery('option', _this).each(function(k,v){
			var v = jQuery(v);
			
			var listElement =  jQuery('<a ' + href + ' class="' + settings.className + '-item value-'+v.val()+' item-'+k+tabindex+'">' + v.text() + '</a>');
			listElement.bind("click keyup",function(e){
				if( (e.type == 'keyup' && e.keyCode == 13) || e.type == 'click' ){
					var thisListElement = jQuery(this);
					var thisReplacment = thisListElement.parents('.'+settings.className);
					var thisIndex = thisListElement[0].className.split(' ');
					for( k1 in thisIndex ) {
						if(/^item-[0-9]+$/.test(thisIndex[k1])) {
							thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
							break;
						}
					};
					var thisValue = thisListElement[0].className.split(' ');
					for( k1 in thisValue ) {
						if(/^value-.+$/.test(thisValue[k1])) {
							thisValue = thisValue[k1].replace('value-','');
							break;
						}
					};
					thisReplacment
						.find('.' + settings.className + '-currentItem')
						.text(thisListElement.text());
					thisReplacment
						.find('select')
						.val(thisValue)
						.triggerHandler('change');
					var thisSublist = thisReplacment.find('.' + settings.className + '-list');
					if(thisSublist.filter(":visible").length > 0) {
						hideList( thisSublist );
					}else{
						showList( thisSublist );
					}
				} 
				if (e.type == 'keyup'){
						if(e.keyCode == 40){
							//alert($(this).html());
							$(this).removeClass('listelementhover');
							$(this).next('a').focus();
						}
						if (e.keyCode == 38 ){
							$(this).removeClass('listelementhover');
							$(this).prev('a').focus();
						}
				}
				if (e.type == 'click' && typeof (settings.callback) != "undefined" ){
					settings.callback.call(this);
				}
			}).bind('mouseenter focus' ,function(){
				jQuery(this).addClass('listelementhover');
			}).bind('mouseleave blur',function(){
				jQuery(this).removeClass('listelementhover');
			});
			jQuery('.' + settings.className + '-list', replacement).append(listElement);
			if(v.filter(':selected').length > 0) {
				jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
			}
		});
		/*
		 * Ohad Sadan added the option to open the select box
		 * also from the span area .
		 * added  a selector to the find treverse 
		 * ' + '.' + settings.className + '-currentItem' 
		 * 
		 */
		replacement.find('.' + settings.className + '-moreButton ,' + '.' + settings.className + '-currentItem' ).bind('click keydown',function(e){
			if( (e.type == 'keydown' && e.keyCode == 40) || e.type == 'click' ){
				var thisMoreButton = jQuery(this);
				var otherLists = jQuery('.' + settings.className + '-list')
					.not(thisMoreButton.siblings('.' + settings.className + '-list'));
				hideList( otherLists );
				var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
				if(thisList.filter(":visible").length > 0) {
					hideList( thisList );
				}else{
					showList( thisList );
					$(thisList).find('a:first').focus();
				}
				
			}
		}).bind('mouseenter focus',function(){
			jQuery(this).addClass('morebuttonhover');
		}).bind('mouseleave blur',function(){
			jQuery(this).removeClass('morebuttonhover');
		});
		
		
		
		
		
		
		
		_this.hide().replaceWith(replacement).appendTo(replacement);
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		if(thisListBoxSize > settings.listboxMaxSize)
			thisListBoxSize = settings.listboxMaxSize;
		if(thisListBoxSize == 0)
			thisListBoxSize = 1;	
		var thisListBoxWidth = Math.round(_this.width() + 5);
		if(jQuery.browser.safari)
			thisListBoxWidth = thisListBoxWidth * 0.94;
		replacement.css('width', thisListBoxWidth + 'px');
		thisListBox.css({
			width: Math.round(thisListBoxWidth-5) + 'px',
			height: thisListBoxSize + 'em'
		});
	});
}
jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
};
/* Error messages handling */


var Tami4 = function(){
		
		return{
			show_validation : show_validation,
			show_sibiling_once : show_sibiling_once,
			switch_tabs : switch_tabs,
			aggregate_fields_validation : aggregate_fields_validation,
			aggregate_fields_required : aggregate_fields_required,
			alert_t : alert_t,
			clear_lead_error : clear_lead_error,
			confirm_t : confirm_t
		};
		function clear_lead_error(myid){
			$('label[for=' + myid  + ']').remove();
			if( $('.lead-error label.error').length < 1 ){
					$(".lead-block-line").hide();
				}	
		};
		function alert_t (message){
			alert(message);
		};
		function confirm_t(message){
			if (confirm(message))
				return true;
			else
				return false;
		}
		function show_validation (element,error){
            //alert(element);
		    $("input[name='" + element +"'] ,textarea[name='" + element +"'], select[name='" + element +"']").each(function() {
	    	   // $(this).addClass('error');
                if (($('#page-products-cart').length == 0) && ($('#page-about-strauss-water-contact').length == 0))  {
                    $(this).after("<span class='error tami4-form-error'>" + error + "</span>");
                    $(this).focus(function() {
		    			$(this).removeClass('error');
		    			$(this).siblings('span.tami4-form-error').html('');
		    		});
                }
                else {
                    //alert(element);
                    //Shopping Cart Error msg
                    var err_msg = "<span class='error tami4-form-error'>" + error + "</span>"; //regular error msg
                    if (element == 'phone_prefix') { //if element is phone prefix we want to take care of it.
                        //we are adding a class to the span of the error and put it in the phone_number error
                        err_msg = "<span class='error tami4-form-error'>" + error + "</span><span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>";
                        $('#edit-phone_number').parent().parent().parent().parent().parent().parent().siblings('.custom_error').append("<span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>");
                        $('#edit-phone-prefix-wrapper').click(function(){
                            $('.error_phone_prefix').hide(); //when the selectbox is touched, hid the error class.
                        });
                    }
                    else if (element == 'request_type') {
                        $('.selectbox_request_type').children('.custom_error').append("<span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('נושא פניה הינו שדה חובה') + "</span>");
                        $('div#edit-request-type-wrapper').click(function(){
                                //$(this).removeClass('error');
                                //alert((this).attr('class'));
                                $('.selectbox_request_type').find('.custom_error').html('');
                            });
                    }
                    else if (element == 'message_body'){
                        $('#edit-message-body-wrapper').siblings('.custom_error').append("<span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('הודעה הינה שדה חובה') + "</span>");
                        $('#edit-message-body').focus(function(){
                                $(this).parents('#edit-message-body-wrapper').siblings('.custom_error').html('');
                            });
                    }
                    else 
                        if (element == 'phone_number') { //if the element is phone number
                            var err_msg = "<span class='error tami4-form-error error_phone_number'>" + error + "</span>";
                            $('#edit-phone_number').parent().parent().parent().parent().parent().parent().siblings('.custom_error').append("<span class='error tami4-form-error error_phone_number'>" + /*Drupal.t('טלפון הינו שדה חובה')*/ error + "</span>");
                            $(this).focus(function(){
                                $('.error_phone_number').hide();
                            });
                        }
                        else { //any other form element error
                            $(this).parent().parent().parent().parent().parent().parent().siblings('.custom_error').html(err_msg);
                            $(this).focus(function(){
                                $(this).removeClass('error');
                                $(this).parent().parent().parent().parent().parent().parent().siblings('.custom_error').html('');
                            });
                        }
                }
		    		
		    });
		}
		function show_sibiling_once(src,dest){
			$(src).one('click',function (){
				$(this).parents('p').siblings(dest).slideDown(500);
			});
		}
		function switch_tabs(wrapper,current,func,func_args)
		{
			var src = $("#" + current).attr("id") + "-tab";
			var canvas_on = $("#" + wrapper).find(".tab-canvas-active");
			
			$("#" + wrapper).find('.tab').each(function (){
				if ($(this).attr("id") != current){
					$(this).removeClass("active");
				}else{	
					$('#'+ current).addClass('active');
				}
			});
			
			canvas_on.fadeOut(250, function(){
				$(this).removeClass('tab-canvas-active');
				//@TODO concat the out args into the func
				var mysrc = $("#" + src);  
				mysrc.html(func(func_args));
				mysrc.addClass('tab-canvas-active');
				mysrc.fadeIn(750);
			});
				//$this = $(this);
			
				/*
				
				$('#'+ src).fadeIn(650, function(){
					$("#" + wrapper).find('.tab-canvas').each(function (){
						if ($(this).attr("id") != src){
							$(this).removeClass("tab-canvas-active");
						}else{	
							$('#'+ current).addClass('tab-canvas-active');
						}
					});
				});*/
				
 
		}
		
		function aggregate_fields_validation (arr,msg,$el)
		{
			if (!aggregate_fields_required(arr)){
					if (!$el.find(".aggr_err").Exists()){
						$el.append("<span class='error aggr_err'>" + msg + "</span>");
					}
					$("input").one('blur',function (){
						$el.find('.aggr_err').remove();
					});
					return false;
				}
			return true;
		}
		
		function aggregate_fields_required (fields)
		{
			var fleg =  false;
			for (var f in fields)
			{	
				if ($("#" + fields[f]).val() != "" && $("#" + fields[f]).val() != undefined){
					fleg = true;
				}	
			}
			if (fleg){
				for (var f in fields)
				{	
					if($("#" + fields[f]).val() == ""){
						fleg = false;
					}
				}
			}else {
				//There is nothing to valid ;
				return true; 
			}
			//validation result;
			return fleg;
		} 
	} ();
/*/Error messages handling */	

/* Force numeric input for keydown event */
//Usage example: $('input.numeric').forceNumeric();
(function ($) {
    $.fn.forceNumeric = function () {
        return this.each(function () {
        	
        	$(this).keydown(function(e) {
                           
                	 var ord_value = e.which;
                	 if((ord_value >= 48 && ord_value <= 57) || (ord_value >= 96 && ord_value <= 105) || ord_value == 8 || ord_value == 46 || ord_value == 9 || (e.keyCode == 'V'.charCodeAt(0) && e.ctrlKey)) 
                		 return true; //numeric and delete,backspace,escape
                	 else
                		 return false;
                
            	                
            });
        });
    };
})(jQuery);

 
/* this func is checking for ctrl + key like "ctrl+S" 
 * 
 *  to use the funciton  simply do the following
 *  
 *  $.ctrl('S', function() {
 *  alert("Saved");
 *	});
 *
 *  */ 

$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        if(e.keyCode == key.charCodeAt(0) && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });
};


function only_hebraw_text(value)
{
	var c;
	var fleg = true;
	var hebrew_char = false;
	for(i = 0; i < value.length ; i++)
	{
		var j = i;
		c = value.charCodeAt(j);
		if (! ((c > 0x590 && c < 0x5FF) || c == 32 || c ==  45 || c == 34 || c == 96 ) ){
			fleg = false;
		}
		else { //check if Hebrew char exists
		  if( c > 0x590 && c < 0x5FF) {
			  hebrew_char = true; //Hebrew char does exist
		  }
		}
	}	
	return (fleg &&  ( value.length == 0 || hebrew_char)  );
}


function check_side_hebrew_validation(element) {
	if ( !(only_hebraw_text($(element).attr('value')))){
        return false;
    }
    else {    	
        return true;
    }
}

/**
 * Initialize designed checkbox value
 * id = element id (string)
 * 
 */
function initialize_designed_checkbox(id) {
	if(id == null) return false;
	
	if( $(id).is(':checked') ) {
	  $(id).val(1);	  
	  $(id).attr('checked',true);
	  $(id).ezMark();
	}
	else {		
	  $(id).val(0);
	  $(id).attr('checked',false);
	  $(id).ezMark();
	}
}

/*
 * Function put automatic counter index to all elements within elements_string
 * e.g: put_auto_tabindex_to_page('form#contact-us-form a,form#contact-us-form input,form#contact-us-form textarea')
 */
function put_auto_tabindex_to_page(elements_string) {
var tabindex = 1;
    $(elements_string).each(function() { //form#contact-us-form select
        if (this.type != "hidden") {
            var $input = $(this);
            $input.attr("tabindex", tabindex);
            tabindex = parseInt(tabindex) + 10;            
        }
    });
}


function chat_service_ajax(){
        var url = window.location.href;
        $.get('/shopping_cart/chat', {
              url: url
          }, function(data){
          
              tami_execute_load_effect(data);
              
          }, 'text');
    }
    $('.chat_list_chat').mouseover(function(){
        alert('hello');
    });
    $('.chat_list_contact').mouseover(function(){
       $(this).children('a').children('div').removeClass('chat_list_contact_img');
       $(this).children('a').children('div').addClass('chat_list_contact_img_hover');
       //delete_product
   });
   $('.chat_list_contact').mouseout(function(){
       $(this).children('a').children('div').removeClass('chat_list_contact_img_hover');
       $(this).children('a').children('div').addClass('chat_list_contact_img');
   });
   
   
   
/**--------------------- faq functions ---------------**/

/*---------- faq page - close/open cube-----------*/	
function collapse_faq(e){

		var path_faq = window.location.pathname;
		var arr_path_faq = path_faq.split('/');
	
		var element = $(e.target);
		element = (element.is('.faq_img_open') || element.is('.faq_img_close'))? element.siblings('.faq_title'): element;
		var faq_img_open = element.siblings('.faq_img_open');
		var faq_img_close = element.siblings('.faq_img_close');
		//var faq_img_open = (element.is('.faq_img_open'))? element : element.siblings('.faq_img_open');
		//var faq_img_close = (element.is('.faq_img_close'))? element :element.siblings('.faq_img_close');

	 	//console.log($(e.target).siblings('.faq_img_close'));
        if (faq_img_open.attr('class')=='faq_img_open') {
            faq_img_open.replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" class="faq_img_close">');
        }
        else {
             faq_img_close.replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" class="faq_img_open">');
        }
       //alert(arr_path_faq[1]);
        //@TODO בעייתי שינינו את הלינק
        switch(arr_path_faq[1]) {
	case 'service':
	    element.parent().parent().parent().nextAll(".views-field-body").eq(0).slideToggle('slow');
		break;
	case 'about-strauss-water':
	    element.parent().parent().parent().nextAll(".views-field-nothing").find('.views-field-body').slideToggle('slow');;
		break;
}


        
element.parent().parent().parent().nextAll(".views-field-nothing").find('.views-field-body');
 
}

/*---------- faq page - close/open all cubes-----------*/	
function collapse_faq_all(e){
	
		var element = $(e.target);
		if(element.attr("class") != 'expand_categories'){
			element = element.parents(".expand_categories");
		}
		var faq_arrow_open = element.find('.open_arrow');
		var faq_arrow_close = element.find('.close_arrow');
		
	 	//console.log(faq_arrow_open);
        if (faq_arrow_open.attr('class')=='open_arrow') {
            faq_arrow_open.replaceWith('<img class="close_arrow" src ="/sites/all/themes/tami4/images/button/blue_arrow_up.png" />');
			 $(".view-display-id-page_1 .views-field-title .faq_img_open").replaceWith('<img src="/sites/all/themes/tami4/images/products/div_close.png" class="faq_img_close">');
			 element.find(".open_all").html('סגור');
			
			$(".view-display-id-page_1 .views-field-body").show('slow');
        }
        else {
			$(".view-display-id-page_1 .views-field-title .faq_img_close").replaceWith('<img src="/sites/all/themes/tami4/images/products/div_open.png" class="faq_img_open">');
			element.find(".open_all").html('להצגה מלאה');
			faq_arrow_close.replaceWith('<img class="open_arrow" src ="/sites/all/themes/tami4/images/button/blue_arrow_down.png" />');
			$(".view-display-id-page_1 .views-field-body").hide('slow');
        }
       
}

/*---------- faq block - category selected  -----------*/	
function faq_select_category(){
	
	var path_faq = window.location.pathname;
	var arr_path_faq = path_faq.split('/');
	//alert(arr_path_faq[1]);
	switch(arr_path_faq[1]){
		case 'service':
				if(!!arr_path_faq[3]){
					
					$('#block-views-FAQ-block_2 .view-content a').parent().addClass('unselected-menu-faq-job');
					//var target = $('#block-views-FAQ-block_2 .view-content a').parent().css('border-bottom','none');
					
					$('#block-views-FAQ-block_2').find('a[href*="'+path_faq+'"]').find('div').attr('class','selected-menu-faq-job');
					
					var target = $('#block-views-FAQ-block_2').find('a[href*="'+path_faq+'"]').find('div').parent().parent().parent().parent();
					var d_border = target.prev('div').find('span').is('span');
					if(d_border){	
						target.prev('div').find('span').find('div').css('border-bottom','none');
					}else{
						$('#block-views-FAQ-block_2 .view-content a').parent().css('border-bottom','none'); 
					}
					
				}else{
					$('#block-views-FAQ-block_2 .view-content a').parent().addClass('selected-menu-faq-job');					
				}
		break;

		case 'about-strauss-water':
			if(!!arr_path_faq[3]){
				
				$('#block-views-jobs-block_2 .view-content a').parent().addClass('unselected-menu-faq-job');
				//var target = $('#block-views-jobs-block_2 .view-content a').parent().css('border-bottom','none');
				
				$('#block-views-jobs-block_2').find('a[href*="'+path_faq+'"]').find('div').attr('class','selected-menu-faq-job');
				
				var target = $('#block-views-jobs-block_2').find('a[href*="'+path_faq+'"]').find('div').parent().parent().parent().parent();
				var d_border = target.prev('div').find('span').is('span');
				if(d_border){	
					target.prev('div').find('span').find('div').css('border-bottom','none');
				}else{
					$('#block-views-jobs-block_2 .view-content a').parent().css('border-bottom','none'); 
				}
				
			}else{
				$('#block-views-jobs-block_2 .view-content a').parent().addClass('selected-menu-faq-job');					
			}
		break;
	
		case 'about-strauss-water_OLD':
				if(!!arr_path_faq[3]){
					$('#block-views-jobs-block_2 .view-content .views-row ul li a[href*="'+path_faq+'"]').parent().addClass('faq_background_selected');
					var target = $('#block-views-jobs-block_2 .view-content .views-row ul li a[href*="'+path_faq+'"]').parent();
					$('<div class="tab_selected_top"></div>').insertBefore(target);
					if(target.parents('.views-row').next('ul').find('li').is('li')){
						$('<div class="tab_selected_bot"></div>').insertAfter(target);
					}else{
						$('<div class="tab_selected_bot_white"></div>').insertAfter(target);
					}
					
					
					
					if(!!target.parents('.views-row').prev('.views-row').find('li').is('li')){
						target.parents('.views-row').prev('.views-row').find('li').css('border-bottom','none');
					}else if(!!target.parents('.views-row').prev('ul').find('li').is('li')){
						target.parents('.views-row').prev('ul').find('li').css('border-bottom','none'); 
					}
				}else{
					$('#block-views-jobs-block_2 .view-content ul li .all_faq_category').parent().addClass('faq_background_selected');
					var target = $('#block-views-jobs-block_2 .view-content ul li .all_faq_category').parent();
					$('<div class="tab_selected_top_white"></div>').insertBefore(target);
					$('<div class="tab_selected_bot"></div>').insertAfter(target);
				}
		break;
		
	}

}	
/** ------------------- END faq functions ---------------**/

/**
 * Function that insert into the body of the page the chat div 
 * @param {Object} txt
 */
function tami_execute_load_effect(txt) {
            
	$('body').append('<div class="chat_background"></div><div class="chat_div"><div class="catalog_error_exit_image"><img src="/sites/all/themes/tami4/images/products/shopping_cart/white_X.PNG" alt="'+Drupal.t('סגור')+'" title="'+Drupal.t('סגור')+'">'
                        +'</img></div><div class="chat_title">'+Drupal.t('בחר את דרך התקשורת המועדפת עלייך:')+'</div>'+txt+'</div>');
    var windowWidth = document.documentElement.clientWidth;      
    var windowHeight = document.documentElement.clientHeight;  
    var popupHeight = $(".chat_div").height();  
    var popupWidth = $(".chat_div").width();  
    var pagePosition = $(window).scrollTop();  
    $(".chat_div").css({  
        "top": (windowHeight/2-popupHeight/2) /*+ $(window).scrollTop()*/,  
        "left": windowWidth/2-popupWidth/2  
    });  
    $('.catalog_error_exit_image').click(function(){
                $('.chat_div').fadeOut();
                $('.chat_background'). hide();
            });
     $('.chat_list_contact').mouseover(function(){
       $(this).children('a').children('div').removeClass('chat_list_contact_img');
       $(this).children('a').children('div').addClass('chat_list_contact_img_hover');
   });
   $('.chat_list_contact').mouseout(function(){
       $(this).children('a').children('div').removeClass('chat_list_contact_img_hover');
       $(this).children('a').children('div').addClass('chat_list_contact_img');
   });

}


/**------------------ job page ------------------**/
/*email*/
function job_email_value(){
	
		$('.section-about-strauss-water-career .job_email_value').val();
		$('.section-about-strauss-water-career .job_email_value').each(function(){
			//$(e).text("<input type='button' VALUE='e-mail' onClick='parent.location=\'mailto:[field_job_email_value]\' />");
			element_value = $.trim ($(this).text());
			$(this).html("<input class='service_box_button' type='button' VALUE='שלח מועמדות' onClick='job_email(\""+element_value+"\")' />");
			//console.log(element_value);
		});
}

function job_email(element_value){
	
	window.location.href = "mailto:"+element_value+"\"";
}
/**------------- END job page ------------------**/

/**-------------- nanorep side dialog -------------**/

function nanorep_side_dialog(){
	
	 //  var url = window.location.href;
	 $('#nanorep_dialog_opener').click(function(){
		 $('#nanorep_dialog_window').fadeIn(250,function(){
			 $(this).attr("style","");
			 ///$('#nanorep_isq_dialog').focus();
			 $("#nanorep_window").fadeIn(500);
		 });
		 });
     $('.nanorep_exit_image').click(function(){
											 	$('#nanorep_window,#nanorep_dialog_window').fadeOut(750,function(){
												
											 			$('#nanorep_window,#nanorep_dialog_window'). hide();
											 		}
											 	);
											});

		  //$('#nanorep_dialog_window').show();  
          //$('.chat_div').fadeIn('slow');
          
  

}

/**--------- END nanorep side dialog -------------**/

/**
 * Client side validation. 
 * @param {String} element The element we want to check.
 * @param {String} title The title of the element.
 * @param {Object} options The options we want to check.
 */
function client_side_validate(element, title, options){
    
    var default_args = { //default values.
		'empty'	:	 false,
		'digit'	:	 false,
		'mail'	:	 false,
		'length':	 false,
		'heb_chars': false,
        'eqlength' : 30
	}
    var default_weight = { //defalt weight
		'empty'	:	    1,
		'digit'	:	    2,
		'mail'	:	    2,
		'length':	    3,
		'heb_chars':	4,
        'not_define' : 10000 //weight for the first time.
	}
	for(var index in default_args) {
		if (typeof options[index] == "undefined") { //set options to have all the needed values
            options[index] = default_args[index];
        }
	}
    $(element).blur(function(){
    	
        var current_checked = 'not_define';
        var error_msg = '';    
        for (var index in options){
           // alert(index);
            var tmp_msg = '';
            var use_index = true; //flag which tell us if we want to use to option or not.
            if (options[index]){
                switch(index) {
                    case 'empty': //if empty validation is set for true
                        if ($(element).attr('value') == '') {
                            tmp_msg = title + Drupal.t(' הינו שדה חובה');
                            use_index = true;
                        }
                        else { // even though the validation of this option is on, we dont want to use it because the field is not empty.
                            use_index = false;
                        }
                        break;
                    case 'digit': //if digit validation is set for true.
                        if (!client_side_is_digit($(element).attr('value'))) {
                            tmp_msg = title + Drupal.t(' חייב להיות מספר');
                            use_index = true;
                        }
                        else { // even though the validation of this option is on, we dont want to use it because the field is a digit.
                            use_index = false;
                        }
                        break;
                    case 'mail': //if mail validation is set for true
                        if (!checkemail($(element).attr('value'))) {
                            tmp_msg = title + Drupal.t(' לא תקין');
                            use_index = true;
                        }
                        else {
                            use_index = false;
                        }
                        break;
                    case 'length': //if length is set for true.
                        if ($(element).attr('value').length != options['eqlength']) {
                            tmp_msg = title + Drupal.t(' חייב להיות ') + options['eqlength'];
                            use_index = true;
                        }
                        else {
                            use_index = false;
                        }
                        break;
                    case 'heb_chars':
                    	if( !check_side_hebrew_validation(element)) {
                    		tmp_msg = title + Drupal.t(' חייב להכיל רק תווים בעברית');
                            use_index = true;
                    	}
                    	else use_index = false;
                    	break;
                    default:                    	
                    	break;
                }
                // if we wnat to use the validation(because it was set for true and it didn't ass the test) and the current index weight is lower then the previous check
                if ((use_index) && (default_weight[index] < default_weight[current_checked])){ 
                    error_msg = tmp_msg;
                    current_checked = index;
                    
                }
            }
        }
   
        if (error_msg){ // if the error msg is not empty
            $(element).parents('.txt_fld_design').siblings('.custom_error').html('<span class="error tami4-form-error">' + error_msg +'</span>');
        }
        else {
            $(element).parents('.txt_fld_design').siblings('.custom_error').html('');
        }
    });
}

function check_client_validation(element, title, options){
     var default_args = { //default values.
		'empty'	:	    false,
		'digit'	:	    false,
		'mail'	:	    false,
		'length':	    false,
		'heb_chars':	false,
        'eqlength' :    30
	}
    var default_weight = { //defalt weight
		'empty'	:	    1,
		'digit'	:	    2,
		'mail'	:	    2,
		'length':	    3,
		'heb_chars':	4,
        'not_define':   10000 //weight for the first time.
	}
	for(var index in default_args) {
		if (typeof options[index] == "undefined") { //set options to have all the needed values
            options[index] = default_args[index];
        }
	}
        
        var current_checked = 'not_define';
        var error_msg = '';    
        for (var index in options){
           // alert(index);
            var tmp_msg = '';
            var use_index = true; //flag which tell us if we want to use to option or not.
            if (options[index]){
                switch(index) {
                    case 'empty': //if empty validation is set for true
                        if ($(element).attr('value') == '') {
                            tmp_msg = title + Drupal.t(' הינו שדה חובה');
                            use_index = true;
                        }
                        else { // even though the validation of this option is on, we dont want to use it because the field is not empty.
                            use_index = false;
                        }
                        break;
                    case 'digit': //if digit validation is set for true.
                        if (!client_side_is_digit($(element).attr('value'))) {
                            tmp_msg = title + Drupal.t(' חייב להיות מספר');
                            use_index = true;
                        }
                        else { // even though the validation of this option is on, we dont want to use it because the field is a digit.
                            use_index = false;
                        }
                        break;
                    case 'mail': //if mail validation is set for true
                        if (!checkemail($(element).attr('value'))) {
                            tmp_msg = title + Drupal.t(' לא תקין');
                            use_index = true;
                        }
                        else {
                            use_index = false;
                        }
                        break;
                    case 'length': //if length is set for true.
                        if ($(element).attr('value').length != options['eqlength']) {
                            tmp_msg = title + Drupal.t(' חייב להיות ') + options['eqlength'];
                            use_index = true;
                        }
                        else {
                            use_index = false;
                        }
                        break;
                    case 'heb_chars':
                    	if( !check_side_hebrew_validation(element)) {
                    		tmp_msg = title + Drupal.t(' חייב להכיל רק תווים בעברית');
                            use_index = true;
                    	}
                    	else use_index = false;
                    	break;
                }
                // if we wnat to use the validation(because it was set for true and it didn't ass the test) and the current index weight is lower then the previous check
                if ((use_index) && (default_weight[index] < default_weight[current_checked])){ 
                    error_msg = tmp_msg;
                    current_checked = index;
                    
                }
            }
        }
   
        if (error_msg){ // if the error msg is not empty
            $(element).parents('.txt_fld_design').siblings('.custom_error').html('<span class="error tami4-form-error">' + error_msg +'</span>');
            return false;
        }
        else {
            $(element).parents('.txt_fld_design').siblings('.custom_error').html('');
            return true;
        }

}

function contact_us_client_validate(){
    
  //alert('here');
   var option = {'empty':true};   
   client_side_validate('#edit-full_name',  Drupal.t('שם'), {'empty': true,'heb_chars':false});
   
  client_side_validate(
      '#edit-phone_number', 
      Drupal.t('טלפון'), 
      {
        'empty':true,
		'digit'	:	true,
		'length':	true,
        'eqlength' : 7
      }
  );
  client_side_validate('#edit-email', Drupal.t('דוא"ל'), {'mail' : true, 'empty' : true});
  client_side_is_textarea('#edit-message-body', Drupal.t('הודעה הינה שדה חובה'));
}



function client_side_is_digit(element){
   // alert(msg);
    var intRegex = /^\d+$/;
    
    if (intRegex.test(element)) {
        return true;
    }
    else {
        return false;
    }

}

function checkemail(str){
   // var str=document.validation.emailcheck.value;
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if (filter.test(str)) {
        testresults = true;
    }
    else {
      //  alert("Please input a valid email address!")
        testresults = false;
    }
    return (testresults);
}

function client_side_is_textarea(element, msg){
    $(element).blur(function(){
       if ($(element).attr('value') == ''){
           $(element).parents('#edit-message-body-wrapper').siblings('.custom_error').html('<span class="error tami4-form-error">' + msg +'</span>');
          
       }
       else {
           $(element).parents('#edit-message-body-wrapper').siblings('.custom_error').html('');
          
       }
   });
}
function check_client_side_is_textarea(element, msg){
  // alert(msg);
       if ($(element).attr('value') == ''){
           $(element).parents('#edit-message-body-wrapper').siblings('.custom_error').html('<span class="error tami4-form-error">' + msg +'</span>');
           return false;
       }
       else {
           $(element).parents('#edit-message-body-wrapper').siblings('.custom_error').html('');
           return true;
       }
}
function check_client_side_select(){
    if ($('div.selectbox_request_type span.jquery-selectbox-currentItem').text() == 'בחרו נושא'){
        $('.selectbox_request_type').find('.custom_error').html('<span class="error tami4-form-error">' + Drupal.t('נושא הפניה הינו שדה חובה') +'</span>');
        return false;  
    }
    else {
        true;
    }
}

function check_contact_client_phone_prefix(){
    if($('#edit-phone-prefix-wrapper').find('.jquery-selectbox-currentItem').text() == 'בחר'){
        var phone_number = $('#edit-phone_number').attr('value');
        var phone_number_msg = "<span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>";
        if(phone_number == ''){
            phone_number_msg = "<span class='error tami4-form-error'>" + Drupal.t('טלפון הינו שדה חובה') + "</span><span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>";
        }
        else if(phone_number.length != 7){
            phone_number_msg = "<span class='error tami4-form-error'>" + Drupal.t('טלפון חייב להיות בעל 7 ספרות') + "</span><span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>";
        } 
         else if(!client_side_is_digit(phone_number)){
            phone_number_msg = "<span class='error tami4-form-error'>" + Drupal.t('טלפון הינו חייב להיות מספר') + "</span><span class='error tami4-form-error error_phone_prefix'>" + Drupal.t('קדומת הינו שדה חובה') + "</span>";
        }
        $('#edit-phone_number').parents('.txt_fld_design').siblings('.custom_error').html(phone_number_msg);
        return false; 
   }
   else {
       return true;
   }
}
function pausecomp(millis){
    var date = new Date();
    var curDate = null;
    
    do { curDate = new Date(); }
    while(curDate-date < millis);
} ;
/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();;
/**
 * Automatic increase button text width to add some spacing between horizonal button surround to button text 
 * For now, it called only by buttons navigation
 * 
 */
function increase_troubleshooting_stage3_elements_width() {
	var new_width = 'auto';
	$('.troubleshooting_wizard.step2-3.step-3 .troubleshooting_blue_button').each(function(index) {
		new_width = parseInt($(this).outerWidth()) + 20;
		new_width = new_width + 'px'+ ' !important';		
		$(this).attr('style', 'width: '+new_width+'');		
	});
}

/**
 * Modifly position of troubleshooting left block for image/s, flash, non-media cases. 
 * 
 */
function modify_troubleshooting_left_block_position() {
	if($('.troubleshooting_wizard.step2-3.step-3 .left_node_value .rotate_images ul.troubleshooting_carouslide ul li.s-id-0').html()) {
    	var image_rotate_height = $('.troubleshooting_wizard.step2-3.step-3 .left_node_value .rotate_images ul.troubleshooting_carouslide').outerHeight();
    	image_rotate_height = parseInt(image_rotate_height) - 115;
    	$('.troubleshooting_wizard.step2-3.step-3 .troubleshooting_links_block_class').css('margin-top',image_rotate_height+'px');
    }
    
    
    if($('.troubleshooting_wizard.step2-3.step-3 .left_node_value .rotate_images .swftools-swf').html()) {
    	$('.troubleshooting_wizard.step2-3.step-3 .troubleshooting_links_block_class').css('margin-top','100px');
    }
}

/**
 * Function add visitor tracking via ajax.
 * For now, it called only by buttons navigation
 * 
 */
function ajax_mark_troubleshooting_visit(mlid,is_valid_tree,path_url) {
	if(is_valid_tree) is_valid_tree = '1'; 
	else is_valid_tree = '0';
	$.get('/ajax/mark_troubleshooting_visit',{ 'mlid':encodeURI(mlid), 'is_valid_tree':encodeURI(is_valid_tree) }, function(result){
		location.href = path_url;		
	});
}

jQuery(document).ready(function() {
    jQuery('body.page-troubleshooting-wizard .troubleshooting_carouslide').CarouSlide({
    	animType:"slide",
		showBackNext:true,
		autoAnim: false,	
		animInfinity: true,
		slideTime: 1000,
		showSlideNav: true,
		easingStyle: "easeInSine"
    });
    
    increase_troubleshooting_stage3_elements_width();
    modify_troubleshooting_left_block_position();    
});;
$(document).ready(function() {	

	$('body.node-type-resolve-problems form#node-form .node-form .form-item select').each(function(index) {
		
		$(this).change(function() {
			var the_value = $(this).val();
			$(this).parents('td').find('input.autocomplete').removeClass('autocomplete-processed');
			$(this).parents('td').find('input.autocomplete').val('/resolve_problems/products_autocomplete/1/' + the_value);
			//Drupal.attachBehaviors(document);
			Drupal.behaviors.autocomplete();
			$(this).parents('td').find('input.autocomplete').addClass('autocomplete-processed');
		});
		
	});
	
});;
/*
 * Get html select class id and return widget field numuric value
 */
function get_troubleshooting_widget_counter(widget_field_string) {
	var widget = 'edit-field-button-'; //a constant class pattern of string within all "select" classes
	var pos = widget_field_string.indexOf(widget);
	var string_len = widget.length;
	
	if(pos == -1 ) return false;
	
	var pos2 = widget_field_string.indexOf('-');
	if(pos2 == -1 ) return false;
	
	var widget_field_number = parseInt(widget_field_string.substr(string_len+pos,pos2-pos-1));
	
	return widget_field_number;
}

/*
 * Get javascript object of some selected element and return array of all relevant selected values
 * Return array with 4 selected values
 */
function get_troubleshooting_admin_selected_values(obj) {	
	var val1 = $(obj).parents('td').find('select.product_nid_class_admin_item').val();
	var val2 = $(obj).parents('td').find('select.troubleshooting_category_class_admin_item').val();
	var val3 = $(obj).parents('td').find('select.tree_mlid_level1_class_admin_item').val();
	var val4 = $(obj).parents('td').find('select.tree_mlid_class_admin_item').val();
	
	return [val1,val2,val3,val4];
}

/*
 * Generate select input html from ajax values * 
 */
function generate_select_input_html_from_array(result) {
	var s = '';
	$.each(result, function(key, val) {					
	    s += '<option value="'+key+'">'+val+'</option>';
	});
	return s;
}

/*
 * 
 * ajax to update select list of "tree_mlid_level1" or "tree_mlid" and update relevant elements with return values
 * 
 */
function ajax_update_select_list(current_obj,select_string) {
	
	var all_selected_values = get_troubleshooting_admin_selected_values(current_obj);
	
	switch(select_string) {
		case 'both_tree_ajax': //execute "tree_mlid_level1" ajax, then "tree_mlid" ajax
			Siebel_execute_load_effect();
			$.getJSON('/ajax/troubleshooting_button/get_tree_mlid_level1',{ 'product_nid':encodeURI(all_selected_values[0]), 'troubleshooting_category':encodeURI(all_selected_values[1]), 'tree_mlid_level1':encodeURI(all_selected_values[2]), 'tree_mlid':encodeURI(all_selected_values[3]) }, function(result){			
				$(current_obj).parents('td').find('select.tree_mlid_level1_class_admin_item').html( generate_select_input_html_from_array(result) );				
			
				/* execute tree_mlid ajax */
				all_selected_values = get_troubleshooting_admin_selected_values(current_obj);
				$.getJSON('/ajax/troubleshooting_button/get_tree_mlid',{ 'product_nid':encodeURI(all_selected_values[0]), 'troubleshooting_category':encodeURI(all_selected_values[1]), 'tree_mlid_level1':encodeURI(all_selected_values[2]), 'tree_mlid':encodeURI(all_selected_values[3]) }, function(result){
					$(current_obj).parents('td').find('select.tree_mlid_class_admin_item').html(generate_select_input_html_from_array(result));
					Siebel_execute_unload_effect();
				});
				/*/execute tree_mlid ajax */
				
			});
			break;
		case 'tree_mlid':
			Siebel_execute_load_effect();
			$.getJSON('/ajax/troubleshooting_button/get_tree_mlid',{ 'product_nid':encodeURI(all_selected_values[0]), 'troubleshooting_category':encodeURI(all_selected_values[1]), 'tree_mlid_level1':encodeURI(all_selected_values[2]), 'tree_mlid':encodeURI(all_selected_values[3]) }, function(result){				
				$(current_obj).parents('td').find('select.tree_mlid_class_admin_item').html(generate_select_input_html_from_array(result));
				Siebel_execute_unload_effect();
			});
			break;
		default:
			return false;
			break;
	}
	
	return true;
}

/*
 * Initialize change event to troubleshooting_category field.
 * When different option is selected, function changes options of select fields below. 
 */
function initialize_change_event_to_field_troubleshooting_category() {
	//$('body.logged-in.node-type-troubleshooting-wizard .node-form #field_button_values .form-item select.troubleshooting_category_class_admin_item').each(function(index) {	
	$('body.logged-in .node-form #field_button_values .form-item select.troubleshooting_category_class_admin_item').each(function(index) {
		$(this).change(function(index) {
			ajax_update_select_list(this,'both_tree_ajax');
		});
	});
}

/*
 * Initialize change event to product_nid field.
 * When different option is selected, function changes options of select fields below. 
 */
function initialize_change_event_to_field_product_nid() {
	//$('body.logged-in.node-type-troubleshooting-wizard .node-form #field_button_values .form-item select.product_nid_class_admin_item').each(function(index) {	
	$('body.logged-in .node-form #field_button_values .form-item select.product_nid_class_admin_item').each(function(index) {
		$(this).change(function(index) {										
			ajax_update_select_list(this,'both_tree_ajax');
		});
	});
}

/*
 * Initialize change event to tree_mlid_level1 field.
 * When different option is selected, function changes options of select fields below. 
 */
function initialize_change_event_to_field_tree_mlid_level1() {
	//$('body.logged-in.node-type-troubleshooting-wizard .node-form #field_button_values .form-item select.tree_mlid_level1_class_admin_item').each(function(index) {	
	$('body.logged-in .node-form #field_button_values .form-item select.tree_mlid_level1_class_admin_item').each(function(index) {
		$(this).change(function(index) {
			ajax_update_select_list(this,'tree_mlid');
			//alert( $(this).parents('td').find('select.tree_mlid_class_admin_item').html() );					
		});
	});
}
	
jQuery(document).ready(function() {
	initialize_change_event_to_field_troubleshooting_category();
	initialize_change_event_to_field_product_nid();
	initialize_change_event_to_field_tree_mlid_level1();
});;
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */;
/*
    http://www.JSON.org/json2.js
    2010-08-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

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


    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.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
;
/*
 * Please use this file for document ready purposes only. 
 * Put tami4.js functions in "tami4_functions.js" 
 */

// chekcs if ie7
function is_ie_7()
{
	var iebrowser = false;
	var version7 = false; 
	jQuery.each(jQuery.browser, function(i, val) {
		if(i == 'version' && val==7.0)
			version7 = true;
		if(i == 'msie' && val == true)
			iebrowser = true;
	});
	
	return iebrowser && version7

}

function timer_1()
{
	/*
	$("#product_page .prod_ayntk_img").click(function(){
		window.setTimeout(setheight,800); // sets a timeout for the adjust height of pashtut atipul
	});
	*/
    if($("#product_page #tab_left img").attr('id') == 'prod_img_open' || $("#product_page #tab_left img").attr('id') == 'prod_img_close' || $("#product_page #tab_left img").hasClass('bundle_title_img'))
    {
    	
		$("#product_page #tab_left img").click(function(){
			window.setTimeout(setclass,1000);
			window.setTimeout(setheight,800); // sets a timeout for the adjust height of pashtut atipul
			window.setTimeout(timer_1,900);
			//alert("clicked_1");
		});
    }
	
}

function setclass() 
{
	$("#product_page #tab_left img").each(function(){
	    if($(this).attr('id') == 'prod_img_open' || $(this).attr('id') == 'prod_img_close')
		{
		    $(this).addClass("prod_ayntk_img");
		}
	})
	$("#product_page .bundle_title_img").each(function(){
		$(this).addClass("prod_ayntk_img");
	})
}
function setheight(){
	if($("#product_page #pashtut_hatiful_li").css('display') == "list-item")
	{
		$("#product_page #product_content").height($("#product_page #pashtut_hatiful_li").height()+50);
		//alert("changed")
	}else
	{
		$("#product_page #product_content").height($("#product_page #kedai_ladaat_li").height()+100);
	}
	
	//window.setTimeout(timer,300);
		
}

$(document).ready(function(){
   
	// set product page when there are no tabs margin bottom
	
	if($("#content_tabs_menu").children().length == 0)
		$("#product_page").css('margin-bottom','250px');
	
	
	
	// set first dd css on product page for ie 7; 
	
	if(is_ie_7())
	{
		var dd_elements= $("#product_page #product_content ul#content_tabs  li #tab_right").find('dd')
		var dd_css = {'float': 'right'}
		$(dd_elements[0]).css(dd_css)
	}
	/*
	// set #pashtut_hatiful_li and #kedai_ladaat_li  adjusting the height of right side content container; if ie7 then don't use this height set 
	if(!is_ie_7())
	{
		// adds class to #tab_left img
		$("#product_page #tab_left img").each(function(){
		    if($(this).attr('id') == 'prod_img_open' || $(this).attr('id') == 'prod_img_close')
		{
		    $(this).addClass("prod_ayntk_img");
		}
		})
		
		$("#product_page .bundle_title_img").each(function(){
		    $(this).addClass("prod_ayntk_img");
		})
		
		$("#product_page #product_content").height($("#product_page #kedai_ladaat_li").height()+100);
		$("#product_page #content_tabs_menu li:last-child").click(function(){
			$("#product_page #product_content").height($("#product_page #pashtut_hatiful_li").height()+50);
		});
		$("#product_page #content_tabs_menu li:first-child").click(function(){
			$("#product_page #product_content").height($("#product_page #kedai_ladaat_li").height()+100);
		});
		
		$("#product_page .prod_ayntk_img").click(function(){
				window.setTimeout(setclass,700);
				window.setTimeout(setheight,800); // sets a timeout for the adjust height of pashtut atipul
				//alert("clicked_0");
		});
		
		$("#product_page #tab_left img").click(function(){
		
		    if($(this).attr('id') == 'prod_img_open' || $(this).attr('id') == 'prod_img_close' || $(this).hasClass('bundle_title_img'))
		    {
		    	//alert("clicked")
				window.setTimeout(setclass,700);
				window.setTimeout(setheight,800);
				window.setTimeout(timer_1,900);// sets a timeout for the adjust height of pashtut atipul

		    }
		});
		
		
		

	}
	*/
	
	// set on private area if a product from sybel is not in our DB and the are no productcs to show under מוצרים in יןמן משלוחים
	if($("#page-myarea-log-shipping-page .bottom2 div").length == 0)
	{
	    $("#page-myarea-log-shipping-page .top_section , #page-myarea-log-shipping-page .bottom2").remove()
	}
	
	// set the nano rap in the center
	
		if(window.location.pathname == '/')
		{
			//console.log('home');
			set_nano_center(-610,-100);//(width pos,height pos)
		}
		else
		{
			//console.log('not home');
			set_nano_center(349,175);//(width pos,height pos)
		}
  
    
    $('form#lead-form input#edit-submit').click(
      function(){
        _gaq.push(['_trackEvent', 'Lead Form', 'click', 'Lead Submit']);
      }
    );
    $('ul.slider-holder > li').each(function(){
        
        $(this).show();
    });
    
    $('div.selectbox_request_type').click(function(){
        $('.selectbox_request_type').find('.custom_error').html('');
        //alert('here');
    });
    $('#contact-us-form').submit(function(){
    	var check_name = check_client_validation('#edit-full_name', Drupal.t('שם'), {'empty': true,'heb_chars': false});
        var check_phone = check_client_validation('#edit-phone_number', Drupal.t('טלפון'), {
            'empty':true,
    		'digit'	:	true,
    		'length':	true,
            'eqlength' : 7
          });
        var check_mail =  check_client_validation('#edit-email', Drupal.t('דוא"ל'), {'mail' : true, 'empty' : true});
        var check_txtarea = check_client_side_is_textarea('#edit-message-body', Drupal.t('הודעה הינה שדה חובה'));        
        var check_select = check_client_side_select();
        var check_phone_prefix = check_contact_client_phone_prefix();
        if ( check_name && check_phone && check_mail && check_txtarea /*&& check_select */&& check_phone_prefix){
           Siebel_execute_load_effect();
           return true;
        }
        else {
            return false;
        }
        
    }); //end of $('#contact-us-form').submit(function(){
        
    
    /*$('form#contact-us-form input#edit-submit').click(function(){
        contact_us_client_validate();
        return false;
        //Siebel_execute_load_effect();
    });*/
	faq_select_category();
	nanorep_side_dialog();
	
	job_email_value();
	$('.view-display-id-page_1 .expand_categories').click(
		function(e){
			collapse_faq_all(e);
			
		}
	);	
	var service_box_button = '#page-affiliate_program .affiliate_program .affiliate_program_img .service_box_button ';
	$(service_box_button+'a').hover(function(){
		
		$(service_box_button+'a').css('color','#0E76BC');
		$(service_box_button).css('background-image','url("/sites/all/themes/tami4/images/affiliate_program_button/affiliated_button_mouse_over.png")');
	},function(){
		$(service_box_button+'a').css('color','#FFF');
		$(service_box_button).css('background-image','url("/sites/all/themes/tami4/images/affiliate_program_button/affiliated_button_normal.png")');

	});
	$('.section-service-general-qna .views-field-title, .section-about-strauss-water-career .views-field-title').click(function(e){
		
		collapse_faq(e);
	});
	
    var question = true;
    $('.question_mark').mouseover(function(){
        if (question) {
            question = false;
            $(this).siblings().fadeIn('slow',function(){pausecomp(1000);});
        }
    });
    $('.question_mark').mouseout(function(){
        
        $(this).siblings().fadeOut('slow',function(){question = true;});
    });
	
	
    $("#contact-mail-page").validate({
  		rules: {
			name: {
				required: true
			},
			codes: { 
				selectNone: true 
  			},
    		phone: {
 				required: true,
     			number: true
    		},
			additional_phone: {
      			number: true
    		},
			types: { 
				selectNone: true 
  			}, 
			mail: { 
 				required: true,
				email: true 
  			} 
	  	}
	});

	$('#customer_service_blocks .more').click(function(){
		$(this).prev().toggle('slow');
		/*if ( $(this).html() == 'עוד<img src="/sites/all/themes/tami4/images/button/blue_arrow_down.png" class="open_arrow">' )
			$(this).html('סגור<img src="/sites/all/themes/tami4/images/button/blue_arrow_up.png" class="close_arrow">');
		else
			$(this).html('עוד<img src="/sites/all/themes/tami4/images/button/blue_arrow_down.png" class="open_arrow">');*/
          // alert($(this).attr('class'));
       if ($(this).children('img').hasClass('open_arrow')){
           $(this).html('סגור<img src="/sites/all/themes/tami4/images/button/blue_arrow_up.png" class="closed_arrow">');
       }
       else {
           $(this).html('עוד<img src="/sites/all/themes/tami4/images/button/blue_arrow_down.png" class="open_arrow">');
           
       }
	});
	
	$('#quick_nav h2').text(' ');
	
	/* Selectbox modifications */
	$("body.not-page-admin form #edit-phone-prefix").selectbox({'tabindex' : (parseInt( $('body.not-page-admin form input#edit-phone_number').attr('tabindex') ) - 5) });
	$("body.not-page-admin form#contact-us-form #edit-additional-phone-prefix").selectbox({'tabindex' : (parseInt( $('body.not-page-admin form input#edit-additional_phone').attr('tabindex') ) - 5) });
	$("body.not-page-admin form#shopping-cart-form #edit-additional-phone-prefix").selectbox({'tabindex' : (parseInt( $('body.not-page-admin form input#edit-additional_phone_number').attr('tabindex') ) - 5) });
	$("body.not-page-admin form #edit-request-type").selectbox();
	
	$('body.not-page-admin form .jquery-selectbox-list.jquery-custom-selectboxes-replaced-list').css('height','auto');
	$('body.not-page-admin form .jquery-selectbox-list.jquery-custom-selectboxes-replaced-list').css('width','auto');	
	$('body.not-page-admin form #edit-request-type-wrapper .jquery-selectbox-list.jquery-custom-selectboxes-replaced-list').css('width','auto');
	
	$('body.not-page-admin form #edit-phone-prefix-wrapper .jquery-selectbox.jquery-custom-selectboxes-replaced').css('width','52px');
	$('body.not-page-admin form #edit-additional-phone-prefix-wrapper .jquery-selectbox.jquery-custom-selectboxes-replaced').css('width','52px');
	
	$('body.not-page-admin form #edit-phone-prefix-wrapper .jquery-selectbox-list.jquery-custom-selectboxes-replaced-list').css('width','46px');
	$('body.not-page-admin form #edit-additional-phone-prefix-wrapper .jquery-selectbox-list.jquery-custom-selectboxes-replaced-list').css('width','46px');
	
	$('body.not-page-admin form #edit-request-type-wrapper .jquery-selectbox.jquery-custom-selectboxes-replaced').css('width','196px');	
	/*/Selectbox modifications */
	
	/* Checkbox modifications */	
	$('input[type="checkbox"]').each(function () {
		initialize_designed_checkbox( $(this) );
	});	
	/* Checkbox modifications */
	
	/*---------- Primary links - li change location  -----------*/
	$('body.front #header #primary-menu ul.primary-links li, body.not-front #header #primary-menu.primary-menu.level_1 li').each(function () {
		if($(' a',this)) {
			$(this).click(function () {				
				location.href = $(' a',this).attr('href');
			});
		}
		
	});
	/*---------- /Primary links - li change location  -----------*/
   
    /* Update "inner_content" height */
	if($('#page #left').html() && $('#page_content .back_main_content').html() ) { //relevant only if left region and inner_content exist
		if( $('#page #left').outerHeight() > $('#page_content .back_main_content').outerHeight() ) {
			$('#page_content .back_main_content ').height( $('#page #left').outerHeight() );
		}
	}	
    /* /Update "inner_content" height */
	
   
   /*********************** CHAT ******************************/
  $('.chat_service').click(function(){
      var url = window.location.href;
      $.get('/shopping_cart/chat', {
          url: url
      }, function(data){
      
          tami_execute_load_effect(data);
          
      }, 'text');
  });
	
    /**
     * COLOR PICKER
     */
     $('.color_picker_selected_more, .color_picker_selected_color').click(function(){
         
         $(this).parents('.color_picker_main').siblings('.color_picker_bo').toggle();
     });
     $('.color_picker_line').mouseover(function(){
        $(this).addClass('color_picker_line_over'); 
     });
     $('.color_picker_line').mouseout(function(){
        $(this).removeClass('color_picker_line_over'); 
     });
	 
	 /** check if the login-block is closed or open 
	 and if it is open then change the lead margin
	 */
     if ($(".login-header td.td-arrow .login-content-display").hasClass('content-visible') && $('body').hasClass('not-front')){
	 
	 	 var margintop = $('#left').css('marginTop');
		margintop = margintop.replace("px","") * 1;
		$('.not-front #left').css('marginTop',margintop  + 68 +'px');
	 }
}); //END OF DOCUMENT READY

function set_nano_center(width,height)
{
	 //Get the screen height and width
       
	   var winH = $(window).height() //maskHeight - pagePosition;
       var winW = $(window).width();
       var top  = (winH/2 - height) + $(window).scrollTop();
       var left = winW/2 - width;
       
       if(window.location.pathname == '/')
 	  {   	
    	   top = screen.height/2 - top;
    	   left = screen.width/2 - left;
    	   //console.log('height:'+screen.height+'width:'+screen.width);
    	  //return 0; 
 	  }
	  
	  var css = {top: top, right : left};
	  
	 //$(".not-front #nanorep_window").css(css);
	  $("#nanorep_window").css(css);
	  
}
;

