var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);

function openWindow(theURL,winName,features){
	window.open(theURL,winName,features);
}

function IsNumeric(strString){
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   for (i = 0; i < strString.length && blnResult == true; i++){
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1){
         blnResult = false;
      }
   }
   return blnResult;
}

function is_integer(value){
	for (i=0;i<value.length;i++)
	{
		if (value[i]<'0' || value[i]>'9')
		{
			return false;
		}
	}
	return true;
}

function validate_seach(){
	if($("#cauta").val().length<3){
		alert('Cautati dupa un cuvant de minim 3 caractere')
		return false;
	}
	location.href=url_base+str_replace(" ","-",$("#cauta").val())+'-'+$("#type").val();
}

function str_replace(search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

/* jquery.autocomplete */
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}('(3($){$.28.1n({14:3(b,c){5 d=S b=="1o";c=$.1n({},$.D.1G,{T:d?b:15,w:d?15:b,1p:d?$.D.1G.1p:10,U:c&&!c.1q?10:37},c);c.1r=c.1r||3(a){6 a};c.1s=c.1s||c.1H;6 I.K(3(){1I $.D(I,c)})},M:3(a){6 I.V("M",a)},1t:3(a){6 I.16("1t",[a])},1J:3(){6 I.16("1J")},1K:3(a){6 I.16("1K",[a])},1L:3(){6 I.16("1L")}});$.D=3(h,j){5 k={29:38,2a:40,2b:46,2c:9,2d:13,2e:27,2f:39,2g:33,2h:34,2i:8};5 l=$(h).3a("14","3b").N(j.2j);5 m;5 n="";5 o=$.D.2k(j);5 p=0;5 r;5 s={1u:B};5 t=$.D.2l(j,h,1M,s);5 u;$.1N.2m&&$(h.2n).V("3c.14",3(){4(u){u=B;6 B}});l.V(($.1N.2m?"3d":"3e")+".14",3(a){r=a.2o;3f(a.2o){O k.29:a.19();4(t.L()){t.2p()}z{W(0,C)}P;O k.2a:a.19();4(t.L()){t.2q()}z{W(0,C)}P;O k.2g:a.19();4(t.L()){t.2r()}z{W(0,C)}P;O k.2h:a.19();4(t.L()){t.2s()}z{W(0,C)}P;O j.1a&&$.1v(j.Q)==","&&k.2f:O k.2c:O k.2d:4(1M()){a.19();u=C;6 B}P;O k.2e:t.X();P;3g:1O(m);m=1P(W,j.1p);P}}).1Q(3(){p++}).3h(3(){p=0;4(!s.1u){2t()}}).2u(3(){4(p++>1&&!t.L()){W(0,C)}}).V("1t",3(){5 c=(1w.7>1)?1w[1]:15;3 1R(q,a){5 b;4(a&&a.7){17(5 i=0;i<a.7;i++){4(a[i].M.R()==q.R()){b=a[i];P}}}4(S c=="3")c(b);z l.16("M",b&&[b.w,b.J])}$.K(1b(l.E()),3(i,a){1S(a,1R,1R)})}).V("1J",3(){o.1c()}).V("1K",3(){$.1n(j,1w[1]);4("w"2v 1w[1])o.1d()}).V("1L",3(){t.1x();l.1x();$(h.2n).1x(".14")});3 1M(){5 a=t.2w();4(!a)6 B;5 v=a.M;n=v;4(j.1a){5 b=1b(l.E());4(b.7>1){v=b.18(0,b.7-1).2x(j.Q)+j.Q+v}v+=j.Q}Y=v.1y("3i");4(Y[1]!=""&&Y[1]!="1T"&&Y[1]!=1T){4(3j(Y[1])){3k.3l=3m+3n(" ","-",Y[0])+\'-\'+$(\'#3o\').E()+\'-\'+Y[1]+"/"}}z{l.E(v);1e();l.16("M",[a.w,a.J]);6 C}}3 W(a,b){4(r==k.2b){t.X();6}5 c=l.E();4(!b&&c==n)6;n=c;c=1f(c);4(c.7>=j.1U){l.N(j.1V);4(!j.1z)c=c.R();1S(c,2y,1e)}z{1A();t.X()}};3 1b(b){4(!b){6[""]}5 c=b.1y(j.Q);5 d=[];$.K(c,3(i,a){4($.1v(a))d[i]=$.1v(a)});6 d}3 1f(a){4(!j.1a)6 a;5 b=1b(a);6 b[b.7-1]}3 1B(q,a){4(j.1B&&(1f(l.E()).R()==q.R())&&r!=k.2i){l.E(l.E()+a.3p(1f(n).7));$.D.1W(h,n.7,n.7+a.7)}};3 2t(){1O(m);m=1P(1e,3q)};3 1e(){5 c=t.L();t.X();1O(m);1A();4(j.2z){l.1t(3(a){4(!a){4(j.1a){5 b=1b(l.E()).18(0,-1);l.E(b.2x(j.Q)+(b.7?j.Q:""))}z l.E("")}})}4(c)$.D.1W(h,h.J.7,h.J.7)};3 2y(q,a){4(a&&a.7&&p){1A();t.2A(a,q);1B(q,a[0].J);t.1X()}z{1e()}};3 1S(c,d,e){4(!j.1z)c=c.R();5 f=o.2B(c);4(f&&f.7){d(c,f)}z 4((S j.T=="1o")&&(j.T.7>0)){5 g={3r:+1I 3s()};$.K(j.2C,3(a,b){g[a]=S b=="3"?b():b});$.3t({3u:"3v",3w:"14"+h.3x,2D:j.2D,T:j.T,w:$.1n({q:1f(c),3y:j.U},g),3z:3(a){5 b=j.1C&&j.1C(a)||1C(a);o.1g(c,b);d(c,b)}})}z{t.2E();e(c)}};3 1C(a){5 b=[];5 c=a.1y("\\n");17(5 i=0;i<c.7;i++){5 d=$.1v(c[i]);4(d){d=d.1y("|");b[b.7]={w:d,J:d[1],M:j.1D&&j.1D(d,d[1])||d[1]}}}6 b};3 1A(){l.1h(j.1V)}};$.D.1G={2j:"3A",2F:"3B",1V:"3C",1U:1,1p:3D,1z:B,1i:C,1Y:B,1j:10,U:3E,2z:B,2C:{},1Z:C,1H:3(a){6 a[0]},1s:15,1B:B,F:0,1a:B,Q:", ",1r:3(a,b){6 a.2G(1I 3F("(?![^&;]+;)(?!<[^<>]*)("+b.2G(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2H,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2H"),"<2I>$1</2I>")},1q:C,1E:3G};$.D.2k=3(g){5 h={};5 j=0;3 1i(s,a){4(!g.1z)s=s.R();5 i=s.3H(a);4(i==-1)6 B;6 i==0||g.1Y};3 1g(q,a){4(j>g.1j){1c()}4(!h[q]){j++}h[q]=a}3 1d(){4(!g.w)6 B;5 b={},2J=0;4(!g.T)g.1j=1;b[""]=[];17(5 i=0,2K=g.w.7;i<2K;i++){5 c=g.w[i];c=(S c=="1o")?[c]:c;5 d=g.1s(c,i+1,g.w.7);4(d===B)20;5 e=d.3I(0).R();4(!b[e])b[e]=[];5 f={J:d,w:c,M:g.1D&&g.1D(c)||d};b[e].21(f);4(2J++<g.U){b[""].21(f)}};$.K(b,3(i,a){g.1j++;1g(i,a)})}1P(1d,25);3 1c(){h={};j=0}6{1c:1c,1g:1g,1d:1d,2B:3(q){4(!g.1j||!j)6 15;4(!g.T&&g.1Y){5 a=[];17(5 k 2v h){4(k.7>0){5 c=h[k];$.K(c,3(i,x){4(1i(x.J,q)){a.21(x)}})}}6 a}z 4(h[q]){6 h[q]}z 4(g.1i){17(5 i=q.7-1;i>=g.1U;i--){5 c=h[q.3J(0,i)];4(c){5 a=[];$.K(c,3(i,x){4(1i(x.J,q)){a[a.7]=x}});6 a}}}6 15}}};$.D.2l=3(e,f,g,h){5 j={G:"3K"};5 k,y=-1,w,1F="",22=C,H,A;3 2L(){4(!22)6;H=$("<3L/>").X().N(e.2F).Z("3M","3N").23(2M.2N);A=$("<3O/>").23(H).3P(3(a){4(11(a).2O&&11(a).2O.3Q()==\'2P\'){y=$("24",A).1h(j.G).3R(11(a));$(11(a)).N(j.G)}}).2u(3(a){$(11(a)).N(j.G);g();f.1Q();6 B}).3S(3(){h.1u=C}).3T(3(){h.1u=B});4(e.F>0)H.Z("F",e.F);22=B}3 11(a){5 b=a.11;3U(b&&b.3V!="2P")b=b.3W;4(!b)6[];6 b}3 12(a){k.18(y,y+1).1h(j.G);2Q(a);5 b=k.18(y,y+1).N(j.G);4(e.1q){5 c=0;k.18(0,y).K(3(){c+=I.1k});4((c+b[0].1k-A.1l())>A[0].3X){A.1l(c+b[0].1k-A.3Y())}z 4(c<A.1l()){A.1l(c)}}};3 2Q(a){y+=a;4(y<0){y=k.1m()-1}z 4(y>=k.1m()){y=0}}3 2R(a){6 e.U&&e.U<a?e.U:a}3 2S(){A.2T();5 a=2R(w.7);17(5 i=0;i<a;i++){4(!w[i])20;5 b=e.1H(w[i].w,i+1,a,w[i].J,1F);4(b===B)20;5 c=$("<24/>").3Z(e.1r(b,1F)).N(i%2==0?"41":"42").23(A)[0];$.w(c,"2U",w[i])}k=A.43("24");4(e.1Z){k.18(0,1).N(j.G);y=0}4($.28.2V)A.2V()}6{2A:3(d,q){2L();w=d;1F=q;2S()},2q:3(){12(1)},2p:3(){12(-1)},2r:3(){4(y!=0&&y-8<0){12(-y)}z{12(-8)}},2s:3(){4(y!=k.1m()-1&&y+8>k.1m()){12(k.1m()-1-y)}z{12(8)}},X:3(){H&&H.X();k&&k.1h(j.G);y=-1},L:3(){6 H&&H.44(":L")},45:3(){6 I.L()&&(k.2W("."+j.G)[0]||e.1Z&&k[0])},1X:3(){5 a=$(f).47();H.Z({F:S e.F=="1o"||e.F>0?e.F:$(f).F(),2X:a.2X+f.1k,26:a.26}).1X();4(e.1q){A.1l(0);A.Z({2Y:e.1E,48:\'49\'});4($.1N.4a&&S 2M.2N.4b.2Y==="1T"){5 b=0;k.K(3(){b+=I.1k});5 c=b>e.1E;A.Z(\'4c\',c?e.1E:b);4(!c){k.F(A.F()-2Z(k.Z("30-26"))-2Z(k.Z("30-4d")))}}}},2w:3(){5 a=k&&k.2W("."+j.G).1h(j.G);6 a&&a.7&&$.w(a[0],"2U")},2E:3(){A&&A.2T()},1x:3(){H&&H.4e()}}};$.D.1W=3(a,b,c){4(a.31){5 d=a.31();d.4f(C);d.4g("32",b);d.4h("32",c);d.4i()}z 4(a.35){a.35(b,c)}z{4(a.36){a.36=b;a.4j=c}}a.1Q()}})(4k);',62,269,'|||function|if|var|return|length|||||||||||||||||||||||||data||active|else|list|false|true|Autocompleter|val|width|ACTIVE|element|this|value|each|visible|result|addClass|case|break|multipleSeparator|toLowerCase|typeof|url|max|bind|onChange|hide|selTxt|css||target|moveSelect||autocomplete|null|trigger|for|slice|preventDefault|multiple|trimWords|flush|populate|hideResultsNow|lastWord|add|removeClass|matchSubset|cacheLength|offsetHeight|scrollTop|size|extend|string|delay|scroll|highlight|formatMatch|search|mouseDownOnSelect|trim|arguments|unbind|split|matchCase|stopLoading|autoFill|parse|formatResult|scrollHeight|term|defaults|formatItem|new|flushCache|setOptions|unautocomplete|selectCurrent|browser|clearTimeout|setTimeout|focus|findValueCallback|request|undefined|minChars|loadingClass|Selection|show|matchContains|selectFirst|continue|push|needsInit|appendTo|li||left||fn|UP|DOWN|DEL|TAB|RETURN|ESC|COMMA|PAGEUP|PAGEDOWN|BACKSPACE|inputClass|Cache|Select|opera|form|keyCode|prev|next|pageUp|pageDown|hideResults|click|in|selected|join|receiveData|mustMatch|display|load|extraParams|dataType|emptyList|resultsClass|replace|gi|strong|nullData|ol|init|document|body|nodeName|LI|movePosition|limitNumberOfItems|fillList|empty|ac_data|bgiframe|filter|top|maxHeight|parseInt|padding|createTextRange|character|||setSelectionRange|selectionStart|150||188|attr|off|submit|keypress|keydown|switch|default|blur|_|IsNumeric|location|href|url_base|str_replace|type|substring|200|timestamp|Date|ajax|mode|abort|port|name|limit|success|ac_input|ac_results|ac_loading|400|100|RegExp|180|indexOf|charAt|substr|ac_over|div|position|absolute|ul|mouseover|toUpperCase|index|mousedown|mouseup|while|tagName|parentNode|clientHeight|innerHeight|html||ac_even|ac_odd|find|is|current||offset|overflow|auto|msie|style|height|right|remove|collapse|moveStart|moveEnd|select|selectionEnd|jQuery'.split('|'),0,{}));

/* scrollTo */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/* timers */

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

/* lightbox */
(function($){
	var opts;

	$.fn.lightbox = function(options){
		// build main options
		opts = $.extend({}, $.fn.lightbox.defaults, options);

		// initalize the lightbox
		$.fn.lightbox.initialize();
		return this.each(function(){
			$(this).click(function(){
				$(this).lightbox.start(this);
				return false;
			});
		});
	};

	// lightbox functions
	$.fn.lightbox.initialize = function(){
		$('#overlay').remove();
		$('#lightbox').remove();
		opts.inprogress = false;
		var outerImage = '<div id="outerImageContainer"><div id="imageContainer"><img id="lightboxImage"><div id="hoverNav"><a href="javascript://" title="' + opts.strings.prevLinkTitle + '" id="prevLink"></a><a href="javascript://" id="nextLink" title="' + opts.strings.nextLinkTitle + '"></a></div><div id="loading"><a href="javascript://" id="loadingLink"><img src="'+opts.fileLoadingImage+'"></a></div></div></div>';
		var imageData = '<div id="imageDataContainer" class="clearfix"><div id="imageData"><div id="imageDetails"><span id="caption"></span><span id="numberDisplay"></span></div><div id="bottomNav">'

		if (opts.displayHelp)
			imageData += '<span id="helpDisplay">' + opts.strings.help + '</span>';

		imageData += '<a href="javascript://" id="bottomNavClose" title="' + opts.strings.closeTitle + '"><img src="'+opts.fileBottomNavCloseImage+'"></a></div></div></div>';

		var string;

		if (opts.navbarOnTop) {
		  string = '<div id="overlay"></div><div id="lightbox">' + imageData + outerImage + '</div>';
		  $("body").append(string);
		  $("#imageDataContainer").addClass('ontop');
		} else {
		  string = '<div id="overlay"></div><div id="lightbox">' + outerImage + imageData + '</div>';
		  $("body").append(string);
		}

		$("#overlay").click(function(){ $.fn.lightbox.end(); }).hide();
		$("#lightbox").click(function(){ $.fn.lightbox.end();}).hide();
		$("#loadingLink").click(function(){ $.fn.lightbox.end(); return false;});
		$("#bottomNavClose").click(function(){ $.fn.lightbox.end(); return false; });
		$('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
		$('#imageDataContainer').width(opts.widthCurrent);
	};

	$.fn.lightbox.getPageSize = function(){
		var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

		if (self.innerHeight) { // all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}


		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}

		var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};


	$.fn.lightbox.getPageScroll = function(){
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}

		var arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};

	$.fn.lightbox.pause = function(ms){
		var date = new Date();
		var curDate = null;
		do{curDate = new Date();}
		while( curDate - date < ms);
	};

	$.fn.lightbox.start = function(imageLink){

		$("select, embed, object").hide();
		var arrayPageSize = $.fn.lightbox.getPageSize();
		$("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : opts.overlayOpacity}).fadeIn();
		opts.imageArray = [];
		imageNum = 0;

		var anchors = document.getElementsByTagName( imageLink.tagName);

		// if image is NOT part of a set..
		if(!imageLink.rel || (imageLink.rel == '')){
			// add single image to Lightbox.imageArray
			opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
		} else {
		// if image is part of a set..
			$("a").each(function(){
				if(this.href && (this.rel == imageLink.rel)){
					opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
				}
			})


			for(i = 0; i < opts.imageArray.length; i++){
				for(j = opts.imageArray.length-1; j>i; j--){
					if(opts.imageArray[i][0] == opts.imageArray[j][0]){
						opts.imageArray.splice(j,1);
					}
				}
			}
			while(opts.imageArray[imageNum][0] != imageLink.href) { imageNum++;}
		}

		// calculate top and left offset for the lightbox
		var arrayPageScroll = $.fn.lightbox.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();


		if (!opts.slideNavBar)
			$('#imageData').hide();

		$.fn.lightbox.changeImage(imageNum);

	};

	$.fn.lightbox.changeImage = function(imageNum){
		if(opts.inprogress == false){
			opts.inprogress = true;
			opts.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#loading').show();
			$('#lightboxImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();

			if (opts.slideNavBar) { // delay preloading image until navbar will slide up
				// $('#imageDataContainer').slideUp(opts.navBarSlideSpeed, $.fn.doChangeImage);
				$('#imageDataContainer').hide();
				$('#imageData').hide();
				$.fn.doChangeImage();
			} else {
			    $.fn.doChangeImage();
			}
		}
	};

	$.fn.doChangeImage = function(){

		imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
		    var newWidth = imgPreloader.width;
		    var newHeight = imgPreloader.height;


			if (opts.fitToScreen) {
		        var arrayPageSize = $.fn.lightbox.getPageSize();
				var ratio;
				var initialPageWidth = arrayPageSize[2] - 2 * opts.borderSize;
				var initialPageHeight = arrayPageSize[3] - 200;

				if (imgPreloader.height > initialPageHeight)
				{
					newWidth = parseInt((initialPageHeight/imgPreloader.height) * imgPreloader.width);
					newHeight = initialPageHeight;
				}
				else if (imgPreloader.width > initialPageWidth)
				{
					newHeight = parseInt((initialPageWidth/imgPreloader.width) * imgPreloader.height);
					newWidth = initialPageWidth;
				}
			}

			$('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])
							   .width(newWidth).height(newHeight);
			$.fn.lightbox.resizeImageContainer(newWidth, newHeight);
		}

		imgPreloader.src = opts.imageArray[opts.activeImage][0];
	}
	
	$.fn.lightbox.end = function(){
		$.fn.lightbox.disableKeyboardNav();
		$('#lightbox').hide();
		$('#overlay').fadeOut();
		$('select, object, embed').show();
	};

	$.fn.lightbox.preloadNeighborImages = function(){
		if((opts.imageArray.length - 1) > opts.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = opts.imageArray[opts.activeImage + 1][0];
		}
		if(opts.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = opts.imageArray[opts.activeImage - 1][0];
		}
	};

	$.fn.lightbox.keyboardAction = function(e){
		if (e == null) { // ie
			var keycode = event.keyCode;
			var escapeKey = 27;
		} else { // mozilla
			var keycode = e.keyCode;
			var escapeKey = e.DOM_VK_ESCAPE;
		}

		var key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
			$.fn.lightbox.end();
		} else if((key == 'p') || (keycode == 37)){ // display previous image
			if(opts.activeImage != 0){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){ // display next image
			if(opts.activeImage != (opts.imageArray.length - 1)){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage + 1);
			}
		}
	};

	$.fn.lightbox.resizeImageContainer = function(imgWidth, imgHeight){
		// get current width and height
		opts.widthCurrent = document.getElementById('outerImageContainer').offsetWidth;
		opts.heightCurrent = document.getElementById('outerImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (opts.borderSize * 2));
		var heightNew = (imgHeight  + (opts.borderSize * 2));

		// scalars based on change from old to new
		opts.xScale = ( widthNew / opts.widthCurrent) * 100;
		opts.yScale = ( heightNew / opts.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = opts.widthCurrent - widthNew;
		hDiff = opts.heightCurrent - heightNew;

		$('#imageDataContainer').animate({width: widthNew},opts.resizeSpeed,'linear');
		$('#outerImageContainer').animate({width: widthNew},opts.resizeSpeed,'linear',function(){
			$('#outerImageContainer').animate({height: heightNew},opts.resizeSpeed,'linear',function(){
				$.fn.lightbox.showImage();
			});
		});


		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (jQuery.browser.msie){ $.fn.lightbox.pause(250); } else { $.fn.lightbox.pause(100);}
		}

		$('#prevLink').height(imgHeight);
		$('#nextLink').height(imgHeight);
	};

	$.fn.lightbox.showImage = function(){
		$('#loading').hide();
		$('#lightboxImage').fadeIn("fast");
		$.fn.lightbox.updateDetails();
		$.fn.lightbox.preloadNeighborImages();

		opts.inprogress = false;
	};

	$.fn.lightbox.updateDetails = function(){

		if(opts.imageArray[opts.activeImage][1]){
			$('#caption').html(opts.imageArray[opts.activeImage][1]).show();
		}

		// if image is part of set display 'Image x of x'
		if(opts.imageArray.length > 1){
			var nav_html;

			nav_html = opts.strings.image + (opts.activeImage + 1) + opts.strings.of + opts.imageArray.length;

			// display previous / next text links
			if ((opts.activeImage) > 0) {
				nav_html = '<a title="' + opts.strings.prevLinkTitle + '" href="#" id="prevLinkText">' + opts.strings.prevLinkText + "</a>" + nav_html;
			}

			if ((opts.activeImage + 1) < opts.imageArray.length) {
				nav_html += '<a title="' + opts.strings.nextLinkTitle + '" href="#" id="nextLinkText">' + opts.strings.nextLinkText + "</a>";
			}

			$('#numberDisplay').html(nav_html).show();
		}

		if (opts.slideNavBar) {
		    $("#imageData").slideDown(opts.navBarSlideSpeed);
		} else {
			$("#imageData").show();
		}

		var arrayPageSize = $.fn.lightbox.getPageSize();
		$('#overlay').height(arrayPageSize[1]);
		$.fn.lightbox.updateNav();
	};

	$.fn.lightbox.updateNav = function(){
		$('#hoverNav').show();

		// if not first image in set, display prev image button
		if(opts.activeImage != 0){
			$('#prevLink,#prevLinkText').show().click(function(){
				$.fn.lightbox.changeImage(opts.activeImage - 1); return false;
			});
		}

		// if not last image in set, display next image button
		if(opts.activeImage != (opts.imageArray.length - 1)){
			$('#nextLink,#nextLinkText').show().click(function(){

				$.fn.lightbox.changeImage(opts.activeImage +1); return false;
			});
		}

		$.fn.lightbox.enableKeyboardNav();
	};


	$.fn.lightbox.enableKeyboardNav = function(){
		document.onkeydown = $.fn.lightbox.keyboardAction;
	};

	$.fn.lightbox.disableKeyboardNav = function(){
		document.onkeydown = '';
	};

	$.fn.lightbox.defaults = {
		fileLoadingImage : url_base+'css/images/loading.gif',
		fileBottomNavCloseImage : url_base+'css/images/closelabel.gif',
		overlayOpacity : 0.8,
		borderSize : 10,
		imageArray : new Array,
		activeImage : null,
		inprogress : false,
		resizeSpeed : 350,
		widthCurrent: 250,
		heightCurrent: 250,
		xScale : 1,
		yScale : 1,
		displayTitle: true,
		navbarOnTop: false,
		slideNavBar: false, // slide nav bar up/down between image resizing transitions
		navBarSlideSpeed: 350,
		displayHelp: false,
		strings : {
			help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
			prevLinkTitle: var_prevLinkTitle,
			nextLinkTitle: var_nextLinkTitle,
			prevLinkText:  var_prevLinkText,
			nextLinkText:  var_nextLinkText,
			closeTitle: var_closeTitle,
			image: var_image,
			of: var_of
		},
		fitToScreen: false		// resize images if they are bigger than window
	};
})(jQuery);

/* onLoad */
$(document).ready(function(){
	$(".lightbox").lightbox();
	
	$index=0;
	$('ul.controls-wrapper li:first a').addClass('active');
	$('ul.controls-wrapper li').bind('click', function(){
		$index = $('ul.controls-wrapper li').index(this);
		
		$(this).parent().find('a.active').removeClass('active');
		$(this).find('a').addClass('active');
		
		$('div.body').scrollTo( $('div.bigpreview div:eq('+$index+')'), 810 );
	});

	// auto scroll
	$(document).everyTime(3500, function() {
		if( $index==$('ul.controls-wrapper li').size() ){
			$index=0;
		} else {
			$('ul.controls-wrapper li:eq('+  $index  +')').trigger('click');
			$index++;
		}
	});

	$('a.login').bind('click', function(){
		$('#login-menu').animate({top: "0px"}, 500);
	});
	$('#login-menu').bind('mouseleave', function(){
		if(mouselv == 1){
			$(this).delay(500).animate({top: "-158px"}, 500);
		}
	});
	$('#login-menu input').focus(function(){mouselv=0;});
	$('#login-menu input').blur(function(){mouselv=1;});

	$('#add_to_cart, .add_to_cart').bind('click', function(){
		ready_to_add = 0;
		if(materiale > 0 && $('#material').val()!=""){
			ready_to_add = 1;
		}else if(materiale == 0){
			ready_to_add = 1;
		}
		
		if(ready_to_add == 1){
			ids = $(this).attr('rel').split("-");
			params = "add=1&id="+ids[0]+"&pret="+ids[1];
			rel = "im"+ids[0];
			if(ids[1]!=undefined){
				rel += "-"+ids[1];
			}
			if($('#material').val()!="" && $('#material').val()!=undefined){
				rel += "-"+$('#material').val();
				params += "&mat="+$('#material').val();
			}
			
			$.ajax({
				type: "GET",
				url: url_base+"addtocart.php",
				data: params,
				async: false,
				success: function(html) {
					$.scrollTo( 0, 100 );
					$('a.login').trigger('click');
					$('#big-pic img.image').eq(0)
						.clone()
						.css({position:'absolute', left:210, zIndex:25})
						.appendTo('#big-pic')
						.delay(650)
						.animate({top:-60, left:430, opacity:.3, height:40, width:40}, 500, function(){
							$('.cart-nr').css("font-weight", "bold").html(parseInt($('.cart-nr').html())+1);
							if($("#"+rel).length != 0){
								$("#"+rel+" span").html(parseInt($("#"+rel+" span").html())+1);
								$(this).remove();
								$('#login-menu').delay(2500).trigger('mouseleave');
							}else{
								$anchor = $('<a href="'+url_base+'cosul-de-cumparaturi/" title="Cosul de cumparaturi" id="'+rel+'" rel="nofollow"></a>');
								$span = $("<span>1</span>");
								$anchor.prependTo('#shop-cart div').html($(this));
								$span.appendTo($anchor);
								$(this).attr('src', $(this).attr('src').replace('prod/', 'prod/thumb2/'))
									.attr('width', '40').attr('height', '40')
									.css({position:'', top:'', left:'', float:'left', height:40, width:40})
									.animate({opacity:1}, 400, function(){
										$('#login-menu').delay(2500).trigger('mouseleave');
									});
							}					
					});
				}
			});
		}else{
			alert("Pentru a putea adauga produsul in cos trebuie sa selectati unul din materialele afisate in partea stanga!");
		}
	});

	$('#login-status').bind('click', function(){
		$('#login-status').css({display:'block'}).animate({opacity:0}, 300, function(){$('#login-form form').animate({opacity:1}, 500);}).attr('style','');
	});

	//ajax newsletter subscriber
	var nform = $('#newsletter form');
	var submit = $('#ns-submit');
	var input = $('#ns-email');
	var action = $('#ns-action').val();
	submit.click(function(){
		email = input.val();
		$.ajax({
			url: url_base+'ajax/',
			type: 'post',
			data: 'ajax=1&newsletter=1&email='+email+'&action=1',
			beforeSend: function(){
				input.addClass('loading');
			},
			success: function(responseText){
				//to eval json expressions add paranthesis: '('+responseText+')'
				input.removeClass('loading');
				response = eval("("+responseText+")");
				if(response.error) {input.removeClass('success').addClass('error');}
				if(response.success) {input.removeClass('error').addClass('success');nform.find('input').attr('disabled','disabled')}
				input.val("");
				$('#response').html("<b>"+response.message+"</b>");
			}
		});
	});
});

function loguser(){
	if($('#username').val()!="" && $('#password').val()!=""){
		$.ajax ({
			url: url_base+'login.php',
			type: 'POST',
			cache: false,
			dataType: 'html',
			data: 'user='+$('#username').val()+'&pass='+$('#password').val(),
			beforeSend :function(){
				$('#login-status p').html('Va rugam asteptati!');
				$('#login-form form').animate({opacity:.1}, 300, function(){$('#login-status').css({opacity:0,display:'block'}).animate({opacity:1}, 500);});
			},
			success: function(responseText){
				if(responseText == "ok") {
					$('#login-status').css({display:'none'}).animate({opacity:0}, 300, function(){$('#login-form form').animate({opacity:0}, 500);});
					document.location = url_base + 'trimite-comanda/';
				} else {
					$('#login-status p').html(responseText).parent().addClass('error');
				}
				
			}
		});
	}else{
		alert("Scrieti username-ul si parola!");
		$('#username').focus();
		mouselv = 0;
	}
}
