var liwe={};liwe.utils={};liwe.fx={};liwe.strong_debug=false;liwe._libbase="";liwe.ajax_url="/ajax.php";if(!window.console){window.console={}}try{liwe._console=window.console.debug}catch(e){liwe._console=null}if(!liwe._console){var names=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];for(var i=0;i<names.length;++i){if(!window.console[names[i]]){window.console[names[i]]=function(){}}}}liwe.set_libbase=function(c){if(c){liwe._libbase=c;return}var a=document.getElementsByTagName("script");var b=a.length;var d,f,h,g="";for(d=0;d<b;d++){f=a[d].src;if(!f){continue}if(f.match(/liwe.*js/)){f=f.replace(/.*os3phplib.send_gzip.php.fname=/,"");h=f.lastIndexOf("/");if(h!=-1){g=f.slice(0,h+1)}}}if(g){liwe._libbase=g}else{liwe._libbase="/os3jslib"}};liwe.set_libbase();liwe.utils.WAIT_TIMEOUT=2000;liwe.utils.WAIT_TIME=50;liwe.utils.wait_def=function(b,a,d,c){if(!liwe.utils.is_def(b)){if(!c){c=0}if(c>liwe.utils.WAIT_TIMEOUT){if(liwe.strong_debug){alert("Failed: "+b)}return}setTimeout(function(){liwe.utils.wait_def(b,a,d,c+liwe.utils.WAIT_TIME)},liwe.utils.WAIT_TIME)}else{if(typeof(a)!="object"){a(d)}}};liwe.utils.append_js=function(a){var b=document.getElementsByTagName("head")[0];var c=document.createElement("script");c.src=a;c.type="text/javascript";b.appendChild(c)};liwe.utils.is_def=function(name){var is_def=false;var l;if(typeof name=="string"){var items=name.split(".");var s="";s=items[0];l=items.length;for(t=0;t<l;t++){eval("is_def = ( typeof ( "+s+" ) != 'undefined' );");if(!is_def){return false}if(!items[t+1]){break}s+="."+items[t+1]}return true}var t;var n;l=name.length;for(t=0;t<l;t++){n=name[t];eval("is_def = ( typeof ( "+n+" ) != 'undefined' );");if(!is_def){return false}}return true};liwe.browser={};liwe.browser.version=navigator.appVersion;liwe.browser.has_dom=document.getElementById?1:0;liwe.browser.ie=(typeof window.ActiveXObject!="undefined");liwe.browser.gecko=(navigator.userAgent.toLowerCase().indexOf("gecko")!=-1)?1:0;liwe.browser.opera=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1)?1:0;liwe.postload={};liwe.postload.WAIT_TIMEOUT=30000;liwe.postload.WAIT_TIME=50;liwe.postload.events={};liwe.postload.events.script_load=null;liwe.postload.events.update=null;liwe.postload.events.completed=null;liwe.postload._files=[];liwe.postload._loaded_files=0;liwe.postload.add=function(f,c,b,a,d){if(!b){b=1}if(liwe.utils.is_def(c)){return}liwe.postload._files.push([b,f,c,a,d,0])};liwe.postload.load=function(){var b,a,c;liwe.postload._files.sort();a=liwe.postload._files.length;liwe.postload._loaded_files=0;for(b=0;b<a;b++){c=liwe.postload._files[b];if(c[5]){liwe.postload._loaded(b)}liwe.utils.append_js(c[1]);liwe.utils.wait_def(c[2],liwe.postload._loaded,b)}};liwe.postload._loaded=function(b){liwe.postload._loaded_files+=1;var a=liwe.postload._files[b];a[5]=1;if(liwe.postload.events.script_loaded){liwe.postload.events.script_loaded(a[1])}if(a[3]){a[3](a[4])}if(liwe.postload.events.update){liwe.postload.events.update(liwe.postload._loaded_files,liwe.postload._files.length)}if(!(liwe.postload._files.length-liwe.postload._loaded_files)){if(liwe.postload.events.completed){liwe.postload.events.completed()}}};liwe._clear_dom=function(j){var g,c=j.childNodes.length;for(g=0;g<c;g++){var a=j.childNodes[g];var m;for(m in a){if(m.charAt(0)!="_"){continue}console.debug(m);if(m=="_listeners"){var k=[].concat(a[m]);var f,b=k.length;for(f=0;f<b;f++){var h=k[f];var d=_all[h];if(d){liwe.events.del(d.target,d.type,d.listener)}}}try{a[m]=null}catch(j){}}liwe._clear_dom(a)}};function $(b,a,d){if(!b){return null}var c=document.getElementById(b);if(!c){if(d){console.warn("Element: %s not found",b)}return null}if(typeof a=="undefined"){return c}c.innerHTML=a;return c}function $v(b,a){var c=document.getElementById(b);if(!c){return a}if((c.type=="select")||(c.type=="select-one")){return c.options[c.selectedIndex].value}return c.value};Object.prototype.iterate=function(b){var a;for(a in this){if(typeof(this[a])=="function"){continue}b(this[a],a)}};Object.prototype.keys=function(){var a=[];this.iterate(function(c,b){a.push(b)});return a};Object.prototype.values=function(){var a=[];this.iterate(function(b){a.push(b)});return a};Object.prototype.debugDump=function(d,b){var c="";var a;if(!b){b=""}for(a in this){if(typeof(this[a])=="function"){if(d){c+=b+"function "+a+" ()\n"}}else{if(typeof(this[a])=="object"){c+=b+a+":\n"+this[a].debugDump(d,b+"-----  ")}else{c+=b+a+": "+this[a]+"\n"}}}return c};Object.prototype.count=function(){var a;var b=0;for(a in this){if((typeof(this[a])=="function")){continue}b++}return b};Object.prototype.get=function(b,a){var c=this[b];if(typeof(c)=="undefined"){return a}return c};Object.prototype.getName=function(){if(this.name){return this.name}var b=""+this;var a=b.match(/^function  *([_a-zA-Z$][_a-zA-Z0-9$]*)  *.*/);if(!a){return""}return a[1]};Object.prototype.inherits=function(b){var a;this.parent=b;for(a in b){if(typeof this[a]=="undefined"){this[a]=b[a]}}};Object.prototype.clone=function(){var b={};var a;for(a in this){b[a]=this[a]}return b};Array.prototype.toSourceString=function(d){var e="{";var b,a;var c=true;for(b in this){if((typeof(this[b])=="function")&&(!d)){continue}if(!c){e+=", "}e+="'"+b+"' : '"+this[b]+"'";c=false}e+="}";return e};Array.prototype.count=function(){var a;var b=0;for(a in this){if((typeof(this[a])=="function")){continue}if(a=="__arr"){continue}b++}return b};Array.fromObject=function(c,f){var b=new Array();var e,d;for(e in c){if((!f)&&(typeof(c[e])=="function")){continue}b[e]=c[e]}return b};Array.fromForm=function(c,b){var a=new Array();var d=document.getElementById(c);if(!b){b=0}_form_add_elems(d,a,b,0);return a};Object.fromForm=function(c,b){var a={};var d=document.getElementById(c);if(!b){b=0}_form_add_elems(d,a,b,0);return a};Array.prototype.find=function(e,b,d){var a;var f=0;if(!b){e=e.toLowerCase()}for(a in this){if((typeof(this[a])=="function")&&(!d)){continue}a=this[a];if(!b){a=a.toLowerCase()}if(a==e){return f}f++}return -1};Array.toObject=function(a){var c={};var b;for(b in a){if((typeof(a[b])=="function")){continue}c[b]=a[b]}return c};Array.prototype.del=function(h,a){if(!a){a=1}var e=Array();var g=h;var d=h+a;var b,f=-1,c;for(b in this){f++;if(f<g){continue}else{if(f>=d){break}}e.push(b)}for(c=0;c<e.length;c++){delete this[e[c]]}};Array.prototype.delKey=function(a){delete this[a]};if(Array.prototype.indexOf==null){Array.prototype.indexOf=function(c){var b,a=this.length;for(b=0;b<a;b++){if(this[b]==c){return b}}return -1}}function _form_add_elems(c,g,d,b){var h,e,f,i,a;h=c.getElementsByTagName("input");e=c.getElementsByTagName("select");f=c.getElementsByTagName("textarea");for(i=0;i<h.length;i++){a=h[i];if(((a.type=="radio")||(a.type=="checkbox"))&&(a.checked==false)){continue}g[a.name]=a.value}for(i=0;i<e.length;i++){g[e[i].name]=e[i].value}for(i=0;i<f.length;i++){g[f[i].name]=f[i].value}}if(Array.prototype.push==null){Array.prototype.push=function(){for(var a=0;a<arguments.length;a++){this[this.length]=arguments[a]}return this.length}};String.prototype.startsWith=function(a){if(this.substr(0,a.length)==a){return(true)}return(false)};String.prototype.endsWith=function(a){if(this.substr(this.length-a.length)==a){return(true)}return(false)};String.buffer=function(){this._buf=[];this.add=function(){var b,a=arguments.length;for(b=0;b<a;b++){if(arguments[b]&&arguments[b].length){this._buf.push(arguments[b])}}return this};this.get=function(a){if(!a){a=""}return this._buf.join(a)};this.length=function(){return this._buf.length};this.clear=function(){this._buf=[]};this.toString=function(){return this.get("")}};String._re_htmlentities_invalid=/([^a-zA-Z0-9,.:;=!?+\/_ |@-\\(\\)<>\n\r'"&#{}-][$])/g;String.prototype.htmlEntities=function(){function a(b){return("&#"+b.charCodeAt(0)+";")}return this.replace(String._re_htmlentities_invalid,a)};String._re_entities_decl=/&#([^;]*);/g;String.prototype.entities2char=function(){function a(b,c){return String.fromCharCode(parseInt(c,10))}return this.replace(String._re_entities_decl,a)};String.prototype.join=function(a){var b=a.length;var c,e;var f="";var d=true;for(e=0;e<b;e++){if(typeof(a[e])=="function"){continue}if(!d){f+=this}f+=a[e];d=false}return f};String.prototype.LStrip=function(){return this.replace(/^\s+/,"")};String.prototype.RStrip=function(){return this.replace(/\s+$/,"")};String.prototype.Strip=function(){return this.replace(/^\s+|\s+$/,"")};String.prototype.isUpper=function(){var a=this.length;var d,b;if(!a){return false}for(b=0;b<a;b++){d=this[b].toUpperCase();if(d!=this[b]){return false}}return true};String.prototype.isLower=function(){var a=this.length;var d,b;if(!a){return false}for(b=0;b<a;b++){d=this[b].toLowerCase();if(d!=this[b]){return false}}return true};String.basename=function(b,a){if(!a){a="/"}return b.split(a).slice(-1)};String.dirname=function(b,a){if(!a){a="/"}return a.join((b.split(a)).slice(0,-1))};String.format=function(){function d(h){var g=h.match(a);var i=c[++f];return _string_re_replace(g,i)}var a=/%([0+#-]*)([0-9]*)(\.{0,1})([0-9]*)([dsqm])/;var e=/%[0+#-]*[0-9]*\.{0,1}[0-9]*[dsqm]/gi;var b=arguments[0];var f=0;var c=arguments;return b.replace(e,d)};String.formatDict=function(b,e){function c(g){var f=g.match(a);var h=f[1];var j=e.get(h,undefined);var i=f.shift();if(j===undefined){console.warn("Missing parameter: %s info: %o",h,{format:b,dict:e});j=""}f.shift();f.unshift(i);return _string_re_replace(f,j)}var a=/%\(([^)]*)\)([0+#-]*)([0-9]*)(\.{0,1})([0-9]*)([dsqm])/;var d=/%\([a-z0-9_-]+\)[0+#-]?[0-9]*\.?[0-9]*[dsqm]/gi;if(b==""){return""}if(!b){console.warn("No FMT for the following dict: %o",e);return""}return b.replace(d,c)};function _string_re_replace(e,i){var d=e[1];var b=(e[2]?parseInt(e[2]):0);var f=(e[4]?parseInt(e[4]):0);var h=e[5];var g="";var a=" ";var c=false;var j=false;if(d.indexOf("-")>=0){c=true}if(d.indexOf("0")>=0){a="0"}if(d.indexOf("+")>=0){j=true}if(a=="0"&&c){a=" "}switch(h){case"m":if(typeof(Money)!="undefined"){g=Money.fromLongInt(i)}else{g=i}break;case"d":g=_string_mkpad(true,i,f,b,a,false,c,j);break;case"q":i=i.replace(/'/g,"\\'");case"s":g=_string_mkpad(false,i,f,b,a,true,c,false);break}return g}function _string_mkpad(l,j,d,c,b,a,f,k){var e="";if(l){j=parseInt(j);if(j<0){e="-"}else{if(k){e="+"}}j=Math.abs(j)}j=String(j);if(!c&&!d){return j}var h,m,g;if(l){h=d-j.length;if(h>0){for(m=0;m<h;m++){j="0"+j}}}j=e+j;h=c-j.length;if(h>0){for(m=0;m<h;m++){j=(f?j+b:b+j)}}if(!l&&d){return j.slice(0,d)}return j};function AJAXManager(){this._reqs=[];this._in_list=0;this._in_abort=false;this.url=liwe.ajax_url;this.cbacks={serialize:null,"req-start":null,"req-end":null,"req-error":null};this.request=function(a,i,l,d,j){var k=null;var b="";var n;var h="";var m=this;var o;if(!a){a=this.url}if(i){for(n in i){if(typeof(i[n])=="undefined"){continue}if(typeof(i[n])=="function"){continue}if((typeof(i[n])=="object")&&(i[n]==null)){continue}if(typeof(i[n])=="object"){o=i[n].toString();if(o.match(/^function/)){continue}}if(i[n]=="__arr"){continue}if((typeof(i[n])=="string")||(typeof(i[n])=="number")){h+=n+"="+this._ajax_escape(i[n])+"&"}else{try{h+=n+"="+this._ajax_escape(i[n].toJSONString())+"&"}catch(f){h+=n+"="+this._ajax_escape(i[n])+"&"}}}h=h.substr(0,h.length-1)}k=this._build_req_obj();var g=this;if(this.error_handler){console.warn("AJAXManager.error_handler is DEPRECATED. Use cbacks [ 'req-error' ] instead.");k.onreadystatechange=function(){g._req_change(k,l,d,g.error_handler)}}else{k.onreadystatechange=function(){g._req_change(k,l,d,g.cbacks["req-error"])}}var c=true;if(j){c=false}a=a.replace(/^\/\//g,"/");k.open("POST",a,c);k.setRequestHeader("Content-Type","application/x-www-form-urlencoded");k.send(h);if(d){if(this.start_req_handler){console.warn("AJAXManager.start_req_handler is DEPRECATED. Use cbacks [ 'req-start' ] instead.");this.start_req_handler(k)}if(this.cbacks["req-start"]){this.cbacks["req-start"](k)}}};this.easy=function(a,b){this.request(null,a,b,true)};this._build_req_obj=function(){var a;if(!a&&typeof XMLHttpRequest!="undefined"){try{a=new XMLHttpRequest()}catch(b){a=false}}if(!a&&window.createRequest){try{a=window.createRequest()}catch(b){a=false}}this._reqs.push(a);return a};this._req_change=function(d,e,b,c){if(!b){if(e){e(d)}}else{var a=this._in_abort;if(d.readyState==4){if(this.end_req_handler){console.warn("AJAXManager.end_req_handler is DEPRECATED. Use cbacks [ 'req-end' ] instead.");this.end_req_handler(d)}if(this.cbacks["req-end"]){this.cbacks["req-end"](d)}this._remove_req(d);if(a){return}AJAXManager.handle_easy(d.responseText,e,c)}}};this.error_handler=null;this.start_req_handler=null;this.end_req_handler=null;this._remove_req=function(c){var b,a=this._reqs.length;if(this._in_list){var d=this;setTimeout(function(){d._remove_req(c)},100);return}this._in_list=1;for(b=0;b<a;b++){if(this._reqs[b]==c){break}}if(b<a){this._reqs.splice(b,1)}this._in_list=0};this.abort=function(b){var c,a=this._reqs.length;if(this._in_list){var f=this;setTimeout(function(){f.abort()},100);return}this._in_list=2;this._in_abort=true;for(c=0;c<a;c++){try{this._reqs[c].abort()}catch(d){}}this._in_abort=false;this._in_list=0;if(b){b()}};this._ajax_escape=function(a){if(this.cbacks.serialize){a=this.cbacks.serialize(a)}a=escape(a);a=a.replace(/\+/g,"%2B");return a}}AJAXManager.handle_easy=function(responseText,callback,err_handler){var resp_txt=responseText.replace(/^\s+/,"");if(resp_txt.substr(0,"var ajax".length)=="var ajax"){try{eval(resp_txt);if(ajax_response.err_code){if(!err_handler){if(ajax_response.err_descr){console.error(ajax_response.err_descr);alert(ajax_response.err_descr)}else{console.error("Generic Request error. Error code: "+ajax_response.err_code)}}else{err_handler(responseText,ajax_response.err_descr,ajax_response.err_code)}return}if(callback&&typeof(callback)=="function"){callback(ajax_response)}}catch(e){if(err_handler){err_handler(responseText)}console.error("ERROR IN EVAL: %s - (except: %o)",responseText,e);return}}else{if(err_handler){err_handler(responseText)}console.error("Request ERROR: "+responseText)}};liwe.AJAX=new AJAXManager();liwe.AJAX._multi={};liwe.AJAX._multi_data={};liwe.AJAX.add=function(b,d,f,a){var e;var c;if(!b){b="AJAX"}if(!d){d=null}e=this._multi[b];if(!e){e=[];c={}}else{c=this._multi_data[b]}if(c.running){console.error("Requests are already running for: %s",b);return}e.push([d,f,a]);this._multi[b]=e;this._multi_data[b]=c;console.debug("Multi: %s - Len: %d",b,e.length)};liwe.AJAX.start=function(a,h){var f,e,j,c,g,b;f=this._multi[a];if(!f){console.error("There is no multi group called: %s",a);return}e=this._multi_data[a];e.running=true;e.len=f.length;e.count=0;c=f.length;var d;for(j=0;j<c;j++){g=f[j];liwe.AJAX._send(a,g,h)}};liwe.AJAX._send=function(b,c,a){this.request(c[0],c[1],function(d){liwe.AJAX._req_cback(b,d,c,a)},true)};liwe.AJAX._req_cback=function(c,b,d,a){var f=liwe.AJAX._multi[c];var e=liwe.AJAX._multi_data[c];if(d[2]){d[2](b)}e.count+=1;if(e.count==e.len){if(a){a()}liwe.AJAX._multi[c]=null;liwe.AJAX._multi_data[c]=null}};liwe.history={};liwe.history.listener_callback={};liwe.history.cbacks={"before-add":null,"before-module":null};liwe.history._load=function(){liwe.history._is_ie=(document.all&&navigator.userAgent.toLowerCase().indexOf("msie")!=-1);liwe.history._blank_page=liwe._libbase+"/data/history_blank.html";liwe.history._data_storage=[];if(liwe.history._is_ie){liwe.history._int_create_iframe()}document.write('<form style="display: none;"><input id="historyDataText" type="text" value="" /></form>')};liwe.history.init=function(){liwe.history._saved_location=liwe.history.get_current_location();setInterval(liwe.history._int_check_location,100);setTimeout(liwe.history._init_done,200)};liwe.history._init_done=function(){var a=document.getElementById("historyDataText");if(a.value){liwe.history._data_storage=a.value.parseJSON()}liwe.history._int_call_listener()};liwe.history._int_create_iframe=function(){var a=liwe.history.get_current_location();liwe.history._adding=true;document.write("<iframe style='border: 2px; width: 1px; height: 1px; position: absolute; bottom: 0px; right: 0px; display: none;' name='liwe.historyFrame' id='liwe.historyFrame' src='"+liwe.history._blank_page+"?"+a+"'></iframe>");liwe.history._iframe=document.getElementById("liwe.historyFrame");window._os3_history_cb=liwe.history._int_iframe_location_changed};liwe.history.get_current_location=function(){var a=window.location.hash;if(a.length>0&&a.charAt(0)=="#"){a=a.slice(1)}return a};liwe.history.get_current_obj=function(){var e=liwe.history.get_current_location().split(",");var c,a=e.length;var b={},d;for(c=0;c<a;c++){d=e[c].split("=");b[d[0]]=d[1]}return b};liwe.history._int_call_listener=function(){if(!liwe.history.listener_callback){return}var e=liwe.history.get_current_location();var d=liwe.history._str2dict(e);var c,b;if(typeof d.__dk!="undefined"){var a=parseInt(d.__dk);c=liwe.history._data_storage[a];delete d.__dk}if(typeof d.__m!="undefined"){b=d.__m}else{b="__DEFAULT__"}if(!liwe.history.listener_callback[b]){return}liwe.history._listener_call=true;try{liwe.history.listener_callback[b](d,c)}finally{liwe.history._listener_call=false}};liwe.history.set_listener=function(b,a){if(!a){a="__DEFAULT__"}liwe.history.listener_callback[a]=b};liwe.history.add=function(b,a){return liwe.history.add_module(null,b,a)};liwe.history.add_module=function(b,h,e){if(!h){h={}}if(liwe.history._listener_call){return}if(h.get("__nh")==1){return}if(liwe.history.cbacks["before-add"]){var f=liwe.history.cbacks["before-add"](b,h,e);if(f){return}}if(e){var a=liwe.history._data_storage.length.toString();liwe.history._data_storage.push(e);h.__dk=a;var c=liwe.history._data_storage.toJSONString();var d=document.getElementById("historyDataText");d.value=c}if(b){h.__m=b}var g=liwe.history._dict2str(h);window.location.hash=g;liwe.history._saved_location=g;if(liwe.history._is_ie){liwe.history._adding=true;liwe.history._iframe.src=liwe.history._blank_page+"?"+g}};liwe.history.replace=function(b,h,e){if(liwe.history._listener_call){return}if(h.get("__nh")==1){return}var a=(liwe.history._data_storage.length-1).toString();liwe.history._data_storage[liwe.history._data_storage.length-1]=e;h.__dk=a;var c=liwe.history._data_storage.toJSONString();var d=document.getElementById("historyDataText");d.value=c;if(b){h.__m=b}var f=String(location).split("#")[0];var g=liwe.history._dict2str(h);window.location.replace(f+"#"+g);liwe.history._saved_location=g;if(liwe.history._is_ie){liwe.history._adding=true;liwe.history._iframe.src=liwe.history._blank_page+"?"+g}};liwe.history._dict2str=function(e){var d="";var c=true;var b,a;for(b in e){a=e[b];if(typeof(a)=="function"){continue}if(c){c=false}else{d+=","}d+=b;if(a!=null&&a!=undefined){a=a.toString();d+="="+liwe.history._escape_value(a)}}return d};liwe.history._str2dict=function(d){var c;var g={};d=liwe.history._lstrip(d);while(d.length>0){var f=d.indexOf(",");while(f<d.length-1&&d.charAt(f+1)==","){f=d.indexOf(",",f+2)}if(f==-1){c=d;d=""}else{c=d.slice(0,f);d=d.slice(f+1);d=liwe.history._lstrip(d)}var e=c.split("=");var b=e[0];var a=liwe.history._join("=",e.slice(1));a=a.replace(",,",",");g[b]=unescape(a)}return g};liwe.history._escape_value=function(a){return a.replace(",",",,")};liwe.history._lstrip=function(a){while(a.length>0&&a.charAt(0)==" "){a=a.slice(1)}return a};liwe.history._join=function(c,a){var b=a.length;if(b==0){return""}var e=a[0];for(var d=1;d<b;d++){e+=c+a[d]}return e};liwe.history._int_iframe_location_changed=function(a){if(liwe.history._adding){liwe.history._adding=false;return}if(a.length>0&&a.charAt(0)=="?"){a=a.slice(1)}window.location.hash=a;liwe.history._saved_location=a;liwe.history._int_call_listener()};liwe.history._int_check_location=function(){var a=liwe.history.get_current_location();if(a==liwe.history._saved_location){return}liwe.history._saved_location=a;if(liwe.history._is_ie){liwe.history._iframe.src=liwe.history._blank_page+"?"+a}else{liwe.history._int_call_listener()}};liwe.history._load();liwe.module=function(a,c){function d(f,g){var e=this;this.module_name=f;this._events={};this._dest_div="block_main";this.cbacks={};this.history_cbacks=g;this.event_dispatch=function(k,j){console.debug(this);console.debug(this._events);var i=k.get("_page");var h=this._events.get(i);if(liwe.history.cbacks["before-module"]){liwe.history.cbacks["before-module"](this.module_name,k,j)}if(!h){if(this.history_cbacks&&(h=this.history_cbacks[i])){h=this[h]}else{console.warn("Module: %s - Event: %s not handled",this.module_name,i);return}}h(k,j)};this.set_history=function(i,h,j){if(typeof(h)=="string"){h=this[h]}this._events[i]=h;if(!j){j={}}j._page=i;liwe.history.add_module(this.module_name,j)};this.init=function(){};this.ajax=function(i,j,k,h){var l=this;if(typeof h=="undefined"){h=true}else{h=false}if(typeof k=="undefined"){k=null}if(typeof j=="undefined"){j=function(m){console.debug("Module: %s - Result: %o",l.module_name,m)}}liwe.AJAX.request(k,i,j,h)};e.templates=null;e._templates_loading=false;this.load_templates=function(h){if(e._templates_loading){console.debug("Templates for: %s already loading ...",e.module_name);setTimeout(function(){e.load_templates(h)},200);return}e._templates_loading=true;if(!e.templates){e.ajax({action:e.module_name+".ajax.get_templates"},function(i){e.templates=i.templates;if(h){h()}})}else{if(h){h()}}e._templates_loading=false};this.get_admin_actions=function(){return this._actions};this.register=function(h){this._actions=h;if(typeof(system)!="undefined"&&typeof(system.admin)!="undefined"){system.admin.module_register(this);return true}console.error("ERROR: could not register %s - module system not found",this.module_name);return false};this.set_dest_div=function(h){this._dest_div=h}}var b=new d(a,c);if(liwe.history){liwe.history.set_listener(function(f,e){b.event_dispatch(f,e)},a)}return b};liwe.locale={};liwe.locale.words={};liwe.locale.set=function(b,a){liwe.locale.words[b]=a};function _(c,b){var a=liwe.locale.words.get(c,Array());return a.get(b,b)};liwe.events={};if(document.addEventListener){liwe.events.add=function(c,a,b){c.addEventListener(a,b,false);return c};liwe.events.del=function(c,a,b){c.removeEventListener(a,b,false)};liwe.events.prevent=function(a){a.preventDefault()};liwe.events.stop=function(a){a.stopPropagation()};liwe.events.source=function(a){return a.target};liwe.events.keycode=function(a){return a.which}}else{if(document.attachEvent){liwe.events.add=function(g,b,e){if(liwe.events._find(g,b,e)!=-1){return}var f=function(){var i=window.event;if(Function.prototype.call){e.call(g,i)}else{g._curr_listener=e;g._curr_listener(i);g._curr_listener=null}};g.attachEvent("on"+b,f);var h={target:g,type:b,listener:e,_cback:f};var d=g.document||g;var c=d.parentWindow;var a="l"+liwe.events._list_counter++;if(!c._all){c._all={}}c._all[a]=h;if(!g._listeners){g._listeners=[]}g._listeners[g._listeners.length]=a;if(!c._unload_added){c._unload_added=true;c.attachEvent("onunload",liwe.events._del_all)}return g};liwe.events.del=function(g,c,f){var a=liwe.events._find(g,c,f);if(a==-1){return}var e=g.document||g;var d=e.parentWindow;var b=g._listeners[a];var h=d._all[b];g.detachEvent("on"+c,h._cback);g._listeners.splice(a,1);delete d._all[b]};liwe.events.prevent=function(a){a.returnValue=false};liwe.events.stop=function(a){a.cancelBubble=true};liwe.events.source=function(a){return event.srcElement};liwe.events.keycode=function(a){return event.keyCode};liwe.events._find=function(f,h,a){var j=f._listeners;if(!j){return -1}var g=f.document||f;var b=g.parentWindow;for(var e=j.length-1;e>=0;e--){var c=j[e];var d=b._all[c];if(d.type==h&&d.listener==a){return e}}return -1};liwe.events._del_all=function(){var a=this;for(id in a._all){var b=a._all[id];if(typeof(b)=="function"){continue}b.target.detachEvent("on"+b.type,b._cback);delete a._all[id]}};liwe.events._list_counter=0}}function $e(d,c,a){var b=d;if(typeof(d).toLowerCase()=="string"){b=$(d)}return liwe.events.add(b,c,a)}liwe.events.once=function(d,c,a){var b=function(f){a(f);liwe.events.del(d,c,b)};liwe.events.add(d,c,b)};if(!Object.prototype.toJSONString){Array.prototype.toJSONString=function(){var e=["["],c,g,d=this.length,f;function h(a){if(c){e.push(",")}e.push(a);c=true}for(g=0;g<d;g+=1){f=this[g];switch(typeof f){case"undefined":case"function":case"unknown":break;case"object":if(f){if(typeof f.toJSONString==="function"){h(f.toJSONString())}}else{h("null")}break;default:h(f.toJSONString())}}e.push("]");return e.join("")};Boolean.prototype.toJSONString=function(){return String(this)};Date.prototype.toJSONString=function(){function a(b){return b<10?"0"+b:b}return'"'+this.getFullYear()+"-"+a(this.getMonth()+1)+"-"+a(this.getDate())+"T"+a(this.getHours())+":"+a(this.getMinutes())+":"+a(this.getSeconds())+'"'};Number.prototype.toJSONString=function(){return isFinite(this)?String(this):"null"};Object.prototype.toJSONString=function(){var d=["{"],c,f,e;function g(a){if(c){d.push(",")}d.push(f.toJSONString(),":",a);c=true}for(f in this){if(this.hasOwnProperty(f)){e=this[f];switch(typeof e){case"undefined":case"function":case"unknown":break;case"object":if(e){if(typeof e.toJSONString==="function"){g(e.toJSONString())}}else{g("null")}break;default:g(e.toJSONString())}}}d.push("}");return d.join("")};(function(s){var m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};s.parseJSON=function(filter){try{if(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)){var j=eval("("+this+")");if(typeof filter==="function"){function walk(k,v){if(v&&typeof v==="object"){for(var i in v){if(v.hasOwnProperty(i)){v[i]=walk(i,v[i])}}}return filter(k,v)}return walk("",j)}return j}}catch(e){}throw new SyntaxError("parseJSON")};s.toJSONString=function(){if(/["\\\x00-\x1f]/.test(this)){return'"'+this.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c}c=b.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+this+'"'}})(String.prototype)};liwe.form={};liwe.form._instances={};liwe.form.cbacks={};liwe.form.utils={};liwe.form.cbacks.ip_change=function(a){console.debug(a)};liwe.form.get=function(a){return liwe.form._instances.get(a)};liwe.form.check=function(a){var j,i;var b,c;var h;var g;var d;var e=liwe.form.get(a);g=e._mandatory;for(i=0;i<g.length;i++){b=document.getElementById(g[i]);c=document.getElementById(g[i]+"@hint");h=document.getElementById(g[i]+"_mandatory");if(!b){continue}c.innerHTML="&nbsp;";if(b.value.length==0){c.innerHTML=_("os3_form","Mandatory&nbsp;field");h.src=liwe._libbase+"/gfx/form/error.gif";b.focus();return false}h.src=liwe._libbase+"/gfx/form/ok.gif"}g=e._validates;for(i=0;i<g.length;i++){b=document.getElementById(g[i][0]);h=document.getElementById(g[i][0]+"_valid");c=document.getElementById(g[i][0]+"@hint");if(!b){continue}c.innerHTML="&nbsp;";if(b.value.length==0){continue}if(g[i][1](b.value)==false){c.innerHTML=_("os3_form","Validation&nbsp;failed");h.src=liwe._libbase+"/gfx/form/error.gif";h.alt=_("os3_form","Validation failed");h.title=_("os3_form","Validation failed");b.focus();return false}h.src=liwe._libbase+"/gfx/form/ok.gif";h.alt=_("os3_form","Validation OK");h.title=_("os3_form","Validation OK")}return true};liwe.form.cbacks.ajax_submit=function(id){var frm=liwe.form._instances[id];if(!frm.check()){return}if(frm.events.start){var r=frm.events.start(frm);if(!r){return}}var a=frm.get_values();var action=frm._resolve_action();eval("var _func = "+frm.events.complete);if(!frm.events.submit){liwe.AJAX.request(action,a,_func,true)}else{frm.events.submit(a,action,_func)}};function form_sel(b){if(typeof OS3Sel=="undefined"){alert(_("os3_form","You *MUST* include OS3Sel!"));return null}this._start_field(b);b.id=this.name+"@"+this._get_name(b);this.html+='<div id="'+b.id+'"></div>';this._newline(b);var a=new OS3Sel({div_id:b.id,multi:b.get("multi",0),bicolor:b.get("bicolor",true),num_columns:b.get("columns",1),width:b.get("width","100%"),height:b.get("height","100%")});if(b.headers){a.set_headers(b.headers)}return a}liwe.form.instance=function(a,b,c){this.name=a;this.action=b;this.easy=true;this.events={start:null,"before-complete":null,complete:null,submit:null};this.no_table=c;this.multipart=false;this.html="";this.ajax_mode=null;this.debug=false;this._first_field=null;this._field_extensions=[];this.register_field_extension=function(f,d,e){var g={name:f,cback:d,skip:e};if(e){this.skips.push(e.toLowerCase())}this._field_extensions.push(g)};this.upload=function(d){this.multipart=true;this._start_field(d);this._add_field("file",d)};this.text=function(d){this._start_field(d);this._add_field("text",d)};this.email=function(d){this._set_values("email",d);this._start_field(d);this._add_field("text",d)};this.number=function(d){this._set_values("number",d);this._start_field(d);this._add_field("text",d)};this.money=function(d){if(typeof Money=="undefined"){liwe.utils.append_js(liwe._libbase+"/money.js")}this._set_values("money",d);this._start_field(d);this._add_field("text",d)};this.submit=function(d){if(typeof(d)=="string"){d={value:d}}this._start_field(d);if(this.multipart){this._add_field("submit",d)}else{d.onclick="liwe.form.cbacks.ajax_submit('"+this.name+"');";this._add_button(d)}};this.label=function(d){this._start_field(d);this.html+=d.value;this._newline(d)};this.password=function(d){this._start_field(d);this._add_field("password",d)};this.checkbox=function(d){this._start_field(d);this._add_field("checkbox",d)};this.hidden=function(d,e){if(typeof(e)!="undefined"){var f=this.name+"@"+d;this._fields.push(d);this.html+='<input type="hidden" name="'+d+'" id="'+f+'" value="'+e+'" ';this.html+=" />"}else{var f=this.name+"@"+d.name;this._fields.push(d.name);this.html+='<input type="hidden" id="'+f+'" name="'+d.name+'" value="'+d.value+'" ';if(d.onchange){this.html+=' onchange="'+d.onchange+'" '}this.html+=" />"}};this.select=function(i){this._start_field(i);var n="<select ";var h;var m="{"+this._skips.join("}{")+"}";var f=-1;i.id=this.name+"@"+this._get_name(i);n+=' id="'+i.id+'" ';if((i.defval!=undefined)&&(i.value==undefined)){i.value=i.defval}for(h in i){if(typeof i[h]=="function"){continue}if(m.indexOf("{"+h.toLowerCase()+"}")!=-1){continue}n+=h+'="'+i[h]+'" '}n+=">";this.html+=n;if(i.value!=undefined){f=i.value}n="";if(i.force_select){n+='<option value="">'+_("os3_form","(Selezionare)")+"</option>"}if(i.options){var d=Array.fromObject(i.options);var g=d.length;var j,e;for(j=0;j<g;j++){e=d[j];n+='<option value="'+e.value+'" ';if(e["class"]){n+=' class="'+e["class"]+'" '}if((e.selected||(f==e.value))){n+=' selected="selected" '}n+=">"+e.label+"</option>"}}n+="</select>";this.html+=n;if(i.mandatory){this._mandatory.push(i.id)}this._create_hint(i);this._newline(i)};this.select_set_values=function(i,g){var h,f=g.length,j;var d=this.get_element(i);for(h=0;h<f;h++){d.options[0]=null}for(h=0;h<f;h++){j=new Option(g[h]["label"],g[h]["value"],false,false);d.options[d.options.length]=j}};this.sep=function(d){this._newline({});if(!this.no_table){this.html+='<tr><td colspan="200">'}this.html+="<hr />";this._newline({})};this.textarea=function(g){this._start_field(g);var f="<textarea ";var e;var d="{label}{mandatory}{akey}{hint}{text}{nonl}{os3_full}{defval}{value}{show_entity}{code}";g.id=this.name+"@"+this._get_name(g);if((g.value)&&(!g.text)){g.text=g.value}if((g.defval!=undefined)&&(g.text==undefined)){g.text=g.defval}for(e in g){if(d.indexOf("{"+e.toLowerCase()+"}")!=-1){continue}if(typeof g[e]=="function"){continue}f+=e+'="'+g[e]+'" '}if(g.akey){f+=' accesskey="'+g.akey+'" '}if(g.code){f+=' style="font-family: Courier, monospace; font-size: 80%;" '}f+=">";if(g.text){if(g.show_entity){f+=g.text.replace(new RegExp("&([a-zA-Z][a-z]+);","g"),"&amp;$1;").replace(new RegExp("<br[^>]*>","g"),"\n")}else{f+=g.text}}f+="</textarea>";this.html+=f;if(g.mandatory){this._mandatory.push(g.id)}this._create_hint(g);this._newline(g)};this.button=function(d){this._start_field(d);d.id=this.name+"@"+this._get_name(d);this._add_button(d);this._newline(d)};this.descr=function(d){if(typeof(d)=="string"){d={text:d}}this._newline({});if(!this.no_table){this.html+='<tr><td colspan="200" class="text_descr">'}this.html+=d.text;this._newline({})};this.error_msg=function(d){var f=$(this.name+"_err_box");if(!f){console.error("No error box for form: "+this.name)}if(d){f.innerHTML=d;f.style.visibility="visible"}else{f.style.visibility="hidden"}};this.get=function(){var g="";var d="";var e="";var f=this._resolve_action();if(!this.name){this.name="no_name"}g+='<form method="post" name="'+this.name+'" id="'+this.name+'"  action="'+f+'"  onsubmit="return liwe.form._aim.submit(this,{onStart: liwe.form._event_on_start, onComplete: liwe.form._event_on_complete})">';if(this.no_table){g+='<div class="frm" id="'+this.name+'_frm" >';d+="</div>"}else{g+='<table border="0" class="frm" id="'+this.name+'_frm" cellpadding="0" cellspacing="0" >';d+="</table>"}return g+this.html+d+"</form>"};this.set=function(d){var e=document.getElementById(d);if(!e){console.error("Form.set(): object '%s' not found in DOM",d);return}e.innerHTML=this.get();this._render_all();if(this._first_field){this.set_focus(this._first_field)}};this._resolve_action=function(){if(this.action){return this.action}if(this.ajax_mode){return this.ajax_mode}if(liwe.AJAX&&liwe.AJAX.url){return liwe.AJAX.url}console.error("Form: %s does not have an 'action' value set",this.name);return""};this.error_box=function(){var d;var e=Array();e.os3_full=1;this._start_field(e);d="border: 1px solid red; padding: 4px; background-color: #FFE87F; color: black; visibility: "+(e.show?"visible":"hidden");this.html+='<div id="'+this.name+'_err_box" style="'+d+'"></div>';this._newline(e)};this.workspace=function(d){this._newline({});if(!this.no_table){this.html+='<tr><td colspan="200">'}this.html+='<div id="'+d.name+'"></div>';this._newline({})};this.check=function(){return liwe.form.check(this.name)};this.get_value=function(g){if(this._widgets[g]){var d=this._widgets[g];return d.get_value()}var f=document.getElementById(this.name+"@"+g);if(!f){return null}if((f.type=="checkbox")&&(!f.checked)){return false}return f.value};this.set_value=function(g,d){if(this._widgets[g]){this._widgets[g].set_value(d);return}var f=document.getElementById(this.name+"@"+g);if(!f){console.warn("Form: could not find input '%s'",this.name+"@"+g);return}switch(f.type){case"checkbox":f.checked=d;break;default:f.value=d}};this.set_focus=function(g){if(this._widgets[g]){var d=this._widgets[g];d.set_focus();return}var f=document.getElementById(this.name+"@"+g);if(!f){return}f.focus();f.select()};this.get_element=function(d){return document.getElementById(this.name+"@"+d)};this.get_values=function(){var d={};var e=this;this._fields.iterate(function(f){d[f]=e.get_value(f)});return d};this.clear=function(){function d(f){var g=f.length;var h;for(h=0;h<g;h++){if(f[h].type.toUpperCase()=="CHECKBOX"){f[h].checked=false}else{f[h].value=""}}}var e=$(this.name+"_frm");d(e.getElementsByTagName("input"));d(e.getElementsByTagName("select"));d(e.getElementsByTagName("textarea"))};this.radio=function(d){this._start_field(d);this._add_field("radio",d)};this.grid=function(f){if(typeof OS3Grid=="undefined"){alert(_("os3_form","You *MUST* include OS3Grid"));return null}var d=f.name;this._start_field(f);f.id=this.name+"@"+this._get_name(f);this.html+='<div id="'+f.id+'"></div>';this._newline(f);var e=new OS3Grid(f.name);e.width="100%";e.height="100%";e.highlight=true;e.div_id=f.id;if(f.headers){e.set_headers(f.headers)}return e};this.add_widget=function(d){this._start_field(d);this.html+=d.widget;this._newline(d)};this.replace=function(e){function i(o){var p=o.getElementsByTagName("option");var n,j=p.length,m;var k=[];if(o.getAttribute("force_select")==1){k.push({label:"(Selezionare)",value:""})}for(n=0;n<j;n++){m=p[n];k.push({label:m.innerHTML,value:m.value})}return k}var h=document.getElementById(e);var g,d,f;["input","textarea"].iterate(function(j){f=h.getElementsByTagName(j);for(g=0;g<d;g++){this._create_field(f[g])}});f=h.getElementsByTagName("select");d=f.length;for(g=0;g<d;g++){opts=i(f[g]);this._create_field(f[g]);this.select_set_values(f[g].name,opts)}};this.ipaddr=function(f){var e={};this._start_field(f);if((f.defval!=undefined)&&(f.value==undefined)){f.value=f.defval}if(f.value){e=f.value.match(new RegExp("([1-9][0-9]{0,2}).([1-9][0-9]{0,2}).([1-9][0-9]{0,2}).([1-9][0-9]{0,2})"))}if(!f.onchange){f.onchange="liwe.form.cbacks.ip_change ( this )"}else{f.onchange="liwe.form.cbacks.ip_change ( this );"+f.onchange}this.html+='<table border="0" cellpadding="0" cellspacing="0"><tr><td>';var d=Array();d.filter="0123456789";d["class"]="number";d.os3_def_validator=liwe.validators.is_integer;d.nonl=1;d.onchange=f.onchange;d.name=f.name+"@ip1";d.id=f.name+"@ip1";d.size=3;d.maxlength=3;d.title="IP 1";d.value=e[1];this._add_field("text",d);this.html+=".</td><td>";d.name=f.name+"@ip2";d.id=f.name+"@ip2";d.size=3;d.maxlength=3;d.title="IP 2";d.value=e[2];this._add_field("text",d);this.html+=".</td><td>";d.name=f.name+"@ip3";d.id=f.name+"@ip3";d.title="IP 3";d.value=e[3];this._add_field("text",d);this.html+=".</td><td>";d.name=f.name+"@ip4";d.id=f.name+"@ip4";d.title="IP 4";d.value=e[4];this._add_field("text",d);this.html+="</td>";this._create_hint(f);if(f.id){this.html+='</td><td><div id="'+f.id+'"></div>'}this.html+="</td></tr></table>";this._newline(f)};this.cod_fisc=function(d){d.size=16;d.maxlength=16;d.filter="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";d.os3_def_validator=liwe.validators.is_codice_fiscale;this._start_field(d);this._add_field("text",d)};this.p_iva=function(d){d.size=11;d.maxlength=11;d.filter="0123456789";d.os3_def_validator=liwe.validators.is_partita_iva;this._start_field(d);this._add_field("text",d)};this.fetch_htmled_contents=function(){console.error("form.fetch_htmled_contents() has been REMOVED")};this._render_all=function(){this._widgets.iterate(function(e,d){if(e.render){e.render()}if(e._refresh){e._refresh()}})};this._start_field=function(i,f){var d="";var h=i.get("os3_class_descr","descr");var g=i.get("os3_class_value","value");if(!i.name){this._get_name(i)}this._fields.push(i.name);if(i.style){d='style="'+i.style+'"'}if((!this.no_table)&&(!this._row_open)){if(i.os3_full){this._row_open=true;this.html+='<tr><td colspan="100" align="center" width="100%" class="'+h+'" '+d+">";return}else{this.html+='<tr><td class="'+h+'" '+d+">"}}this._row_open=true;if(i.label){if(i.akey){var e=new RegExp("("+i.akey+")","i");if(!e.test(i.label)){i.label+=" ("+i.akey+")"}this.html+="<label>"+i.label.replace(e,'<span class="akey">$1</span>')+": </label>"}else{this.html+="<label>"+i.label+": </label>"}}if(!this.no_table){this.html+='</td><td class="'+g+'" valign="top"';if(i.colspan){this.html+=' colspan="'+i.colspan+'"'}this.html+=">"}};this._create_field=function(g){var f=this;function i(j){var k={};f._skips.iterate(function(l){k[l]=j.getAttribute(l)});["name","id","type"].iterate(function(l){k[l]=j.getAttribute(l)});f._set_values(k.type,k);return k}var h=i(g);var e="{"+this._skips.join("}{")+"}";var d;g.id=this.name+"@"+this._get_name(h);if((h.defval!=undefined)&&(h.value==undefined)){h.value=h.defval}if(h.value){h.value=(h.value+"").replace(/"/g,"&quot;")}if(h.filter){g.onkeypress=function(j){return filter_valid_chars(j,h.filter,false)}}if((h.type=="checkbox")&&h.checked){g.setAttribute("checked","checked")}if(h.akey){g.setAttribute("accesskey",h.akey)}if(h.mandatory){this._mandatory.push(h.id)}if(h.validator){if(h.validator==true){if(h.os3_def_validator){this._validates.push([h.id,h.os3_def_validator])}}else{this._validates.push([h.id,h.validator])}}};this._add_field=function(g,h){var f='<input type="'+g+'" ';var e;var d="{"+this._skips.join("}{")+"}";h.id=this.name+"@"+this._get_name(h);if((h.defval!=undefined)&&(h.value==undefined)){h.value=h.defval}if(h.value){h.value=(h.value+"").replace(/"/g,"&quot;")}for(e in h){if(typeof h[e]=="function"){continue}if(d.indexOf("{"+e.toLowerCase()+"}")!=-1){continue}if(h[e]==undefined){continue}f+=e+'="'+h[e]+'" '}if(h.filter){f+=" onkeypress=\"return filter_valid_chars ( event, '"+h.filter+"', false )\" "}if((g=="checkbox")&&h.checked){f+=' checked="checked" '}if(h.akey){f+=' accesskey="'+h.akey+'" '}if(h.mandatory){this._mandatory.push(h.id)}if(h.validator){if(h.validator==true){if(h.os3_def_validator){this._validates.push([h.id,h.os3_def_validator])}}else{this._validates.push([h.id,h.validator])}}f+=' id="'+h.id+'"';f+=" />";this.html+=f;this._create_hint(h);if((!this._first_field)&&(h.name)){this._first_field=this._get_name(h)}this._newline(h)};this._add_button=function(g){var f="<button ";var e;var d="{hint}{akey}{nonl}{os3_full}";g.id=this.name+"@"+this._get_name(g);for(e in g){if(typeof g[e]=="function"){continue}if(d.indexOf("{"+e.toLowerCase()+"}")!=-1){continue}f+=e+'="'+g[e]+'" '}if(g.akey){f+=' accesskey="'+g.akey+'" '}f+=' type="button">';f+=g.value;f+="</button>";this.html+=f;this._create_hint(g);this._newline(g)};this._newline=function(d){if((d.nonl)||(!this._row_open)){this.html+='</td><td valign="top" nowrap="nowrap" class="descr">';return}this._row_open=false;if(this.no_table){this.html+="<br />"}else{this.html+="</td></tr>"}};this._create_hint=function(f){var e;var d;if(f.hint){d=_("os3_form","hint");e='<img alt="'+d+'" src="'+liwe._libbase+'/gfx/bubble/hint.png" onclick="bubble_show ( this.previousSibling, \''+f.hint+"', true )\" />";this.html+=e;if(typeof bubble_show=="undefined"){liwe.utils.append_js(liwe._libbase+"/bubble.js")}}if(f.mandatory){d=_("os3_form","Mandatory field");e='&nbsp;<img alt="'+d+'" title="'+d+'" src="'+liwe._libbase+'/gfx/form/mandatory.gif" id="'+f.id+'_mandatory" />';this.html+=e}if(f.validator){d=_("os3_form","Field needs Validation");e='&nbsp;<img alt="'+d+'" title="'+d+'" src="'+liwe._libbase+'/gfx/form/okb.gif" id="'+f.id+'_valid" />';this.html+=e}if(f.id){this.html+='&nbsp;<span id="'+f.id+'@hint">&nbsp;</span>'}};this._get_name=function(d){this._widget_count++;if(!d.name){d.name="W"+this._widget_count}return d.name};this._set_values=function(d,e){switch(d){case"email":e.filter="0123456789abcdefghijklmnopqrstuvwxyz._@";e.os3_def_validator=liwe.validators.is_email;break;case"number":e.filter="-0123456789";e["class"]="number";e.os3_def_validator=liwe.validators.is_integer;break;case"money":e.filter="0123456789,.";e["class"]="number";if(!e.onblur){e.onblur="this.value = money_format ( this.value )"}else{e.onblur="this.value = money_format ( this.value  );"+e.onblur}if(e.defval){e.defval=Money.fromLongInt(e.defval)}if(e.value){e.value=Money.fromLongInt(e.value)}break}};this._row_open=false;this._widget_count=0;this._mandatory=Array();this._validates=Array();this._fields=[];this._widgets={};this._skips=["label","hint","filter","akey","mandatory","validator","os3_def_validator","nonl","os3_full","defval","checked","id","options"];liwe.form._instances[a]=this};liwe.form._aim={frame:function(e,h,b){var a=document.getElementById("__ajax_form");if(!a){var g=document.createElement("DIV");g.innerHTML='<iframe style="display:none" src="about:blank" id="__ajax_form" name="__ajax_form" onload="liwe.form._aim.loaded()"></iframe>';document.body.appendChild(g);a=document.getElementById("__ajax_form")}if(h&&typeof(h.onComplete)=="function"){a.onComplete=h.onComplete}a._form=b},form:function(a){a.setAttribute("target","__ajax_form");a.setAttribute("enctype","multipart/form-data")},submit:function(b,d){var a=liwe.form.get(b.getAttribute("name"));if(!a.check()){return false}liwe.form._aim.form(b,liwe.form._aim.frame(b,d,a));if(d&&typeof(d.onStart)=="function"){return d.onStart(a)}return true},loaded:function(){var a=document.getElementById("__ajax_form");var b;if(a.contentDocument){b=a.contentDocument}else{if(a.contentWindow){b=a.contentWindow.document}else{b=window.frames.__ajax_form.document}}if(b.location.href=="about:blank"){return}if(typeof(a.onComplete)=="function"){a.onComplete(a._form,b.body.innerHTML)}}};liwe.form._event_on_start=function(a){if(a.events.start){if(!a.events.start(a)){return false}}return true};liwe.form._event_on_complete=function(b,a){if(b.easy){AJAXManager.handle_easy(a,b.events.complete)}else{if(b.events.complete){b.events.complete(a)}}};liwe.utils.max=function(){if(!arguments.length){return 0}var a=0;var b;for(b=0;b<arguments.length;b++){if(a<arguments[b]){a=arguments[b]}}return a};liwe.utils.min=function(){if(!arguments.length){return 0}var a=arguments[0];var b;for(b=1;b<arguments.length;b++){if(a>arguments[b]){a=arguments[b]}}return a};liwe.utils.date2str=function(b,d){var c=new String(b);var a=c.match(new RegExp("([0-9]{4}).([0-9]{1,2}).([0-9]{1,2}).*"));if(!d){d=0}switch(d){case 1:c=a[3]+"-"+a[2]+"-"+a[1];break;case 2:c=a[2]+"-"+a[3]+"-"+a[1];break;default:c=a[1]+"-"+a[2]+"-"+a[3]}return c};liwe.utils.call=function(func_name,arg_array){var i,l=arg_array.length;var s="this_arg."+func_name+" ( ";for(i=0;i<l;i++){if(i>0){s+=", "}s+="arg_array["+i+"]"}s+=" );";return eval(s)};liwe.utils.format_list=function(a,d,f,g){if(!a){return""}var e=new String.buffer();var c,b=a.length;if(f){e.add(f)}for(c=0;c<b;c++){e.add(String.formatDict(d,a[c]))}if(g){e.add(g)}return e.toString()};liwe.utils._ents=null;liwe.utils.map_entities=function(b){if(!liwe.utils_ents){liwe.utils._ents={"&#8217;":"'","&#224;":"&agrave;","&#232;":"&egrave;","&#233;":"&eacute;","&#242;":"&ograve;","&#249;":"&ugrave;","&#8220;":'"',"&#8221;":'"',"&#8211;":"-","%u2013":"-","%u2019":"'","%u201C":'"',"%u201D":'"'};var c="";var a=[];liwe.utils._ents.iterate(function(e,d){a.push(d)});c="("+"|".join(a)+")";liwe.utils._ents_re=RegExp(c,"g")}b=b.replace(/&#37;/g,"%");return b.replace(liwe.utils._ents_re,function(d){return liwe.utils._ents[d]})};liwe.utils.rand=function(a){return Math.floor(Math.random()*(a+1))};liwe.utils.unique_id=function(){var c=new Date(1970,1,1);var b,e;var a=[];b=liwe.utils.rand(Date.parse(new Date()));for(t=0;t<4;t++){a.push(""+b);b=liwe.utils.rand(b);e=new Date(b);b=Math.abs(liwe.utils.rand(e-c))}return a.join("-")};liwe.validators={};liwe.validators.is_integer=function(a){return RegExp("^[-+]?[0-9]+$").test(a)};liwe.validators.is_alpha=function(a){return RegExp("^[a-zA-Z]+$").test(a)};liwe.validators.is_alphanum=function(a){return RegExp("^[a-zA-Z0-9]+$").test(a)};liwe.validators.is_date=function(a){return RegExp("^[0-9]{4,4}.[0-9]{2,2}.[0-9]{2,2}$").test(a)};liwe.validators.is_time=function(a){return RegExp("^[012][0-9]:[0-5][0-9]$").test(a)};liwe.validators.is_email=function(a){return RegExp("^[a-zA-Z0-9-_.]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$").test(a)};liwe.validators.is_float=function(a){return RegExp("^[-+]?[0-9]*.[0-9]*$").test(a)};function filter_valid_chars(a,b,e){a=(a)?a:event;if(a.charCode<32){return true}var d=(a.charCode)?a.charCode:((a.which)?a.which:a.keyCode);var c=String.fromCharCode(d);if(e){c=c.toLowerCase();b=b.toLowerCase()}if(b.indexOf(c)==-1){return false}return true}liwe.validators.is_codice_fiscale=function(p){var d=new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");var o=new Array(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);var a=new Array(1,0,5,7,9,13,15,17,19,21,1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23);var l=p;var b=true;var q="";var c="";var g,n,m=0;var f,h,j,e;if(l.length!=16){return false}l=l.toLowerCase();c=l.substr(0,6)+l.substr(8,1)+l.substr(11,1)+l.substr(15);q=l.substr(6,2)+l.substr(9,2)+l.substr(12,3);for(g=0;g<10;g++){if(c.charCodeAt(g)<97||c.charCodeAt(g)>122){return false}}for(g=0;g<8;g++){if(q.charCodeAt(g)<48||q.charCodeAt(g)>57){return false}}n=l.substr(15,1);m=0;for(g=0;g<16;g=g+2){h=l.substr(g,1);for(e=0;e<36;e++){if(h==d[e]){m+=a[e];break}}}for(g=1;g<15;g=g+2){h=l.substr(g,1);for(e=0;e<36;e++){if(h==d[e]){m+=o[e];break}}}j=m%26;f=String.fromCharCode(97+j);if(n!=f){return false}return true};liwe.validators.is_partita_iva=function(e){var b,a,d,f;if(e==""){return false}if(e.length!=11){console.warn("PIVA: %s - length invalid: %d",e,e.length);return false}a="0123456789";for(b=0;b<11;b++){if(a.indexOf(e.charAt(b))==-1){console.warn("PIVA: %s - invalid char: %s at pos: %d",e,e.charAt(b),b);return false}}d=0;for(b=0;b<=9;b+=2){d+=e.charCodeAt(b)-"0".charCodeAt(0)}for(b=1;b<=9;b+=2){f=2*(e.charCodeAt(b)-"0".charCodeAt(0));if(f>9){f=f-9}d+=f}if((10-d%10)%10!=e.charCodeAt(10)-"0".charCodeAt(0)){console.warn("PIVA: %s - invalid checksum");return false}return true};function money_format(b){var a=new Money(b);return a.value}function Money(a){this.value="";this.set=money_meth_set;this.add=money_meth_add;this._format=money_int_format;this._to_money=money_int_float_to_money;if(a){this.set(a)}}Money.fromLongInt=function(b){var c=new String(b);if(c.indexOf(",")==-1){if(c.length>2){var d=c.substr(c.length-2,2);c=c.substr(0,c.length-2);c+=","+d}else{c="0,"+c}}var a=new Money(c);return a.value};Money.toFloat=function(b){var a;var c;var d;b=new String(b);if(b==""){return 0}b=b.replace(/\./g,"");a=b.indexOf(",");if(a==-1){b+=".00"}else{d=b.substring(0,a);c=b.substring(a+1);b=d+"."+c}return parseFloat(b)};Money.toMoney=function(b){var a=new Money(b);return a.value};function money_meth_set(a){this.value=this._format(a);return this.value}function money_meth_add(b){var a=Money.toFloat(this.value);var c=Money.toFloat(b);return this._to_money(a+c)}function money_int_format(d){var b;var e;var a="";var c;if(typeof d=="number"){this._to_money(d);return this.value}d=new String(d);d=d.Strip();if(!d.length){return""}d=d.replace(/[+-]/g,"");if(d.indexOf(",")==-1){d+=","}d+="00";e=d.replace(new RegExp(".*,(..).*"),"$1");d=d.replace(new RegExp("(.*),.*"),"$1");d=d.replace(new RegExp("\\.","g"),"");for(c=0;c<Math.floor((d.length-(1+c))/3);c++){d=d.substring(0,d.length-(4*c+3))+"."+d.substring(d.length-(4*c+3))}if(d==""){d="0"}if(e.length==1){e="0"+e}b=(a+d+","+e);return b}function money_int_float_to_money(a){var b=new String(a);b=b.replace(/\./g,",");this.value=this._format(b);return this.value};liwe.dom={};liwe.dom.get_offset_top=function(c){var b=c.offsetTop;var a=c.offsetParent;while(a&&a.tagName!="HTML"){b+=a.offsetTop;a=a.offsetParent}return b};liwe.dom.get_offset_left=function(c){var b=c.offsetLeft;var a=c.offsetParent;while(a){b+=a.offsetLeft;a=a.offsetParent}return b};liwe.dom.append_css=function(a,e,d){var b=document.getElementsByTagName("head")[0];var c=document.createElement("link");c.href=a;c.type="text/css";c.rel="stylesheet";if(e){c.id=e}if(d){b.insertBefore(c,b.firstChild)}else{b.appendChild(c)}};liwe.dom.get_padding_width=function(b){var c=b.clientWidth;var a;b.style.width="0px";a=b.clientWidth;b.style.width=(c-a)+"px";return a};liwe.dom.get_padding_height=function(c){var a=c.clientHeight;var b;c.style.height="0px";b=c.clientHeight;c.style.height=(a-b)+"px";return b};liwe.dom.get_size=function(a){return[a.clientWidth,a.clientHeight]};liwe.dom.get_window_size=function(){var c=document.createElement("div");c.style.position="absolute";c.style.bottom="0px";c.style.right="0px";c.style.width="1px";c.style.height="1px";c.style.visibility="hidden";document.body.appendChild(c);var a,b;a=liwe.dom.get_offset_left(c)+c.clientWidth;b=liwe.dom.get_offset_top(c)+c.clientHeight;document.body.removeChild(c);return{width:a,height:b}};liwe.dom.create_element=function(a,b,c){if(!c){c=document.body}if(document.all){a="<"+a+' name="'+b+'">'}var d=document.createElement(a);d.style.position="absolute";d.style.top="0px";d.style.right="0px";d.id=b;d.name=b;c.appendChild(d);return d};liwe.dom.remove_element=function(b,a){if(!a){a=document.body}a.removeChild(b)};liwe.dom.get_event_pos=function(b){var a=0,c=0;if(b==null){b=window.event}if(b.pageX||b.pageY){a=b.pageX;c=b.pageY}else{if(b.clientX||b.clientY){if(document.documentElement.scrollTop){a=b.clientX+document.documentElement.scrollLeft;c=b.clientY+document.documentElement.scrollTop}else{a=b.clientX+document.body.scrollLeft;c=b.clientY+document.body.scrollTop}}}return[a,c]};liwe.dom.has_class=function(a,c){var b=new RegExp("(^| )"+c+"( |$)");if(b.test(a.className)){return true}return false};liwe.dom.add_class=function(b,a){if(liwe.dom.has_class(b,a)){return}if(b.className==""){b.className=a}else{b.className+=" "+a}};liwe.dom.del_class=function(c,b){var a=new RegExp("(^| )"+b+"( |$)");c.className=c.className.replace(a,"$1").replace(/ $/,"")};Object.prototype.hide=function(){if(!this.style||this.style.display=="none"){return}this._old_display=this.style.display;this.style.display="none"};Object.prototype.show=function(){if(!this.style){return}if(this._old_display){this.style.display=this._old_display}else{this.style.display="block"}this._old_display=null};liwe.dom.supports=function(d){var c=document.createElement("div");var b="Khtml Ms O Moz webkit".split(" "),a=b.length;if(d in c.style){return true}d=d.replace(/^[a-z]/,function(e){return e.toUpperCase()});while(a--){if(b[a]+d in c.style){return true}}return false};liwe.dom.tableize=function(){if((!liwe.browser.ie)&&(!liwe.browser.version<8)){return}function b(o,m){var l=o.parentNode;var n=o.nextSibling;l.removeChild(o);l.insertBefore(m,n)}function c(l,n){var m;h=document.createElement("td");h.setAttribute("vAlign","top");h.className=n.className;m=h.appendChild(n.firstChild.cloneNode(true));m.style.display="block";l.appendChild(h)}var g=document.getElementsByTagName("div");var j,d=g.length,a;var i=null,e=null;var k=null,h=null;var f=null;for(j=0;j<d;j++){a=g[j];if(!a.className){continue}if(a.className.indexOf("table")!=-1){if(f){b(f,i);i=null}f=a;i=document.createElement("table");e=document.createElement("tbody");i.appendChild(e);i.className=a.className;i.style.border="1px dotted black"}else{if(a.className.indexOf("cell-first")!=-1){k=document.createElement("tr");e.appendChild(k);c(k,a)}else{if(a.className.indexOf("cell")!=-1){c(k,a)}}}}if(i){b(f,i)}};function $c(d,h,g){if(!g){g=document}var f=g.getElementsByTagName(d);var c,a=f.length;var b=[],e;for(c=0;c<a;c++){e=f[c];if(e.className.indexOf(h)==-1){continue}b.push(e)}return b};var drag={};drag.is_ie=document.all;drag.enabled=false;drag.obj=null;drag.x=0;drag.y=0;drag.move_func=null;drag.release_func=null;drag.start_func=null;drag.x_start=0;drag.y_start=0;drag.container_class="drag_box";drag.handle_class="drag_handle";drag.exclude_class="drag_exclude";drag.lock_x=false;drag.lock_y=false;drag.move=function(c){if(!drag.enabled){return}var b,d;var a=drag.is_ie?event:c;b=a.clientX;d=a.clientY;if(!drag.lock_y){drag.obj.style.top=(d-drag.y_start)+"px"}if(!drag.lock_x){drag.obj.style.left=(b-drag.x_start)+"px"}if(drag.move_func){drag.move_func(drag.obj,b,d)}};drag.start=function(g){var b=drag.is_ie?event:g;var h=drag.is_ie?b.srcElement:b.target;var d=drag.is_ie?"BODY":"HTML";if(!h||h==null||h==""||h.tagName&&h.tagName=="HTML"){return}while(h.tagName!=d&&(h.className.indexOf(drag.handle_class)==-1)&&(h.className.indexOf(drag.exclude_class)==-1)){h=drag.is_ie?h.parentElement:h.parentNode}if(h.className.indexOf(drag.handle_class)!=-1){while(h.tagName!=d&&(h.className.indexOf(drag.container_class)==-1)){h=drag.is_ie?h.parentElement:h.parentNode}drag.enabled=true;drag.obj=h;drag.x=b.clientX;drag.y=b.clientY;document.onmousemove=drag.move;var c=0;var a=0;var f=drag.obj;while(f&&f.tagName!=d){c+=f.offsetLeft;a+=f.offsetTop;f=f.offsetParent}drag.x_start=drag.x-c;drag.y_start=drag.y-a;if(drag.start_func){drag.start_func(drag.obj)}drag.obj.parentNode.removeChild(drag.obj);document.body.appendChild(drag.obj);drag.obj.style.position="absolute";drag.obj.style.top=(drag.y-drag.y_start)+"px";drag.obj.style.left=(drag.x-drag.x_start)+"px"}};drag.stop=function(){if(!drag.obj){return}drag.enabled=false;if(drag.release_func){drag.release_func(drag.obj)}drag.obj=false};document.onmousedown=drag.start;document.onmouseup=drag.stop;var shop = new liwe.module ( "shop" );

// shop._products = null;
shop._last_req = null;

shop.cfg = {
	"url_cancel" : "http://www.blurayweb.it/shop-cancel/%(order_code)s/",
	"url_confirm" : "http://www.blurayweb.it/shop-confirm/%(order_code)s/" 
};

shop.init = function ()
{
	// Richiesta AJAX per la lista dei pagamenti
	shop.ajax ( { action: "shop.ajax.list_payments" }, function ( v ) { shop._payments = v [ 'payments' ]; } );
};

shop.list_orders = function ()
{
	liwe.AJAX.easy ( { action: "shop.ajax.list_orders" }, function ( v )
		{
			var orders = v [ 'orders' ];
			var t, l = orders.length;
			var buf = new String.buffer ();

			if ( ! l ) 
			{
				alert ( "Non ci sono ordini memorizzati per questo utente." );
				return;
			}

			buf.add ( shop.templates [ 'orders-start' ] );
			for ( t = 0; t < l; t ++ )
			{
				orders [ t ] [ "_bg" ] = t % 2;
				buf.add ( String.formatDict ( shop.templates [ 'orders-row' ], orders [ t ] ) );
			}

			buf.add ( shop.templates [ 'orders-end' ] );

			$( "block_main" ).innerHTML = buf.toString ();
			

		} );
};

shop.order_detail = function ( id_order )
{
	liwe.AJAX.easy ( { action: "shop.ajax.order_detail", id_order: id_order }, function ( v )
		{
			if ( typeof ( v [ 'globals' ] ) == "undefined" )
			{
				alert ( "Non c'e' alcun ordine con queste caratteristiche." );
				return;
			}

			if ( ! v [ 'globals' ] [ 'sent' ] ) v [ 'globals' ] [ 'sent' ] = '&nbsp;';
			if ( ! v [ 'globals' ] [ 'payed' ] ) v [ 'globals' ] [ 'payed' ] = '&nbsp;';

			v [ 'addr_sped' ] [ '_title' ] = "Indirizzo di spedizione";
			v [ 'addr_fatt' ] [ '_title' ] = "Indirizzo di fatturazione";

			var buf = new String.buffer ();
			var rows = v [ 'rows' ];
			var t, l = rows.length;

			buf.add ( String.formatDict ( shop.templates [ 'od-top' ], v [ "globals" ] ) );
			buf.add ( String.formatDict ( shop.templates [ 'od-addr' ], v [ "addr_sped" ] ) );
			buf.add ( String.formatDict ( shop.templates [ 'od-addr' ], v [ "addr_fatt" ] ) );
			buf.add ( shop.templates [ 'od-prods' ] );

			for ( t = 0; t < l; t ++ )
				buf.add ( String.formatDict ( shop.templates [ 'od-prod-row' ], rows [ t ] ) );

			buf.add ( shop.templates [ 'od-prods-end' ] );

			$( "block_main" ).innerHTML = buf.toString ();

		} );
};

shop.list_products = function ()
{
	liwe.AJAX.easy ( { action: "shop.ajax.list_products" }, shop._format_small );
};

shop.add_product = function ( prod_code, quant )
{
	liwe.AJAX.easy ( { action: "shop.ajax.add_product",
			   product_code: prod_code,
			   quant: quant }, shop._format_small );
};

shop.del_product = function ( prod_code )
{
	liwe.AJAX.easy ( { action: "shop.ajax.change_quant", product_code: prod_code, quant: 0 }, shop._format_all );
};

shop.change_quant = function ( prod_code, quant )
{
	liwe.AJAX.easy ( { action: "shop.ajax.change_quant", product_code: prod_code, quant: quant}, shop._format_all );
};

shop.show_details = function ()
{
	liwe.history.add_module ( "shop", { "_page" : "show_details" } );

	if ( shop._last_req ) 
		return shop._format_full ( shop._last_req ); //{ "prods" : shop._products } );

	return liwe.AJAX.easy ( { action: "shop.ajax.list_products" }, shop._format_full );
};

shop.clear = function ()
{
	if ( confirm ( "Sei sicuro di voler svuotare il carrello?" ) )
		liwe.AJAX.easy ( { action: "shop.ajax.clear" }, shop._format_small );
};

shop.checkout = function ()
{
	liwe.history.add_module ( "shop", { "_page" : "checkout" } );
	client.login ();
};
	
shop.complete_order = function ( note, id_sped, id_fatt )
{
	// show_wait (true);

	liwe.AJAX.easy ( { action: "shop.ajax.complete_order", note: note, id_sped: id_sped, id_fatt: id_fatt },
		function ( v )
		{
			if ( v [ 'payment_kind' ] != 'contr' )
			{
				$( "block_main", String.formatDict ( shop.templates [ 'complete_order_paypal' ], v ) );
				// alert ( "SEND PAYPAL" );
				shop._send_paypal ( v );
			} else
				$( "block_main", String.formatDict ( shop.templates [ 'complete_order_contr' ], v ) );
		} );
};

shop._send_paypal = function ( vals )
{
	vals [ 'shipping_cost' ] = String.formatDict ( "%(total_vat)m", shop._last_req [ 'sped' ] ).replace ( ",", "." );
	vals [ '_cancel' ] = String.formatDict ( shop.cfg [ 'url_cancel' ], vals );
	vals [ '_confirm' ] = String.formatDict ( shop.cfg [ 'url_confirm' ], vals );

	var prods = shop._last_req [ 'prods' ], l = prods.length, t;
	var s = String.formatDict ( shop.templates [ 'pp_form_start' ], vals );

	for ( t = 0; t < l; t ++ )
	{
		prods [ t ] [ '_row_count' ] = t + 1;
		prods [ t ] [ '_price' ] = String.formatDict ( "%(price_vat)m", prods [ t ] ).replace ( ",", "." );
		s += String.formatDict ( shop.templates [ 'pp_form_row' ], prods [ t ] );
	}

	s += shop.templates [ 'pp_form_end' ];

	$( "shop_hidden_div" ).innerHTML = s;
	$( "shop_hidden_div" ).firstChild.submit ();
};

shop._format_all = function ( v )
{
	if ( ! v ) v = shop._last_req;

	shop._format_small ( v );
	shop._format_full ( v );
};

shop._format_small = function ( v )
{
	if ( ! v ) v = shop._last_req;

	var s = shop._format_cart ( v, "box" );
	$( "shop-small" ).innerHTML = s;
};

shop._format_full = function ( v )
{
	if ( ! v ) v = shop._last_req;

	var s = shop._format_cart ( v, "full" );
	$( "block_main" ).innerHTML = s;
};

shop._create_details = function ()
{
	return shop._format_cart ( shop._last_req, "detail" );
};

shop._format_cart = function ( v, prefix )
{
	var prods = v [ 'prods' ], l = prods.length, t;
	var s = new String.buffer ();
	var total = 0;

	shop._last_req = v;

/*
	shop._products = prods;
	shop._all = v;
*/

	if ( ! l )
		return shop.templates [ 'empty-cart' ];


	s.add ( shop.templates [ prefix + '_start' ] );
	s.add ( shop.templates [ prefix + '_header' ] );

	for ( t = 0; t < l; t ++ )
	{
		prod = prods [ t ];
		prod [ 'vat_total' ] = prod [ 'total_vat' ] - prod [ 'total_net' ];
		prod [ '_row_bg' ] = t % 2;

		s.add ( String.formatDict ( shop.templates [ prefix + '_row' ], prods [ t ] ) );
		total += prods [ t ] [ 'total_vat' ];
	}

	shop._total_vat = total;

	total += v [ 'sped' ] [ 'total_vat' ];
	total += v [ 'payment' ] [ 'total_vat' ];

	v [ 'sped' ] [ '_modify' ] = ''; // Per ora non si puo' modificare il tipo di spedizione

	v [ 'payment' ] [ '_modify' ] = '<a href="javascript:shop.modify_payment()">Cambia</a>';

	s.add ( String.formatDict ( shop.templates [ prefix + '_sped' ], v [ 'sped' ] ) );
	if ( typeof v [ 'payment' ] != "undefined" ) s.add ( String.formatDict ( shop.templates [ prefix + '_sped' ], v [ 'payment' ] ) );

	s.add ( String.formatDict ( shop.templates [ prefix + '_footer' ], { "_total" : total } ) );
	s.add ( String.formatDict ( shop.templates [ prefix + '_order' ], { "_total" : total } ) );
	s.add ( shop.templates [ prefix + '_end' ] );

	return s.toString ();
};

shop.update = function ()
{
	liwe.AJAX.easy ( { action: "shop.ajax.list_products" }, function ( v )
		{
			shop._last_req = v;
			shop._format_small ( v );
			var obj = liwe.history.get_current_obj ();

			if ( ( obj [ '_page' ] == 'show_details' ) && ( obj [ '__m' ] == 'shop' ) )
				shop._format_full ( v );
		} );
};

shop.modify_payment = function ()
{
	var res = new String.buffer ();
	var payments = shop._payments;
	var t, l = payments.length;

	res.add ( '<div style="background-color: white; border: 2px; padding: 8px;">' );

	liwe.lightbox.easy ( "select_payment", "Selezionare il tipo di pagamento", 400, 300 );

	res.add ( String.formatDict ( client.templates [ 'payment-top' ], client.testi ) );

	for ( t = 0; t < l; t ++ )
	{
		row = payments [ t ];

		res.add ( String.formatDict ( client.templates [ 'payment-row' ], row ) );
	}

	res.add ( String.formatDict ( client.templates [ 'payment-bottom' ], { cback: "shop._sel_payment()" } ) );
	res.add ( "</div>" );

	$( "select_payment", res.toString () );
};

shop._sel_payment = function ()
{
	var f = Array.fromForm ( "shop-payment-form" );
	
	if ( typeof f [ 'payment' ] == 'undefined' )
	{
		alert ( "Selezionare un elemento dalla lista" );
		return;
	}

	client.id_payment_meth = f [ 'payment' ];

	liwe.AJAX.easy ( { action: "shop.ajax.set_payment", id_payment_meth: client.id_payment_meth }, 
		function ( v ) 
		{
			liwe.lightbox.close ();
			shop.update ();
		} );
};

shop.event_dispatch = function ( dict, data )
{
	var page = dict.get ( "_page" );

	switch ( page )
	{
		case "show_details":
			shop.show_details ();
			break;

		case "checkout":
			shop.checkout ();
			break;
		
		default:
			console.error ( "shop-dispatch - unhandled page: %s - object: %o", page, dict );
	}

};

liwe.history.set_listener ( shop.event_dispatch, "shop" );
shop.home = {};

shop.home.show = function ()
{
	$( "block_main", shop.home.templates [ 'home' ] );
};
shop.templates = {
	'box_start' : '<table border="1" class="shop-prod-box">',
	'box_header': '<tr><th>Descrizione</th><th>Qnt</th><th>Tot.</th>',
	'box_row'   : '<tr class="bg%(_row_bg)s"><td class="descr">%(descr)s</td><td class="quant">%(quant)s</td><td class="value">%(total_vat)m</td></tr>',
	'box_sped'   : '<tr><td class="descr" colspan="2">%(descr)s<br />%(_modify)s</td><td class="value">%(total_vat)m</td></tr>',
	'box_footer': '<tr><td><a href="javascript:shop.show_details()">Dettagli</a></td><td colspan="2"><a href="javascript:shop.clear()">Svuota</a></td></tr>' + 
			'<tr><td colspan="2" class="total">Totale:</td><td class="tot_val">%(_total)m</td></tr>',
	'box_order' : '<tr><td colspan="3" align="center"><a href="javascript:shop.checkout()">Procedi con l\'ordine</a></td></tr>',
	'box_end'   : '</table>', 

	'full_start' : '<div id="shop-full-box" align="center"><table border="1" class="shop-prod-box">',
	'full_header': '<tr><th></th><th>Descrizione</th><th>Qnt</th><th>Pr.Netto</th><th>Sc. %</th><th>Importo<th>IVA</th><th>Tot.</th>',
	'full_row'   :  '<tr class="bg%(_row_bg)s>' + 
			'<td><a href="javascript:shop.del_product(\'%(product_code)s\')" title="Elimina dal Carrello" alt="Elimina dal Carrello"><div class="trash"></div></a></td>' + 
			'<td class="descr">%(descr)s</td>' + 	
			'<td class="quant"><input size="4" maxlength="3" style="text-align: right" type="text" value="%(quant)s" onchange="shop.change_quant(\'%(product_code)s\',this.value)"</td>' + 
			'<td class="value">&euro; %(real_net)m</td>' + 
			'<td class="value">%(discount)d</td>' + 
			'<td class="value">&euro; %(total_net)m</td>' + 
			'<td class="value">&euro; %(vat_total)m</td>' + 
			'<td class="value">&euro; %(total_vat)m</td>' + 
			'</tr>',
	'full_order' : '<tr><td colspan="8" align="center"><a href="javascript:shop.checkout()">Procedi con l\'ordine</a></td></tr>',
	'full_sped'   : '<tr><td class="descr" colspan="7">%(descr)s</td><td class="value">%(total_vat)m</td></tr>',
	'full_footer': '<tr><td colspan="7" class="total">Totale:</td><td class="tot_val">&euro; %(_total)m</td></tr>',
	'full_end'   : '</table></div>',

	'detail_start' : '<table border="1" class="shop-prod-box">',
	'detail_header': '<tr><th>Descrizione</th><th>Qnt</th><th>Tot.</th>',
	'detail_row'   : '<tr class="bg%(_row_bg)s><td class="descr">%(descr)s</td><td class="quant">%(quant)s</td><td class="value">&euro; %(total_vat)m</td></tr>',
	'detail_order' : '',
	'detail_sped'   : '<tr><td class="descr" colspan="2">%(descr)s</td><td class="value">%(total_vat)m</td></tr>',
	'detail_footer': '<tr><td colspan="2" class="total">Totale:</td><td class="tot_val">&euro; %(_total)m</td></tr>',
	'detail_end'   : '</table>',

	'complete_order_paypal' : '<div id="shop_hidden_div" style="display: none; border: 1px solid black;"></div><h1>Ordine confermato</h1>Grazie per aver confermato l\'ordine: <strong>%(order_code)s</strong>.<br />' + 
			   'Adesso il sistema aprir&agrave; il sito di PayPal per il pagamento di <strong>&euro; %(total_vat)m</strong> tramite <strong>%(payment_descr)s</strong>',

	'complete_order_contr' : '<h1>Ordine confermato</h1>Grazie per aver confermato l\'ordine: <strong>%(order_code)s</strong>.<br />' + 
			   'Il pagamento avverr&agrave; in <strong>contrassegno</strong> per l\'importo di <strong>&euro; %(total_vat)m</strong>',

/*
	'pp_form_start' : '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">' + 
  			  '<input type="hidden" name="cmd" value="_cart" />' + 
  			  '<input type="hidden" name="upload" value="1" />' + 
  			  '<input type="hidden" name="business" value="seller_1230827981_biz@gmail.com" />' + 
  			  '<input type="hidden" name="currency_code" value="EUR" />' + 
  			  '<input type="hidden" name="rm" value="2" />' + 
  			  '<input type="hidden" name="lc" value="IT" />' + 
  			  '<input type="hidden" name="custom" value="%(order_code)s" />' + 
  			  '<input type="hidden" name="handling_1" value="%(shipping_cost)s"">' + 
			  '<input type="hidden" name="cancel_return" value="%(_cancel)s" />' + 
  			  '<input type="hidden" name="return" value="%(_confirm)s" />' + 
  			  '<input type="hidden" name="no_note" value="1">',
*/
	'pp_form_start' : '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">' + 
  			  '<input type="hidden" name="cmd" value="_cart" />' + 
  			  '<input type="hidden" name="upload" value="1" />' + 
  			  '<input type="hidden" name="business" value="info@websellers.it" />' + 
  			  '<input type="hidden" name="currency_code" value="EUR" />' + 
  			  '<input type="hidden" name="rm" value="2" />' + 
  			  '<input type="hidden" name="lc" value="IT" />' + 
  			  '<input type="hidden" name="custom" value="%(order_code)s" />' + 
  			  '<input type="hidden" name="handling_1" value="%(shipping_cost)s"">' + 
			  '<input type="hidden" name="cancel_return" value="%(_cancel)s" />' + 
  			  '<input type="hidden" name="return" value="%(_confirm)s" />' + 
  			  '<input type="hidden" name="no_note" value="1">',

	'pp_form_end' : '<input type="submit" value="PayPal" /></form>',

	'pp_form_row' : '<input type="hiddenx" name="item_name_%(_row_count)d" value="%(descr)s" />' + 
  			'<input type="hiddenx" name="item_number_%(_row_count)d" value="%(product_code)s" />' +
  			'<input type="hiddenx" name="amount_%(_row_count)d" value="%(_price)s" />' + 
  			'<input type="hiddenx" name="quantity_%(_row_count)d" value="%(quant)d" /><br />',

	'empty-cart' : '<div class="shop-empty-cart"></div>',

	'orders-start' : '<table border="0" class="report_table">' + 
			 '<tr><th>Codice</th><th>Data</th><th>Stato ordine</th><th>Importo</th><th>Azioni</th></tr>',
	'orders-row' : '<tr class="bg%(_bg)d"><td><a href="javascript:shop.order_detail(%(id_order)s)">%(code)s</a></td>' + 
		       '<td>%(created)s</td><td>%(status_descr)s</td><td>%(total_vat)m</td><td><a href="javascript:shop.order_detail(%(id_order)s)">Dettagli</a></tr>',
	'orders-end'   : '</table>',

	'od-top' : '<table border="1">' + 
		   '<tr><td class="descr">Codice ordine:</td><td>%(code)s</td><td class="descr">Data creazione</td><td>%(confirmed)s</td></tr>' + 
		   '<tr><td class="descr">Effettuato da:</td><td>%(client_name)s %(client_lastname)s</td><td class="descr">Data Pagamento</td><td>%(payed)s</td></tr>' + 
		   '<tr><td class="descr">Importo totale</td><td>%(total_vat)m</td><td class="descr">Data Spedizione</td><td>%(sent)s</td></tr>' +
		   '<tr><td class="descr">Note</td><td colspan="3">%(note)s</td></tr>',

	'od-addr' : '<tr><td colspan="4">%(_title)s</td></tr>' +
		    '<tr><td colspan="4">' + 
		    '%(addr1)s<br />%(addr2)s<br />%(cap)s %(city)s (%(prov)s)<br /><br />Tel: %(tel)s' + 
		    '</td></tr>',
	'od-prods' : '<tr><td colspan="4">Elenco Prodotti</td></tr><tr><td colspan="4">' + 
		    '<table><tr><th>Sito</th><th>Codice</th><th>Prodotto</th><th>Quant.</th><th>Prezzo</th><th>Sc.%</th><th>Totale</th></tr>',
	'od-prod-row' : '<tr><td>%(site_name)s</td><td>%(product_code)s</td><td>%(descr)s</td><td>%(quant)s</td><td>%(real_vat)m</td><td>%(discount)s</td><td>%(total_vat)m</td></tr>',
	'od-prods-end' : '</table></td></tr>'
};
shop.home.templates = {
	'home' : '<div id="shop_home"><table border="0" width="100%">' + 
		 '<tr><td><div class="user" title="Gestione utente" onclick="user.change_password()"></div></td><td class="descr">Gestione utente</td>' + 
		 '    <td><div class="orders" title="I tuoi ordini" onclick="shop.list_orders()"></div></td><td class="descr">I tuoi ordini</td></tr>' + 
		 '<tr><td><div class="address" title="Gestione indirizzi"></div></td><td class="descr">Gestione indirizzi</td>' + 
		 '    <td><div class="rma" title="Richiesta RMA" onclick="rma.home()"></div></td><td class="descr">Richieste RMA</td></tr>' + 
	         '</table></div>'
};
var client = {};

client.id_addr_sped = 0;
client.id_addr_fatt = 0;
client.addr_mode = null;
client.addrs = [];

client.render_id = 'block_main';

client.login = function ()
{
	liwe.AJAX.easy (  { action: "shop.ajax.client_get_data" }, 
		function ( v ) 
		{
			if ( v [ 'uid' ] > 0 )
				client.add ( v [ 'uid' ], v );
			else
				client._login ();
		} );
};

client._login = function ()
{
	var f = new liwe.form.instance ( 'login' );

	$ ( client.render_id ).innerHTML = client.templates [ 'frm_enter' ];

	client._create_login_frm ( f );
};

client._create_login_frm = function ( f )
{
	f.email    ( { 'name': 'email', 'label': "E-Mail", 'mandatory': true, 'validator': true } );
	f.password ( { 'name': "pwd", 'label': "Password", 'size': 20, 'maxlength': 32, 'mandatory': true } );

	f.button ( { 'value': 'Login', onclick: "client.check_login()" } );

	f.set ( 'cnt_frm_login' );
};

client.check_login = function ()
{
	var f = liwe.form.get ( "login" );
	var a = f.get_values ();

	a [ 'action' ] = "shop.ajax.check_login";
	
	liwe.AJAX.easy ( a, function ( v ) {
		if ( v [ 'uid' ] )
			client.add ( v [ 'uid' ], v );
	} );
};

client.add = function ( uid, vals )
{
	$( client.render_id ).innerHTML = String.formatDict ( client.templates [ 'user_add' ], client.testi );

	var f = new liwe.form.instance ( 'user' );

	client._create_add_frm ( f, uid, vals );
};

client._create_add_frm = function ( f, uid, vals )
{
	var lbl = '';

	if ( ! vals ) vals = {};

	if ( ! uid )
	{
		lbl = String.formatDict ( client.templates [ 'frm_title' ], { txt: "Nuova Registrazione", img: 'nuova_registrazione' } );
	} else {
		lbl = String.formatDict ( client.templates [ 'frm_title' ], { txt: "Modifica i tuoi dati", img: 'tuoi_dati' } );
		f.hidden ( 'uid', uid );
	}

	$ ( 'frm_header' ).innerHTML = lbl;

	//f.descr    ( { text: lbl } );
	if ( ! uid )
	{
		f.email    ( { 'name': 'email', 'label': "E-Mail", 'mandatory': true, 'validator': true } );
		f.email    ( { 'name': 'email2', 'label': "E-Mail ( conferma )", 'mandatory': true, 'validator': true } );
	
		f.password ( { 'name': "pwd", 'label': "Password", 'size': 20, 'maxlength': 32, 'mandatory': ( uid ? false : true ) } );
		f.password ( { 'name': "pwd2", 'label': "Password ( conferma )", 'size': 20, 'maxlength': 32, 'mandatory': ( uid ? false : true ) } );
	}

	f.text     ( { 'name': "name", 'label': "Nome", 'size': 40, value: vals.get ( "name", "" ), 'maxlength': 120, 'mandatory': true } );
	f.text     ( { 'name': "lastname", 'label': "Cognome", 'size': 40, value: vals.get ( "lastname", "" ), 'maxlength': 120, 'mandatory': true } );


	f.cod_fisc ( { 'name': "cod_fisc", 'label': "Cod. Fisc.", 'size': 20, 'maxlength': 16, value: vals.get ( "cod_fisc", "" ), validator: true } );
	f.p_iva ( { 'name': "p_iva", 'label': "P. IVA", 'size': 20, 'maxlength': 11, value: vals.get ( "p_iva", "" ), validator: true } );

	f.button ( { 'value': 'Continua &gt;&gt;', onclick: "client.check_add()" } );

	f.set ( 'frm_user' );
};

client.check_add = function ()
{
	var f = liwe.form.get ( 'user' );
	var dict = f.get_values ();

	if ( ! f.check () ) return;

	if ( dict.pwd != dict.pwd2 )
	{
		$ ( 'err_msg' ).innerHTML = 'Attenzione! Le Password non coincidono';
		$ ( 'err_msg' ).style.display = 'block';
		return;
	}

	if ( dict.email && dict.email != dict.email2 )
	{
		$ ( 'err_msg' ).innerHTML = 'Attenzione! Le E-Mail non coincidono';
		$ ( 'err_msg' ).style.display = 'block';
		return;
	}

	if ( ( ! dict.cod_fisc ) && ( ! dict.p_iva ) )
	{
		$ ( 'err_msg' ).innerHTML = 'Attenzione! Inserire Codice fiscale e/o Partita IVA';
		$ ( 'err_msg' ).style.display = 'block';
		return;
	}

	$ ( 'err_msg' ).innerHTML = '';
	$ ( 'err_msg' ).style.display = 'none';

	dict [ 'action' ] = "shop.ajax.client_create";

	liwe.AJAX.easy ( dict, function ( v ) {
		client.read_addrs ( v [ 'uid' ], client.select_addr );
	} );
};

client.read_addrs = function ( uid, cback )
{
	liwe.AJAX.easy ( { action: "shop.ajax.client_list_data", uid: uid }, 
		function ( v )
		{
			if ( v [ 'addrs' ] )
				client.addrs = v [ 'addrs' ];
			else
				client.addrs = [];

			client.id_payment_meth = v [ 'id_payment_meth' ];
			client.id_ship_kind = v [ 'id_ship_kind' ];

			if ( cback ) cback ();
		} );
};

client.select_addr = function ( mode )
{
	var title = "Indirizzo per la Spedizione";
	var s = '';
	var curr_id = client.id_addr_sped;
	var func_name = '';
	var templ = "ind_sped";
	var _ind;

	if ( ! mode ) mode = "sped";

	if ( mode == "fatt" )
	{
		title = "Indirizzo per la Fatturazione";
		curr_id = client.id_addr_fatt;
		func_name = "select_payment()";
		templ = "ind_fatt";
	} else 
		func_name = "select_addr('fatt')";

	client.addr_mode = mode;

	_ind = String.formatDict ( client.testi [ templ ], client.testi );

	s = String.formatDict ( client.templates [ 'addr_form' ], { _ind: _ind, title: title, mode: mode, ind_select: client.testi [ 'ind_select' ] } );
	$( client.render_id).innerHTML = s;

	// Se l'utente non ha indirizzi associati, mostro la form
	if ( ! client.addrs || ! client.addrs.length )
	{
		client._show_addr_form ();
		return;
	}

	curr_id = client._populate_addr_box ( curr_id );

	if ( client.addrs.length > 1 )
		client._create_select_addrs ( curr_id );

	client._set_id_addr ( curr_id );

	$( "addr_toolbar" ).innerHTML = String.formatDict ( client.templates [ 'addr_toolbar' ], { func : func_name } );

	$( "frm_addr" ).style.display = "none";
	$( "addr_select" ).style.display = "block";
	$( "addr_curr" ).style.display = "block";
};

client.select_payment = function ()
{
	var t, payments = shop._payments;
	var l = payments.length;
	var res = new String.buffer ();
	var row;

	if ( l == 1 )
	{
		client.id_payment_meth = payments [ 0 ] [ "id" ];
		liwe.AJAX.easy ( { action: "shop.ajax.set_payment", id_payment_meth: client.id_payment_meth }, function ( v ) 
			{
				client.select_shipping ();
			} );

		return;
	}

	res.add ( String.formatDict ( client.templates [ 'payment-top' ], client.testi ) );
	for ( t = 0; t < l; t ++ )
	{
		row = payments [ t ];

		res.add ( String.formatDict ( client.templates [ 'payment-row' ], row ) );
	}
	res.add ( String.formatDict ( client.templates [ 'payment-bottom' ], { cback: "client._sel_payment()" } ) );

	$( "block_main", res.toString () );
};

client._sel_payment = function ()
{
	var f = Array.fromForm ( "shop-payment-form" );
	
	if ( typeof f [ 'payment' ] == 'undefined' )
	{
		alert ( "Selezionare un elemento dalla lista" );
		return;
	}

	client.id_payment_meth = f [ 'payment' ];

	liwe.AJAX.easy ( { action: "shop.ajax.set_payment", id_payment_meth: client.id_payment_meth }, 
		function ( v ) 
		{
			client.select_shipping ();
		} );
};

client.select_shipping = function ()
{
	liwe.AJAX.easy ( { action: "shop.ajax.list_shippings", tot_vat: shop._total_vat }, function ( v )
		{
			var t, shippings = v [ 'shippings' ];
			var l = shippings.length;
			var res = new String.buffer ();
			var row;

			if ( l == 1 )
			{
				client.id_shipping_kind = shippings [ 0 ] [ "id_ship" ];
				liwe.AJAX.easy ( { action: "shop.ajax.set_shipping", id_shipping_kind: client.id_shipping_kind }, function ( v ) 
					{
						client._confirm ();
					} );

				return;
			}

			res.add ( client.templates [ 'payment-top' ] );
			for ( t = 0; t < l; t ++ )
			{
				row = shippings [ t ];

				row [ 'id' ] = row [ 'id_ship' ];
				row [ 'title' ] = row [ 'ship_descr' ];
				row [ '_cost' ] = Money.fromLongInt ( row [ 'cost' ] ).toString ();
					
				res.add ( String.formatDict ( client.templates [ 'payment-row' ], row ) );
			}
			res.add ( client.templates [ 'payment-bottom' ] );

			$( "block_main", res.toString () );
		}
	);
	
};


client._confirm = function ()
{
	liwe.AJAX.easy ( { action: "shop.ajax.list_products" }, function ( v )
		{
			shop._last_req = v;
			shop._format_small ( v );
			client._confirm2 ();
		} );


};

client._confirm2 = function ()
{
	var s = String.formatDict ( client.templates [ 'confirm' ], client.testi );

	$( client.render_id ).innerHTML = s;

	client._fill_final_addr ( "addr_sped", client.id_addr_sped, "sped" );
	client._fill_final_addr ( "addr_fatt", client.id_addr_fatt, "fatt" );

	// _create_details ( action, no_modify )
	$( "shop_details" ).innerHTML = shop._create_details ( null, true );
};

client._populate_addr_box = function ( curr_id )
{
	var s = '';
	var t, l = client.addrs.length;
	var addr;

	for ( t = 0; t < l; t ++ )
	{
		addr = client.addrs [ t ];
		if ( addr [ 'id_addr' ] == curr_id )
			break;
	}

	if ( ! addr [ 'addr2' ] ) addr [ 'addr2' ] = '';

	s = String.formatDict ( client.templates [ 'addr_box' ], addr );

	$( "addr_curr" ).innerHTML = s;

	return addr [ 'id_addr' ];
};

client._create_select_addrs = function ( curr_id )
{
	var s = '<select onchange="client._set_addr(this)">';
	var t, l = client.addrs.length;
	var addr;

	

	for ( t = 0; t < l; t ++ )
	{
		addr = client.addrs [ t ];
		
		if ( ! addr [ 'addr2' ] ) 
			addr [ '_addr2' ] = '';
		else
			addr [ '_addr2' ] = addr [ 'addr2' ] + " / ";
			
		if ( addr [ 'id_addr' ] == curr_id )
			addr [ '_selected' ] = 'selected="selected"';
		else
			addr [ '_selected' ] = '';

		s += String.formatDict ( client.templates [ 'addr_line' ], addr );
	}

	s += '</select>';

	$( "addr_select" ).innerHTML = s;
};

client._set_id_addr = function ( id_addr )
{
	if ( client.addr_mode == "fatt" )
		client.id_addr_fatt = id_addr;
	else
		client.id_addr_sped = id_addr;

};

client._set_addr = function ( el )
{
	client._set_id_addr ( el.value );
	client._populate_addr_box ( el.value );
};

//{{{ _show_addr_form ()
client._show_addr_form = function ()
{
	liwe.AJAX.easy ( { 'action': 'shop.ajax.client_addr_prov_list' }, function ( v ) {
		client._prov_sel = client._build_sel_prov_list ( v.get ( 'prov_list', [] ) );
		client._mk_addr_frm ( { 'prov_list': client._prov_sel } );

		// client._set_disabled ( 'addr', [ "citta", "cap" ] );
	} );
};
//}}}
//{{{ _set_disabled ( arr )
client._set_disabled = function ( frm_name, arr )
{
	var f = liwe.form.get ( frm_name );
	var t, l = arr.length;
	var el;

	for ( t = 0; t < l; t ++ )
	{
		el = f.get_element ( arr [ t ] );
		if ( el ) el.disabled = true;
	}
};
//}}}
//{{{ _mk_addr_frm ( dct )
client._mk_addr_frm = function ( dict )
{
	var f = new liwe.form.instance ( "addr" );

	f.text ( { name: "addr1", label: "Indirizzo 1", mandatory: true, maxlength: 200, size: 50, value: dict.get ( 'addr1', '' ) } );
	f.text ( { name: "addr2", label: "Indirizzo 2", mandatory: false, maxlength: 200, size: 50, value: dict.get ( 'addr2', '' ) } );
	f.text ( { name: "tel", label: "Telefono", maxlength: 15, size: 12 } );

	f.select ( { name: "prov", label: "Provincia", mandatory: true, options: dict.get ( 'prov_list', [] ), force_select: true, onchange: 'client.change_prov(this)', value: dict.get ( 'prov', '' ) } );

	if ( dict.get ( "prov" ) )
		f.select ( { name: "citta", label: "Citt&agrave;", mandatory: true, options: dict.get ( 'comu_list', [] ), force_select: true, onchange: 'client.change_comu(this)', value: dict.get ( 'citta', '' ) } );

	if ( dict.get ( "citta" ) )
	{
		f.select ( { name: "cap", label: "CAP", mandatory: true, options: dict.get ( 'cap_list', [] ), value: dict.get ( 'cap', '' ) } );
	
		f.button ( { value: "Inserisci", onclick: "client._addr_add()" } );
	}
		
	f.set ( "frm_addr" );

	$( "frm_addr" ).style.display = "block";
	$( "addr_select" ).style.display = "none";
	$( "addr_curr" ).style.display = "none";
};
//}}}
//{{{ change_prov ( elem )
client.change_prov = function ( el )
{
	if ( ! el.value ) return;
	var f = liwe.form.get ( 'addr' );

	client._set_disabled ( 'addr', [ "citta", "cap" ] );

	var dict = f.get_values ();

	dict [ 'prov' ] = el.value;
	dict [ 'prov_list' ] = client._prov_sel;

	liwe.AJAX.easy ( { 'action': 'shop.ajax.client_addr_comune_search', 'prov': el.value }, function ( v ) {
		client._comu_sel = client._build_sel_comu_list ( v.get ( 'comu_list', [] ) );
		dict [ 'comu_list' ] = client._comu_sel;
		client._mk_addr_frm ( dict );
		client._set_disabled ( 'addr', [ "cap" ] );
	} );
};
//}}}
//{{{ change_comu ( elem )
client.change_comu = function ( el )
{
	if ( ! el.value ) return;

	var f = liwe.form.get ( 'addr' );

	client._set_disabled ( 'addr', [ "cap" ] );

	var dict = f.get_values ();
	dict [ 'prov' ] = f.get_element ( 'prov' ).value;
	dict [ 'prov_list' ] = client._prov_sel;
	dict [ 'citta' ] = el.value;
	dict [ 'comu_list' ] = client._comu_sel;

	liwe.AJAX.easy ( { 'action': 'shop.ajax.client_addr_cap_search', 'prov': dict [ 'prov' ], 'comu': el.value }, function ( v ) {
		client._cap_sel = client._build_sel_cap_list ( v.get ( 'cap_list', [] ) );
		dict [ 'cap_list' ] = client._cap_sel;

		if ( client._cap_sel.length > 0 ) dict [ 'cap' ] = client._cap_sel [ 0 ];
		client._mk_addr_frm ( dict );
	} );
};
//}}}
//{{{ _build_sel_comu_list ( lst )
client._build_sel_comu_list = function ( lst )
{
	var t, l = lst.length;
	var row;
	var res = [];

	for ( t = 0; t < l; t ++ )
	{
		row = lst [ t ];
		res.push ( { label: row.comu_cap, value: row.comu_cap } );
	}

	return res;
};
//}}}
//{{{ _build_sel_cap_list ( lst )
client._build_sel_cap_list = function ( lst )
{
	var t, l = lst.length;
	var row;
	var res = [];

	for ( t = 0; t < l; t ++ )
	{
		row = lst [ t ];
		res.push ( { label: row.capi_cap +  ' ' + row.fraz_cap, value: row.capi_cap } );
	}

	return res;
};
//}}}
//{{{ _build_sel_prov_list ( lst )
client._build_sel_prov_list = function ( lst )
{
	var t, l = lst.length;
	var row;
	var res = [];

	for ( t = 0; t < l; t ++ )
	{
		row = lst [ t ];
		res.push ( { label: row.cod_prov, value: row.cod_prov } );
	}

	return res;
};
//}}}

client._confirm_enable = function ( checked )
{
	$( "btn_confirm" ).disabled = ! checked;
};

client._fill_final_addr = function ( dest_div, id_addr, mode )
{
	var t, l = client.addrs.length;
	var addr;
	var s;

	for ( t = 0; t < l; t ++ )
	{
		addr = client.addrs [ t ];
		if ( addr [ 'id_addr' ] == id_addr )
		{
			s = String.formatDict ( client.templates [ 'addr_box' ], addr );
			$( dest_div ).innerHTML = s + '<br /><br /><a href="javascript:client.select_addr(\'' + mode + '\')"><img border="0" src="/gfx/btn_modifica.gif" alt="Modifica" /></a><br />';
			break;
		}
	}
};

client._addr_add = function ()
{
	var f = liwe.form.get ( "addr" );
	var vals = f.get_values ()

	if ( ! f.check () ) return;

	vals [ 'action' ] = "shop.ajax.client_addr_add";
	liwe.AJAX.easy ( vals, 
		function ( v )
		{
			client.addrs = v [ 'addrs' ];

			if ( client.addr_mode == "sped" )
				client.id_addr_sped = v [ "addr_id" ];
			else
				client.id_addr_fatt = v [ "addr_id" ];

			client.select_addr ( client.addr_mode );
		} );
		
};

client._confirm_send = function ()
{
	$( "btn_confirm" ).disabled = 'true';

	shop.complete_order ( $v ( 'note' ), client.id_addr_sped, client.id_addr_fatt );


};

client.send_email = function ()
{
	var a = {};

	a [ 'to' ] = $ ( 'to' ).value;
	a [ 'from' ] = $ ( 'from' ).value;
	a [ 'sub' ] = $ ( 'subject' ).value;
	a [ 'txt' ] = $ ( 'testo' ).value;

	if ( ! a.to || ! a.sub || ! a.txt || ! a.from )
	{
		alert ( 'Valorizzare tutti i campi' );
		return;
	}

	if ( ! liwe.validators.is_email ( a.from ) )
	{
		alert ( 'La tua email non e\' corretta' );
		return;
	}

	a [ 'action' ] = "client.send_email";

	show_wait (true);

	liwe.AJAX.easy ( a, 
		function ( v )
		{
			console.debug ( v );
			show_wait ();
			alert ( "Grazie, la tua email e' stata inviata con successo!" );
			document.location = "/";
		} );
};
client.templates = {
'frm_enter_sx' : '<div id="cnt_frm_enter_sx"><div id="cnt_frm_login"></div><div id="err_msg"></div></div>',
'frm_enter_dx' : '<div id="cnt_frm_enter_dx"><a href="javascript:client.add()">Sei un nuovo utente? Registrati adesso!</a></div>',
'frm_title'    : '<div class="frm_title"><div class="%(img)s" alt="%(txt)s" title="%(txt)s"></div></div>',
'user_add'     : '<div id="cnt_frm_user_add"><div id="frm_header"></div><div id="info_box">%(dati_utente)s</div><div id="frm_user"></div><div id="err_msg"></div></div>',
'addr_form'    : '<div id="cnt_frm_addr_select"><div id="frm_header"><div class="indirizzo_%(mode)s" alt="%(title)s" title="%(title)s"></div></div>' +
		 '<div id="info_box">%(_ind)s<br />%(ind_select)s</div>' +
		 '<div id="addr_curr"></div>' + 
		 '<div id="addr_select"></div><div id="frm_addr"></div>' +
		 '<div id="addr_toolbar"></div></div>',

'addr_box'     : '%(addr1)s<br />%(addr2)s<br />%(cap)s %(city)s (%(prov)s)<br />Tel.: %(tel)s',
'addr_line'    : '<option value="%(id_addr)s" %(_selected)s>%(addr1)s / %(_addr2)s%(cap)s %(city)s (%(prov)s)</option>',
'addr_toolbar' : '<table border="0" width="100%"><tr><td><button onclick="client._show_addr_form()">Nuovo indirizzo</button></td>' +
		 '<td width="100%" align="right"><button onclick="client.%(func)s">Continua &gt;&gt;</button></td></tr></table>',
'confirm'      : '<div id="info_box">%(conferma)s</div>' +
		'<table border="0" width="100%" cellpadding="5" cellspacing="5">' +
		'<tr><td colspan="2"><div id="shop_details"></div></td></tr>'+ 
		'<tr><td><h3>Indirizzo di <em>Spedizione</em></h3>' + 
		'	<div id="addr_sped"></div></td>' + 
		'   <td><h3>Indirizzo di <em>Fatturazione</em></h3>' +
		'   <div id="addr_fatt"></div></td></tr>' + 
		'<tr><td colspan="2" valign="top">' +
		'	<table  border="0" width="100%">' +
		'		<tr><td valign="top"><b>Note</b></td><td><textarea rows="6" cols="50" id="note" name="note"></textarea></td></tr>' +
		'	</table>' +
		'</td></tr>' +
		'<tr><td colspan="2"><div id="warn_box">%(warning)s</div></td></tr>' +
		'<tr><td align="center"><a href="/regole_ordini" target="_blank"><b>Condizioni dell\'ordine</b></a> &nbsp; <input type="checkbox" onclick="client._confirm_enable(this.checked)" /> <b>Accetto</b></td>' + 
		'<td align="center"><button id="btn_confirm" onclick="client._confirm_send()" disabled="true">Invia Ordine</button></td></tr>' + 
		'</table>',

'payment-top'  : '<div id="info_box">%(tipo_pag)s</div><table id="shop-payment-form" border="0"><tr><th></th><th>Descrizione</th></tr>',
'payment-row'  : '<tr><td><input type="radio" name="payment" value="%(id)s" /></td><td>%(title)s</td></tr>',
'payment-bottom'  : '<tr><td colspan="2" align="center"><input type="button" onclick="%(cback)s" value="Seleziona" /></td></tr></table>'

};

client.templates [ 'frm_enter' ] = '<div id="cnt_frm_enter"><table border="0" class="products" width="98%"><tr><th style="font-size: 110%;"  align="center">Utente Registrato</th>' +
		 '<th style="font-size: 110%;"  align="center">Utente non registrato</th></tr><tr>' +
		 '<td style="white-space: nowrap; padding: 2px;" align="left">' + client.templates [ 'frm_enter_sx' ] + '</td>' +
		 '<td style="white-space: nowrap; padding: 2px;" align="center">' + client.templates [ 'frm_enter_dx' ] + '</td></tr></table></div>';
client.testi = {};

client.testi [ 'dati_utente' ] = 	'Per prima cosa, &egrave; necessario specificare i propri dati anagrafici, che saranno utilizzati ' + 
				'per la spedizione della fattura.<br />' + 
				'Nel caso di azienda, inserire nel campo <strong>Nome</strong> la parola <em>"Azienda"</em> e ' + 
				' nel campo <strong>Cognome</strong> la <em>Ragione Sociale completa</em>.<br />' + 
				' Compilare con attenzione il campo <strong>P.IVA</strong> della Partita IVA per l\'emissione della regolare fattura.';

client.testi [ 'ind_sped' ] = 'Specificare l\'indirizzo al quale dovr&agrave; essere spedita la merce ordinata.<br />' + 
			    'Ricordarsi di inserire anche un numero di telefono dove &egrave; possibile reperirvi ' + 
			    'per eventuali comunicazioni.';

client.testi [ 'ind_fatt' ] = 'Adesso &egrave; necessario inserire l\'indirizzo di fatturazione dell\'ordine.';

client.testi [ 'tipo_pag' ] = 'Selezionate il tipo di pagamento che si desidera effettuare.<br />' + 
			      '<strong>Tutti i pagamenti online sono sicuri</strong> grazie alla collaborazione di <a href="http://www.paypal.it" target="_blank">PayPal</a>.<br />' + 
			      '&nbsp;<br />' + 
			      '<strong>ATTENZIONE</strong>: i pagamenti in contrassegno prevedono un <strong>costo aggiuntivo</strong> richiestoci espressamente ' + 
			      'dal corriere. Quindi, se possibile, utilizzate un altro sistema di pagamento.';
			 

client.testi [ 'ind_select' ] = '<br />Il sistema propone il primo indirizzo disponibile per l\'utente.' + 
			      'Se avete gi&agrave; insierito pi&ugrave; indirizzi, potete selezionarne un altro dalla tendina sottostante.';


client.testi [ 'conferma' ] = 'Se i dati sotto riportati sono corretti, selezionare la checkbox <strong>Accetto</strong> ' + 
			    'delle <em>Condizioni dell\'ordine</em> e premere <strong>Invia Ordine</strong> per completare l\'ordine.';

client.testi [ 'warning' ] = '<strong>ATTENZIONE</strong><br /> Selezionando <strong>Accetto</strong> le <em>Condizioni dell\'ordine</em>' + 
			   ' e premendo <strong>Invia Ordine</strong>, ci si impegna a portare a termine con successo la transazione ' + 
			   ' economica e si accettano incondizionatamente i prezzi riportati nella tabella soprastante.';
function DataSet(a,b){DataSet._instances[a]=this;this.name=a;this.ajax=b;this.ajax_req=DataSet.ajax;this.num_rows=0;this.rows={};this.len=0;this.page=0;this.lines_per_page=10;this.from_row=0;this.to_row=0;this.curr_doc=0;this.paginator_links=10;this.templates={table_start:'<table border="1" width="100%">',table_end:"</table>",table_header:"",table_footer:"",table_row:"",prev_page:"",next_page:"",dash:" - ",next_doc:"",prev_doc:""};this.cbacks={fill_manip:null,prefetch_start:null,prefetch_end:null,fill_start:null,fill_end:null,show_results:null,row_manip:null,row_add:null,write_results:null};this._attrs={};this._form_fields=null;this._dest_div=null;this._fill_cback=null;this._init_paginator=function(){if(!window.Paginator){return null}var c=new Paginator();c.templates["pag-first"]="&lt;&lt;&lt;";c.templates["pag-first-lnk"]="javascript:DataSet.page('"+this.name+"',0)";c.templates["pag-last"]="&gt;&gt;&gt;";c.templates["pag-last-lnk"]="javascript:DataSet.page('"+this.name+"',%(_TOT_PAGES)s)";c.templates["pag-prev"]="&lt;";c.templates["pag-prev-lnk"]="javascript:DataSet.page('"+this.name+"',%(_PREV)s)";c.templates["pag-next"]="&gt;";c.templates["pag-next-lnk"]="javascript:DataSet.page('"+this.name+"',%(_CURR_PAGE)s+1)";c.templates["pag-pos"]="%(_PAGE)s";c.templates["pag-pos-lnk"]="javascript:DataSet.page('"+this.name+"',%(_NUM)s)";c.templates["pag-sep"]="|";c.templates["pag-link-space"]="";return c};this.paginator=this._init_paginator();this.set_fields=function(c){this._form_fields=c.clone();this.clear()};this.get_fields=function(){return this._form_fields};this.del_field=function(c){delete this._form_fields[c]};this.rename_field=function(d,c){this._form_fields[c]=this._form_fields[d];delete this._form_fields[d]};this.clear=function(){this.page=0;this.num_rows=0;this.from_row=0;this.to_row=this.lines_per_page;this.rows={};this.len=0;if(this._form_fields){this._form_fields._X_START_POINT=0;this._form_fields._X_PAGE=0}this._attrs={}};this.fill=function(d,c){var e=this;if(d){this._fill_cback=d}if(!this._form_fields){this._fill_cback&&this._fill_cback(this);return}if(this.cbacks.fill_start){this.cbacks.fill_start(this)}this._form_fields._X_LINES=this.lines_per_page;this.ajax_req(this.ajax,this._form_fields,function(f){e._fill_done(f,e._fill_cback,c)})};this._fill_done=function(h,d,f){var e,c=parseInt(h.lines);if(h._X_START_POINT){this.from_row=h._X_START_POINT}else{this.from_row=h.from_row}if(!this.from_row){this.from_row=0}for(e=0;e<c;e++){if(!h["row"+e]){break}h["row"+e]["ds_name"]=this.name;var i=h["row"+e];var g=i._pos;if(this.cbacks.fill_manip){this.rows[g]=this.cbacks.fill_manip.call(this,i)}else{this.rows[g]=i}}this.to_row=this.from_row+c;this.num_rows=h.rows;if(this.cbacks.fill_end){this.cbacks.fill_end(this,h)}if(d){d(this)}};this.needs_prefetch=function(d){if(d>=this.num_rows){d=this.num_rows-1}if(this.rows[d]){return false}var e=Math.floor(d/this.lines_per_page)*this.lines_per_page;var c=e+this.lines_per_page-1;if(c>=this.num_rows){c=this.num_rows-1}if(!this.rows[e]){return true}if(!this.rows[c]){return true}return false};this.prefetch=function(d,c){if(!this.needs_prefetch(d)){return c(this)}var e=Math.floor(d/this.lines_per_page)*this.lines_per_page;this._form_fields._X_START_POINT=e;if(this.cbacks.prefetch_start){this.cbacks.prefetch_start(this)}this.fill(c);return true};this.get_row=function(c){var d;if(c>=this.num_rows){return null}d=this.rows[c];return d};this.filter_date=function(f){var h=parseInt(f.replace(/[^0-9]*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/,"$1"),10);var c=parseInt(f.replace(/[^0-9]*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/,"$2"),10);var d=f.replace(/.*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/,"$3");var i=f.replace(/([^0-9]*)[0-9][0-9]*-[0-9][0-9]*-[0-9][0-9][0-9][0-9].*/,"$1");var e=f.replace(/.*[0-9][0-9]*-[0-9][0-9]*-[0-9][0-9][0-9][0-9](.*)/,"$1");if(h<10){h="0"+h}if(c<10){c="0"+c}return i+h+"/"+c+"/"+d+e};this.render=function(c,d){var e=this;if(!c){c=this._dest_div}this._dest_div=c;this.prefetch(this.from_row,function(f){e._render_done(c,d)})};this._render_done=function(d,e){var c="";this._prepare_pagination();c=this.to_string();if(this.cbacks.write_results){this.cbacks.write_results(c)}else{$(d).innerHTML=c}if(!e){e=this.cbacks.show_results}if(e){e(this)}};this.refresh=function(c){this._form_fields._X_START_POINT=this.from_row;this.fill(c,true)};this.to_string=function(){var e=new String.buffer();var d,f;var c;e.add(String.formatDict(this.templates.table_start,this._attrs));e.add(String.formatDict(this.templates.table_header,this._attrs));for(d=this.from_row;d<this.to_row;d++){f=this.get_row(d);if(!f){continue}if(d>this.num_rows){break}f.ds_name=this.name;f._ds_row_num=d;f._ds_bg=d%2;if(this.cbacks.row_manip){this.cbacks.row_manip(this,f)}c=String.formatDict(this.templates.table_row,f);e.add(c);this.cbacks.row_add&&this.cbacks.row_add(c)}e.add(String.formatDict(this.templates.table_footer,this._attrs));e.add(String.formatDict(this.templates.table_end,this._attrs));return e.toString()};this._prepare_pagination=function(){var f=this.to_row-this.from_row;var e,d,c;e=this.from_row+1;d=this.to_row;c=this.num_rows;if(d>c){d=c}if(c<=this.lines_per_page){this._attrs.docs_shown=d}else{this._attrs.docs_shown=e+" - "+d+" di "+c}this._attrs.from_row=e;this._attrs.to_row=d;this._attrs.num_rows=c;if(this.page){this._attrs._prev_page="javascript:DataSet.page('"+this.name+"',"+(this.page-1)+")"}else{this._attrs._prev_page=null}if(this.to_row<this.num_rows){this._attrs._next_page="javascript:DataSet.page('"+this.name+"',"+(this.page+1)+")"}else{this._attrs._next_page=null}if(this._attrs._prev_page){this._attrs.prev_page=String.formatDict(this.templates.prev_page,this._attrs)}else{this._attrs.prev_page="&nbsp;"}if(this._attrs._next_page){this._attrs.next_page=String.formatDict(this.templates.next_page,this._attrs)}else{this._attrs.next_page="&nbsp;"}if(this.page&&(this.to_row<this.num_rows)){this._attrs.dash=this.templates.dash}else{this._attrs.dash=""}if(this.paginator){this.paginator.init(this.num_rows,this.lines_per_page,this.paginator_links);this.paginator.set_page(this.page);this._attrs.paginator=this.paginator.mk_str()}else{this._attrs.paginator="Include paginator.js"}};this.show_page=function(c){this.page=c;this.from_row=this.lines_per_page*c;this.to_row=this.lines_per_page*(c+1);this.render()};this.format_str=function(c){return String.formatDict(c,this._attrs)};this.set_curr_doc=function(c){if(c===undefined){c=-1}this.curr_doc=c};this.prepare_result_navi=function(c){var d=this;if(this.curr_doc==-1){return}this.prefetch(this.curr_doc+2,function(e){d.result_navi(e,c)})};this.result_navi=function(e,c){if(this._form_fields&&this.needs_prefetch(this.curr_doc+2)){var g=this;this.prefetch(this.curr_doc+2,function(h){g.result_navi(h,c)});return}var d="";var f;if(this.curr_doc>0){f=this.rows[this.curr_doc-1];this._attrs.prev_doc=String.formatDict(this.templates.prev_doc,f)}else{this._attrs.prev_doc=null}if(this.curr_doc<this.num_rows-1){f=this.rows[this.curr_doc+1];this._attrs.next_doc=String.formatDict(this.templates.next_doc,f)}else{this._attrs.next_doc=null}if(c){c(e)}}}DataSet._instances={};DataSet.get=function(a){return DataSet._instances[a]};DataSet.page=function(b,a){var c=DataSet._instances[b];c.show_page(a)};DataSet.ajax=function(c,a,b){liwe.AJAX.request(c,a,b,true)};var Paginator=function(){var a=this;a._tot_rows=0;a._rows_per_page=0;a._page=0;a._tot_links=10;a._tot_pages=0;a._dest_id=null;a.templates={};a.templates["pag-first"]="&lt;&lt;&lt;";a.templates["pag-first-lnk"]="javascript:self._go(0)";a.templates["pag-last"]="&gt;&gt;&gt;";a.templates["pag-last-lnk"]="javascript:self._go(%(_TOT_PAGES)s)";a.templates["pag-prev"]="&lt;";a.templates["pag-prev-lnk"]="javascript:self._go(%(_PREV)s)";a.templates["pag-next"]="&gt;";a.templates["pag-next-lnk"]="javascript:self._go(%(_CURR_PAGE)s+1)";a.templates["pag-pos"]="%(_PAGE)s";a.templates["pag-pos-lnk"]="javascript:self._go(%(_NUM)s)";a.templates["pag-sep"]="|";a.templates["pag-link-space"]="";a.templates["pag-left-info"]="";a.templates["pag-right-info"]="";a.cbacks={mk_str:null};a.init=function(d,b,c){a._tot_pages=Math.ceil(d/b);a._tot_rows=d;a._rows_per_page=b;a._tot_links=(c?c:10);a.templates._TOT_PAGES=a._tot_pages;a.set_page(0)};a.set_page=function(b){if(b>a._tot_pages){b=a._tot_pages}a._page=b;a.templates._CURR_PAGE=a._page;return a.mk_str()};a.mk_str=function(){if(a.cbacks.mk_str){return a.cbacks.mk_str(a)}return a._mk_str(a)};a._mk_str=function(b){var e="";var c,f;var d=0;b.templates._NUM=b._page;b.templates._PAGE=b._page+1;e+=String.formatDict(b.templates["pag-left-info"],b.templates);if(b._page>0){e+=String.formatDict('<a href="%(pag-first-lnk)s">%(pag-first)s</a>',b.templates);e+=b.templates["pag-link-space"];b.templates._PREV=b._page-1;b.templates["_PREV-LNK"]=String.formatDict(b.templates["pag-prev-lnk"],b.templates);e+=String.formatDict('<a href="%(_PREV-LNK)s">%(pag-prev)s</a>',b.templates)}else{e+=String.formatDict("%(pag-first)s",b.templates);e+=b.templates["pag-link-space"];e+=String.formatDict("%(pag-prev)s",b.templates)}if(b._page>(b._tot_links/2)){d=b._page-(Math.floor(b._tot_links/2));if((b._tot_pages-d)<b._tot_links){d=Math.max(b._tot_pages-b._tot_links,0)}}for(c=0;c<b._tot_links;c++){f=d+c;if((f+1)>b._tot_pages){break}e+=b.templates["pag-link-space"];if(c>0){e+=b.templates["pag-sep"];e+=b.templates["pag-link-space"]}b.templates._NUM=f;b.templates._PAGE=f+1;b.templates._POS=String.formatDict(b.templates["pag-pos"],b.templates);if(f==b._page){e+=String.formatDict("%(_POS)s",b.templates)}else{b.templates["_POS-LNK"]=String.formatDict(b.templates["pag-pos-lnk"],b.templates);e+=String.formatDict('<a href="%(_POS-LNK)s">%(_POS)s</a>',b.templates)}}if((b._page+1)>=b._tot_pages){e+=b.templates["pag-link-space"];e+=String.formatDict("%(pag-next)s",b.templates);e+=b.templates["pag-link-space"];e+=String.formatDict("%(pag-last)s",b.templates)}else{e+=b.templates["pag-link-space"];b.templates["_NEXT-LNK"]=String.formatDict(b.templates["pag-next-lnk"],b.templates);e+=String.formatDict('<a href="%(_NEXT-LNK)s">%(pag-next)s</a>',b.templates);e+=b.templates["pag-link-space"];b.templates["_LAST-LNK"]=String.formatDict(b.templates["pag-last-lnk"],b.templates);e+=String.formatDict('<a href="%(_LAST-LNK)s">%(pag-last)s</a>',b.templates)}b.templates._NUM=b._page;b.templates._PAGE=b._page+1;e+=String.formatDict(b.templates["pag-right-info"],b.templates);return e};a._go=function(b){a.set_page(b);a.render()};a.render=function(b){var c;if(!b){b=a._dest_id}a._dest_id=b;c=a.mk_str();$(b).innerHTML=c}};liwe.lightbox={};liwe.lightbox.opacity=70;liwe.lightbox.fade=false;liwe.lightbox._is_show=false;liwe.lightbox._back_div=null;liwe.lightbox._front_div=[];liwe.lightbox._max_zindex=null;liwe.lightbox._max_zindex_el="div";liwe.lightbox.events={click:null,close:null};liwe.lightbox.create=function(g,b,d,a,f){var c=liwe.lightbox._add_back_div();var e=liwe.lightbox._add_front_div(g,b,d,a,f);return e};liwe.lightbox.created=function(){return liwe.lightbox._back_div!=null};liwe.lightbox.close=function(){var a;a=liwe.lightbox._front_div.pop();liwe.dom.remove_element(a);if(liwe.lightbox.events.close){liwe.lightbox.events.close()}liwe.dom.remove_element(liwe.lightbox._back_div);liwe.lightbox._back_div=null};liwe.lightbox.show=function(){var a=liwe.lightbox._front_div[liwe.lightbox._front_div.length-1];liwe.fx.set_opacity(liwe.lightbox._back_div,liwe.lightbox.opacity);liwe.lightbox._back_div.style.display="block";if(liwe.lightbox.fade){liwe.fx.set_opacity(a,0);a.style.display="block";liwe.fx.fade_in(a)}else{liwe.fx.set_opacity(a,100)}};liwe.lightbox.easy=function(i,e,b,d,a,g){var f=liwe.lightbox.create(i+"_win",b,d,a,g);var c;f.className="lightbox_easy";c='<div class="title">'+e;c+='<div class="close" onclick="liwe.lightbox.close()"></div></div><div id="'+i+'"></div>';f.innerHTML=c;liwe.lightbox.show()};liwe.lightbox._add_back_div=function(){var c=liwe.lightbox._back_div;var b=(!liwe.lightbox._max_zindex)?liwe.lightbox._get_highest_zindex():liwe.lightbox._max_zindex;if(!c){c=liwe.dom.create_element("div","liwe_lightbox");c.style.display="none";c.style.backgroundColor="black";liwe.lightbox._back_div=c}var a=liwe.lightbox._get_size();c.style.zIndex=b+10;c.style.width="100%";c.style.height=a.sh+"px";liwe.events.add(c,"click",liwe.lightbox._back_click);return c};liwe.lightbox._back_click=function(){if(liwe.lightbox.events.click){liwe.lightbox.events.click()}};liwe.lightbox._add_front_div=function(b,k,c,j,i){var f=liwe.lightbox._back_div;var a=liwe.dom.create_element("div",b);var g=(!liwe.lightbox._max_zindex)?liwe.lightbox._get_highest_zindex():liwe.lightbox._max_zindex;var e;k+=80;c+=80;e=this._calc_size(k,c,j,i);k=e[0];c=e[1];j=e[2];i=e[3];a.style.zIndex=g+5;a.style.width=k+"px";a.style.height=c+"px";a.style.left=j+"px";a.style.top=i+"px";liwe.lightbox._front_div.push(a);liwe.lightbox._front_div_id=b;return a};liwe.lightbox.set_size=function(b,d,a,f){var c;var e=document.getElementById(liwe.lightbox._front_div_id);if(!e){console.warning("Could not find DIV: %s",liwe.lightbox._front_div_id);return}c=this._calc_size(b,d,a,f);b=c[0];d=c[1];a=c[2];f=c[3];e.style.width=b+"px";e.style.height=d+"px";e.style.left=a+"px";e.style.top=f+"px"};liwe.lightbox._get_size=function(){var e,b,c,a;var d=document;b=Math.max(Math.max(d.body.offsetHeight,d.documentElement.offsetHeight),Math.max(d.body.clientHeight,d.documentElement.clientHeight));e=Math.max(Math.max(d.body.offsetWidth,d.documentElement.offsetWidth),Math.max(d.body.clientWidth,d.documentElement.clientWidth));c=Math.max(Math.max(d.body.scrollHeight,d.documentElement.scrollHeight),b);a=Math.max(Math.max(d.body.scrollWidth,d.documentElement.scrollWidth),e);return{bh:b,bw:e,sh:c,sw:a}};liwe.lightbox._calc_size=function(b,d,a,e){var c=liwe.lightbox._get_size();if(!b){b=0}if(!d){d=0}if(!a){a=0}if(!e){e=0}a=Math.abs(c.bw-b)/2;e=Math.abs(c.bh-d)/2;return[b,d,a,e]};liwe.lightbox._get_highest_zindex=function(){var d=liwe.lightbox._max_zindex_el;var f=0,b,e;var a=document.getElementsByTagName(d);for(var g=0;g<a.length;g++){if(a[g].currentStyle){e=a[g].currentStyle.zIndex}if(window.getComputedStyle){e=window.getComputedStyle(a[g],null).getPropertyValue("z-index")}b=parseInt(e,10);if((!isNaN(b))&&(b>f)){f=b}}return f};liwe.utils.notifier={};liwe.utils.notifier.fx=false;liwe.utils.notifier.fade_in=50;liwe.utils.notifier.fade_out=50;liwe.utils.notifier.scroll_win=true;liwe.utils.notifier.show=function(b,a){if(!a){a=liwe.utils.notifier.mode.MESSAGE}liwe.utils.notifier._show(b,a)};liwe.utils.notifier.hide=function(){if(!liwe.utils.notifier._el||liwe.utils.notifier._el.style.display!="block"){return}if(liwe.utils.notifier.fx&&liwe.fx&&liwe.fx.fade_in){liwe.fx.fade_out(liwe.utils.notifier._el,10,liwe.utils.notifier.fade_out,function(){liwe.utils.notifier._el.style.display="none"})}else{liwe.utils.notifier._el.style.display="none"}};liwe.utils.notifier.mode={ALERT:"alert",WARN:"warn",NOTICE:"notice",MESSAGE:"message",INFO:"info"};liwe.utils.notifier._el=null;liwe.utils.notifier._show=function(a,b){if(!liwe.utils.notifier._el){liwe.utils.notifier._el=document.createElement("div");document.body.insertBefore(liwe.utils.notifier._el,document.body.firstChild)}liwe.utils.notifier._el.innerHTML=a;liwe.utils.notifier._el.style.display="none";liwe.utils.notifier._el.className="liwe_notifier_"+b;if(liwe.utils.notifier.scroll_win){window.scrollTo(0,0)}if(liwe.utils.notifier.fx&&liwe.fx&&liwe.fx.fade_in){liwe.fx.set_opacity(liwe.utils.notifier._el,0);liwe.utils.notifier._el.style.display="block";liwe.fx.fade_in(liwe.utils.notifier._el,10,liwe.utils.notifier.fade_in)}else{liwe.utils.notifier._el.style.display="block"}};var MD5={};MD5.hexcase=0;MD5.b64pad="";MD5.chrsz=8;MD5.hex_md5=function(a){return MD5._binl2hex(MD5._core_md5(MD5._str2binl(a),a.length*MD5.chrsz))};MD5.b64_md5=function(a){return MD5._binl2b64(MD5._core_md5(MD5._str2binl(a),a.length*MD5.chrsz))};MD5.str_md5=function(a){return MD5._binl2str(MD5._core_md5(MD5._str2binl(a),a.length*MD5.chrsz))};MD5.hex_hmac_md5=function(a,b){return MD5._binl2hex(MD5._core_hmac_md5(a,b))};MD5.b64_hmac_md5=function(a,b){return MD5._binl2b64(MD5._core_hmac_md5(a,b))};MD5.str_hmac_md5=function(a,b){return MD5._binl2str(MD5._core_hmac_md5(a,b))};MD5.test=function(){return MD5.hex_md5("abc")=="900150983cd24fb0d6963f7d28e17f72"};MD5._core_md5=function(r,m){r[m>>5]|=128<<((m)%32);r[(((m+64)>>>9)<<4)+14]=m;var q=1732584193;var p=-271733879;var o=-1732584194;var n=271733878;var h,e=r.length;for(h=0;h<e+32;h++){if(typeof(r[h])=="undefined"){r[h]=0}}for(h=0;h<e;h+=16){var k=q;var j=p;var g=o;var f=n;q=MD5._ff(q,p,o,n,r[h+0],7,-680876936);n=MD5._ff(n,q,p,o,r[h+1],12,-389564586);o=MD5._ff(o,n,q,p,r[h+2],17,606105819);p=MD5._ff(p,o,n,q,r[h+3],22,-1044525330);q=MD5._ff(q,p,o,n,r[h+4],7,-176418897);n=MD5._ff(n,q,p,o,r[h+5],12,1200080426);o=MD5._ff(o,n,q,p,r[h+6],17,-1473231341);p=MD5._ff(p,o,n,q,r[h+7],22,-45705983);q=MD5._ff(q,p,o,n,r[h+8],7,1770035416);n=MD5._ff(n,q,p,o,r[h+9],12,-1958414417);o=MD5._ff(o,n,q,p,r[h+10],17,-42063);p=MD5._ff(p,o,n,q,r[h+11],22,-1990404162);q=MD5._ff(q,p,o,n,r[h+12],7,1804603682);n=MD5._ff(n,q,p,o,r[h+13],12,-40341101);o=MD5._ff(o,n,q,p,r[h+14],17,-1502002290);p=MD5._ff(p,o,n,q,r[h+15],22,1236535329);q=MD5._gg(q,p,o,n,r[h+1],5,-165796510);n=MD5._gg(n,q,p,o,r[h+6],9,-1069501632);o=MD5._gg(o,n,q,p,r[h+11],14,643717713);p=MD5._gg(p,o,n,q,r[h+0],20,-373897302);q=MD5._gg(q,p,o,n,r[h+5],5,-701558691);n=MD5._gg(n,q,p,o,r[h+10],9,38016083);o=MD5._gg(o,n,q,p,r[h+15],14,-660478335);p=MD5._gg(p,o,n,q,r[h+4],20,-405537848);q=MD5._gg(q,p,o,n,r[h+9],5,568446438);n=MD5._gg(n,q,p,o,r[h+14],9,-1019803690);o=MD5._gg(o,n,q,p,r[h+3],14,-187363961);p=MD5._gg(p,o,n,q,r[h+8],20,1163531501);q=MD5._gg(q,p,o,n,r[h+13],5,-1444681467);n=MD5._gg(n,q,p,o,r[h+2],9,-51403784);o=MD5._gg(o,n,q,p,r[h+7],14,1735328473);p=MD5._gg(p,o,n,q,r[h+12],20,-1926607734);q=MD5._hh(q,p,o,n,r[h+5],4,-378558);n=MD5._hh(n,q,p,o,r[h+8],11,-2022574463);o=MD5._hh(o,n,q,p,r[h+11],16,1839030562);p=MD5._hh(p,o,n,q,r[h+14],23,-35309556);q=MD5._hh(q,p,o,n,r[h+1],4,-1530992060);n=MD5._hh(n,q,p,o,r[h+4],11,1272893353);o=MD5._hh(o,n,q,p,r[h+7],16,-155497632);p=MD5._hh(p,o,n,q,r[h+10],23,-1094730640);q=MD5._hh(q,p,o,n,r[h+13],4,681279174);n=MD5._hh(n,q,p,o,r[h+0],11,-358537222);o=MD5._hh(o,n,q,p,r[h+3],16,-722521979);p=MD5._hh(p,o,n,q,r[h+6],23,76029189);q=MD5._hh(q,p,o,n,r[h+9],4,-640364487);n=MD5._hh(n,q,p,o,r[h+12],11,-421815835);o=MD5._hh(o,n,q,p,r[h+15],16,530742520);p=MD5._hh(p,o,n,q,r[h+2],23,-995338651);q=MD5._ii(q,p,o,n,r[h+0],6,-198630844);n=MD5._ii(n,q,p,o,r[h+7],10,1126891415);o=MD5._ii(o,n,q,p,r[h+14],15,-1416354905);p=MD5._ii(p,o,n,q,r[h+5],21,-57434055);q=MD5._ii(q,p,o,n,r[h+12],6,1700485571);n=MD5._ii(n,q,p,o,r[h+3],10,-1894986606);o=MD5._ii(o,n,q,p,r[h+10],15,-1051523);p=MD5._ii(p,o,n,q,r[h+1],21,-2054922799);q=MD5._ii(q,p,o,n,r[h+8],6,1873313359);n=MD5._ii(n,q,p,o,r[h+15],10,-30611744);o=MD5._ii(o,n,q,p,r[h+6],15,-1560198380);p=MD5._ii(p,o,n,q,r[h+13],21,1309151649);q=MD5._ii(q,p,o,n,r[h+4],6,-145523070);n=MD5._ii(n,q,p,o,r[h+11],10,-1120210379);o=MD5._ii(o,n,q,p,r[h+2],15,718787259);p=MD5._ii(p,o,n,q,r[h+9],21,-343485551);q=MD5._safe_add(q,k);p=MD5._safe_add(p,j);o=MD5._safe_add(o,g);n=MD5._safe_add(n,f)}return Array(q,p,o,n)};MD5._cmn=function(h,e,d,c,g,f){return MD5._safe_add(MD5._bit_rol(MD5._safe_add(MD5._safe_add(e,h),MD5._safe_add(c,f)),g),d)};MD5._ff=function(g,f,k,j,e,i,h){return MD5._cmn((f&k)|((~f)&j),g,f,e,i,h)};MD5._gg=function(g,f,k,j,e,i,h){return MD5._cmn((f&j)|(k&(~j)),g,f,e,i,h)};MD5._hh=function(g,f,k,j,e,i,h){return MD5._cmn(f^k^j,g,f,e,i,h)};MD5._ii=function(g,f,k,j,e,i,h){return MD5._cmn(k^(f|(~j)),g,f,e,i,h)};MD5._core_hmac_md5=function(c,f){var e=str2binl(c);if(e.length>16){e=_core_md5(e,c.length*MD5.chrsz)}var a=Array(16),d=Array(16);for(var b=0;b<16;b++){a[b]=e[b]^909522486;d[b]=e[b]^1549556828}var g=MD5._core_md5(a.concat(MD5._str2binl(f)),512+f.length*MD5.chrsz);return MD5._core_md5(d.concat(g),512+128)};MD5._safe_add=function(a,d){var c=(a&65535)+(d&65535);var b=(a>>16)+(d>>16)+(c>>16);return(b<<16)|(c&65535)};MD5._bit_rol=function(a,b){return(a<<b)|(a>>>(32-b))};MD5._str2binl=function(d){var c=Array();var a=(1<<MD5.chrsz)-1;for(var b=0;b<d.length*MD5.chrsz;b+=MD5.chrsz){if(typeof(c[b>>5])=="undefined"){c[b>>5]=0}c[b>>5]|=(d.charCodeAt(b/MD5.chrsz)&a)<<(b%32)}return c};MD5._binl2str=function(c){var d="";var a=(1<<MD5.chrsz)-1;for(var b=0;b<c.length*32;b+=MD5.chrsz){d+=String.fromCharCode((c[b>>5]>>>(b%32))&a)}return d};MD5._binl2hex=function(c){var b=MD5.hexcase?"0123456789ABCDEF":"0123456789abcdef";var d="";for(var a=0;a<c.length*4;a++){d+=b.charAt((c[a>>2]>>((a%4)*8+4))&15)+b.charAt((c[a>>2]>>((a%4)*8))&15)}return d};MD5._binl2b64=function(d){var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var f="";for(var b=0;b<d.length*4;b+=3){var e=(((d[b>>2]>>8*(b%4))&255)<<16)|(((d[b+1>>2]>>8*((b+1)%4))&255)<<8)|((d[b+2>>2]>>8*((b+2)%4))&255);for(var a=0;a<4;a++){if(b*8+a*6>d.length*32){f+=b64pad}else{f+=c.charAt((e>>6*(3-a))&63)}}}return f};liwe.fx.priv={};liwe.fx.set_opacity=function(a,b){if(b>100){b=100}if(b<0){b=0}if(a.filters){if(!a.filters.alpha){a.style.filter="alpha(opacity="+b+")"}a.filters.alpha.opacity=b}else{a.style.MozOpacity=b/100;a.style.opacity=b/100}return b};var product = liwe.module ( "product", { "prod_show" : "_show" } );

// ========================================================
// CBACKS DEFINITION
// ========================================================
// 
// show ( prod ) 
// This callback is called just before the current ``prod`` is
// rendered on screen (all data has already been gathered).
product.cbacks [ 'show' ] = function ( prod ) {};

product.templates = null;
product.makers = null;

product.ds = new DataSet ( 'results' );
product.ds.paginator.templates [ "pag-link-space" ] = "&nbsp;&nbsp;";

product.init = function ()
{
	if ( ! product.templates )
	{
		product.ajax ( { action: "product.ajax.get_templates" }, function ( v ) { product.templates = v [ 'templates' ]; } );
	}

	if ( ! product.makers )
	{
		product.ajax ( { action: "product.ajax.list_makers" }, function ( v ) { product.makers = v [ 'makers' ]; } );
	}
};

product.show_latest = function ()
{
	if ( ! $( "product-latest" ) ) return;
	liwe.AJAX.easy ( { action: "product.ajax.list_latest" }, function ( v ) { product._format_box ( v, "Ultimi Arrivi", "product-latest", "latest" ); } );
};

product.show_discount = function ()
{
	if ( ! $( "product-discount" ) ) return;
	liwe.AJAX.easy ( { action: "product.ajax.list_discount" }, function ( v ) { product._format_box ( v, "I Pi&ugrave; Scontati", "product-discount", "discount" ); } );
};

product.show_future = function ()
{
	if ( ! $( "product-future" ) ) return;
	liwe.AJAX.easy ( { action: "product.ajax.list_future" }, function ( v ) { product._format_box ( v, "Prossime Uscite", "product-future", "future" ); } );
};

product._format_box = function ( v, title, dest_div, mode )
{
	var box = new NewsBox ( "nb_" + mode );
	var t, prods = v [ 'products' ], l = prods.length;
	var s = String.formatDict ( product.templates [ 'box-head' ], { "title" : title } );

	box.rows_to_show = 5;
	box.steps = 20;
	box.title = title;

	for ( t = 0; t < l; t ++ )
	{
		prods [ t ] [ '_row_bg' ] = t % 2;
		box.add ( String.formatDict ( product.templates [ 'box-row' ], prods [ t ] ) );
	}

	box.footer = String.formatDict ( product.templates [ 'box-footer' ], { mode: mode, descr: "Mostra tutti", code: "" } );
	
	box.render ( dest_div );

	// $( dest_div ).innerHTML = s;
};

product._show = function ( data ) {
	if ( ! product.templates ) 
		setTimeout ( function () { product._show ( data ); }, 100 );
	else
		product.show ( data [ 'product_code' ] );
};

product.show = function ( prod_code )
{
	product.set_history ( "prod_show", product._show, { "product_code" : prod_code } );

	liwe.AJAX.easy ( { action: "product.ajax.show_product", product_code: prod_code }, function ( v ) {
				var prod = v [ 'product' ];


				prod [ 'price_vat' ] = parseInt ( prod [ 'price_vat' ], 10 );
				prod [ 'price_net' ] = parseInt ( prod [ 'price_net' ], 10 );
				prod [ 'discount' ] = parseInt ( prod [ 'discount' ], 10 );

				prod [ '_add_cart' ] = product._add_cart ( prod, 'add-cart' );
				prod [ '_add_cart_small' ] = product._add_cart ( prod, 'add-cart-small' );

				prod [ '_cart_box' ] = product._cart_box ( prod );

				media_manager.set_items ( prod );
				
				product._handle_media ( prod, v );

				if ( prod [ 'future' ] )
					prod [ '_future' ] = String.formatDict ( product.templates [ 'product-future' ], prod );
				else
					prod [ '_future' ] = '';

				// Call user-defined callback	
				product.cbacks [ 'show' ] ( prod );

				$( "block_main", String.formatDict ( product.templates [ "product" ], prod ) );

				if ( prod [ 'discount' ] )
				{
					$( "product-discount", "- " + prod [ 'discount' ] + "%" )
					$( "product-discount" ).parentNode.style.display = "block";
				}
			} );
};

product._handle_media = function ( prod, v )
{
	var items = media_manager.get_items_list ( "product", prod [ 'code' ] );
	var t, l = items.length, item, found;

	for ( t = 0; t < l; t ++ )
	{
		item = items [ t ];
		if ( item.data [ 'kind' ] == 'image' )
		{
			found = item;
			break;
		}
	}	

	if ( found )
		prod [ '_img' ] = found.preview ( "small" );
	else
		prod [ '_img' ] = "no image";

	prod [ '_mm_panel' ] = media_manager.panel ( items );
};

product._cart_box = function ( prod )
{
	var s = String.formatDict ( product.templates [ 'cart-box-start' ], prod );

	prod [ '_vat' ] = prod [ 'price_vat' ] - prod [ 'price_net' ];
	
	if ( prod [ 'discount' ] )
	{
		s += String.formatDict ( product.templates [ 'cart-row-discount' ], prod );
	} else 
		s += String.formatDict ( product.templates [ 'cart-row' ], prod );

	if ( prod [ 'future' ] )
		s += String.formatDict ( product.templates [ 'cart-future' ], prod );

	s += String.formatDict ( product.templates [ 'cart-box-end' ], prod );

	return s;
};

product._list_prods = function ( data )
{
	product.list_products ( data [ 'mode' ], data [ 'code' ], data [ 'descr' ] );
};

product.list_products = function ( mode, code, descr )
{
	product.set_history ( "list_prods", product._list_prods, { "code" : code, "mode" : mode, "descr" : descr } );

	product.ds.templates [ 'table_start' ] = String.formatDict ( product.templates [ 'ds-table-start' ], { "_title": descr } );
	product.ds.templates [ 'table_header' ] = product.templates [ 'ds-table-head' ];
	product.ds.templates [ 'table_footer' ] = product.templates [ 'ds-table-foot' ];
	product.ds.templates [ 'table_row' ] = product.templates [ 'ds-row-product' ];
	product.ds.set_fields ( { action: "product.ajax.list_products", mode: mode, code: code, count: 1 } );

	product.ds.cbacks [ 'row_manip' ] = function ( ds, row )
	{
		if ( row [ 'discount' ] )
			row [ '_discount_small' ] = String.formatDict ( product.templates [ 'discount-small' ], row );
		else	
			row [ '_discount_small' ] = '';

		/*row [ '_img' ] = String.formatDict ( product.templates [ 'product-box-img' ], row [ 'media' ] [ 0 ] ); */
		row [ '_add_cart_small' ] = product._add_cart ( row, 'add-cart-small' );
	};

	product.ds.fill ( function () { product.ds.render ( 'block_main' ); } );
};

product._add_cart = function ( prod, template )
{
	return String.formatDict ( product.templates [ template ], prod );
};

product._parse_list = function ( data, templ_name, join_str )
{
	var t, l = data.length;
	var arr = [];
	var templ = product.templates [ templ_name ];

	join_str = join_str || ', ';

	for ( t = 0; t < l; t ++ )
		arr.push ( String.formatDict ( templ, data [ t ] ) );

	return join_str.join ( arr );
};



/*
product.event_dispatch = function ( dict, data )
{
	var page = dict.get ( '_page' );

	switch ( page )
	{
		case "show":
			product.show ( dict [ 'product_code' ] );
			break;

		case "list_products":
			product.list_products ( dict [ 'mode' ], dict [ 'code' ], dict [ 'descr' ] );
			break;


		default:
			console.error ( "product-dispatch" )
			console.error ( dict );
	}
};

liwe.history.set_listener ( product.event_dispatch, 'product' );
*/
product.search = {};

product.search.ds = new DataSet ( 'product-search' );
product.search.ds.paginator.templates [ "pag-link-space" ] = "&nbsp;&nbsp;";

product.search._form_data = {};

product.search.init = function ()
{
/*
	if ( ! $( "product-search" ) ) return;

	var frm = product.templates [ 'search-box' ];
	
	$( "product-search" ).innerHTML = frm;
*/
	product.search._render_form ();
	product.search._ds_init ();
};

product.search.start = function ()
{
	var txt = $v ( "product-search-txt" );

	if ( ! txt ) return;

	product.search._form_data [ 'name' ] = txt;

	product.search._start_search ();
};

product.search._form_start = function ()
{
	product.search._form_data = liwe.form.get ( "product-search-form" ).get_values ();
	product.search._start_search ();
};

product.search._start_search = function ()
{
	var s = '';

	product.search._form_data.iterate ( function ( v, k ) { if ( v ) s += k + ":" + v + "@"; } );

	product.search.ds.set_fields ( { action: "product.ajax.list_products", mode: "search", code: s } );
	product.search.ds.fill ( function () { product.search._render_form (); product.search.ds.render ( "product-search-list" ); } );
};

product.search._ds_init = function ()
{
	product.search.ds.templates [ 'table_start' ] = product.templates [ 'ds-search-form' ] + String.formatDict ( product.templates [ 'ds-table-start' ], { "_title": "Ricerca" } );
	product.search.ds.templates [ 'table_header' ] = product.templates [ 'ds-table-head' ];
	product.search.ds.templates [ 'table_footer' ] = product.templates [ 'ds-table-foot' ];
	product.search.ds.templates [ 'table_row' ] = product.templates [ 'ds-row-product' ];

	product.search.ds.cbacks [ 'row_manip' ] = function ( ds, row )
	{
		if ( row [ 'discount' ] )
			row [ '_discount_small' ] = String.formatDict ( product.templates [ 'discount-small' ], row );
		else
			row [ '_discount_small' ] = '';

		row [ '_add_cart_small' ] = product._add_cart ( row, 'add-cart-small' );
	};
};

product.search._render_form = function ()
{
	if ( $( "product-search-form_frm" ) ) return;

	var f = new liwe.form.instance ( "product-search-form" );

	f.text ( { label: "Titolo", name: "name", size: 20, maxlength: 100, nonl: 1, onchange: "product.search._form_start()", value: product.search._form_data.get ( "name", "" ) } );
	f.select ( { label: "Pubblicato da", name: "id_publisher", options: product.publishers, force_select: true, onchange: "product.search._form_start()" } );
	f.sep ();
	f.workspace ( { name: "product-search-list" } );

	f.set ( "block_main" );
};
function WWL(a,b){this.class_name="";this.to_string=function(){var c="",d;c='<div class="wwl_'+this.type+'"><div id="'+this.id+'" ';c+=this.mk_events();c+=' class="'+WWL.mk_class_str(this,(this._is_disabled?"disabled":null))+'">';c+=this.name;c+="</div></div>";return c};this.type=a;this.name=b;this.id=a+":"+b;this._events={};this._is_disabled=false;this._dest_id=null;this._blocked_events={};this._event_names=["over","out","btn_up","btn_down","click","dblclick","blur"];this.cbacks={"pre-render":null,render:null};this._rendered=false;this.set_event=function(d,c){this._events[d]=c};this.block_event=function(c,d){this._blocked_events[c]=d};this.send_event=function(c){WWL.evt(null,document.getElementById(this.id),c,this)};this.mk_events=function(){var f="";var e,c=this._event_names.length;var g,d;for(e=0;e<c;e++){g=this._event_names[e];d=WWL._event_remap[g];if(!d){d=g}f+=" on"+d+"=\"return WWL.evt(event,this,'"+g+"')\" "}return f};this.disable=function(c){this._is_disabled=c;this.render()};this.render=function(e){if(this.cbacks["pre-render"]&&(this.cbacks["pre-render"](this))){return}var d="",f;var c;this._rendered=false;if(!e){e=this._dest_id}if(e){this._dest_id=e;c=document.getElementById(this._dest_id);if(!c){console.error("ERROR: element with id: '"+this._dest_id+"' does not exists");return}}else{if(!this.id){console.error("ERROR: element %s does not have dest_id or this.id",this.name);return}c=document.getElementById(this.id);if(!c){return}c=c.parentNode}c.innerHTML=this.to_string();this._rendered=true;if(this.cbacks.render){this.cbacks.render(this)}};this.value=function(c){var e=document.getElementById(this.id);var d=e.value;if(c!==undefined){if(c!=d){e.value=c;this.send_event("change")}}return d};WWL._instances[a+":"+b]=this}WWL._instances={};WWL._int_events={};WWL._event_remap={over:"mouseover",out:"mouseout",btn_up:"mouseup",btn_down:"mousedown"};WWL.get_instance=function(a,b){return WWL._instances[a+":"+b]};WWL.evt=function(a,e,d,c){var b=null;if(!c){c=WWL._resolve_widget(e.id)}if(c._is_disabled){return false}if(c._blocked_events[d]){return false}if(c._events["before-"+d]){b=c._events["before-"+d](c,d,e,a)}if(c._int_events&&c._int_events[d]){c._int_events[d](c,e,a)}if(c._events[d]){b=c._events[d](c,d,e,a)}if(b===null){b=true}return b===null?true:b};WWL._resolve_widget=function(c){var b=WWL._instances[c];if(b){return b}var a=c.split(":");var d;a.pop();while(a.length){d=a.join(":");b=WWL._instances[d];if(b){return b}}return null};WWL.get_char_code=function(a){a=(a)?a:event;return(a.charCode)?a.charCode:((a.which)?a.which:a.keyCode)};WWL.get_char=function(a){var b=WWL.get_char_code(a);if(b<32){return null}return String.fromCharCode(b)};WWL.include=function(b){var a="WWL."+b;if(liwe.utils.is_def(a)){return}liwe.utils.append_js(b+".js")};WWL.mk_class_str=function(c,b){var a=(c.class_name?(c.class_name+(b?"_"+b:"")):(b?b:""));return a};WWL._libbase="";WWL.set_libbase=function(c){if(c){WWL._libbase=c;return}var a=document.getElementsByTagName("script");var b=a.length;var d,e,g,f="";for(d=0;d<b;d++){e=a[d].src;if(!e){continue}if(e.match(/wwl.js/)){g=e.lastIndexOf("/");if(g!=-1){f=e.slice(0,g+1)}}}if(f){WWL._libbase=f}else{WWL._libbase="/os3wwl"}};WWL.set_libbase();WWL.scrollbox = function ( name )
{
	var scrollbox = new WWL ( 'scrollbox', name );

	scrollbox._support_transitions = liwe.dom.supports ( "transition" );

	scrollbox._event_names = [];

	scrollbox.cbacks [ 'render' ] = function ( sbox ) { 
		scrollbox._set_content ();

		var cnt = $( scrollbox.id );

		if ( scrollbox._support_transitions )
		{
			if ( ! cnt._has_events )
			{
				cnt.addEventListener ( "transitionend", scrollbox._remove_child, false );
				cnt.addEventListener ( "webkitTransitionEnd", scrollbox._remove_child, false );
				cnt._has_events = true;
			}
		}
	};

	scrollbox._remove_child = function ( evt )
	{
		var cnt = $( scrollbox.id );

		cnt.style.MozTransition = "";
		cnt.style.WebkitTransition = "";
		cnt.style.Transition = "";

		if ( cnt._remove_last )
			cnt.removeChild ( cnt.lastChild );
		else
			cnt.removeChild ( cnt.firstChild );

		cnt.style.left = - ( scrollbox.item_width ) + "px";

		cnt._remove_last = false;

		if ( cnt._transition_cback ) cnt._transition_cback ();
		cnt._transition_cback = null;

		scrollbox._in_transition = false;
	};

	scrollbox.clear = function ()
	{
		// List of items inside scrollbox
		scrollbox._items = [ -1 ];

		// Current start position
		scrollbox._start = 0;

		scrollbox.width = 400;
		scrollbox.height = 100;

		scrollbox.item_width = 100;
		scrollbox.item_height = 100;
	};

	scrollbox.set_size = function ( w, h )
	{
		scrollbox.width = w;
		scrollbox.height = h;
	};

	scrollbox.set_item_size = function ( w, h )
	{
		scrollbox.item_width = w;
		scrollbox.item_height = h;
	};

	scrollbox.add_item = function ( html )
	{
		scrollbox._items.push ( html );
	};

	scrollbox.to_string = function ()
	{
		var s = new String.buffer ();

		scrollbox.items_to_show = Math.floor ( scrollbox.width / scrollbox.item_width );

		s.add ( '<div class="wwl_' + scrollbox.type + '" style="width: ' + scrollbox.width + 'px; height: ' + scrollbox.height + 'px">' );
		s.add ( scrollbox._render_container () );
                s.add ( '</div>' );

		return s.toString ();
	};

	scrollbox._render_container = function ()
	{
		var s = new String.buffer ();

		var container_width = ( scrollbox.items_to_show + 2 ) * scrollbox.item_width;

		s.add ( String.formatDict ( WWL.scrollbox.templates [ 'container-start' ], { 
			"container_width" : container_width + scrollbox.item_width * 2,
			"left" :  - scrollbox.item_width,
			"id" : scrollbox.id,
			"height" : scrollbox.item_height
				} ) );

		s.add ( WWL.scrollbox.templates [ 'container-end' ] );

		return s.toString ();
	};

	scrollbox._set_content = function ()
	{
		var t, l = scrollbox._items.length;
		var item, el;
		
		for ( t = 0; t < scrollbox.items_to_show + 2; t ++ )
		{
			el = scrollbox._create_element ( scrollbox._start + t );

			$( scrollbox.id ).appendChild ( el );
		}
	};

	scrollbox.move_prev = function ()
	{
		var cnt = $( scrollbox.id );
		var el;

		if ( scrollbox._in_transition ) return;
		if ( ! scrollbox.can_move_prev () ) return;

		scrollbox._in_transition = true;

		scrollbox._start -= 1;
		el = scrollbox._create_element ( scrollbox._start );

		cnt._transition_cback = function ()
		{
			cnt.insertBefore ( el, cnt.firstChild );
		};

		cnt._remove_last = true;
		scrollbox._set_transition ( cnt );
		cnt.style.left = "0px";

		if ( ! scrollbox._support_transitions ) scrollbox._remove_child ();
	};

	scrollbox.can_move_prev = function ()
	{
		return ! ( scrollbox._start == 0 );
	};

	scrollbox.can_move_next = function ()
	{
		// console.debug ( "Start: %s, to_show: %s - len: %s", scrollbox._start, scrollbox.items_to_show, scrollbox._items.length );
		return ! ( scrollbox._start + scrollbox.items_to_show + 1  >= scrollbox._items.length );
	};

	scrollbox.move_next = function ()
	{
		var cnt = $( scrollbox.id );
		var el;

		if ( scrollbox._in_transition ) return;
		if ( ! scrollbox.can_move_next () ) return;

		scrollbox._in_transition = true;
		scrollbox._start += 1;

		el = scrollbox._create_element ( scrollbox._start + scrollbox.items_to_show + 1 );
		$( scrollbox.id ).appendChild ( el );

		scrollbox._set_transition ( cnt );
		cnt.style.left = - ( scrollbox.item_width * 2 ) + "px";

		if ( ! scrollbox._support_transitions ) scrollbox._remove_child ();
	};

	scrollbox._set_transition = function ( cnt )
	{
		cnt.style.MozTransition = "left 0.5s ease-in";
		cnt.style.WebkitTransition = "left 0.5s ease-in";
		cnt.style.Transition = "left 0.5s ease-in";
	};

	scrollbox._create_element = function ( pos )
	{
		item = scrollbox._items [ pos ];

		if ( ! item ) item = "";
		
		el = document.createElement ( 'div' );
		el.className = "wwl_scrollbox_item";
		el.style.width = scrollbox.item_width +"px";
		el.style.height = scrollbox.item_height + "px";
		el.innerHTML = item;

		return el;
	};

	scrollbox.get_item = function ( pos ) { return scrollbox._items [ pos ]; };
	scrollbox.set_item = function ( pos, html ) { scrollbox._items [ pos ] = html; };

	scrollbox.clear ();

	return scrollbox;
};

WWL.scrollbox.get_instance = function ( instance_name )
{
	return WWL.get_instance ( "scrollbox", instance_name );
};
WWL.scrollbox.templates = {
	"container-start" : '<div id="%(id)s" class="wwl_scrollbox_container" style="width: %(container_width)spx; height: %(height)spx; left: %(left)spx">',
	"container-end" : '</div>'
};
WWL.arrowbox = function ( name )
{
	var arrowbox = new WWL ( 'arrowbox', name );

	arrowbox.sb = new WWL.scrollbox ( "ab:" + name );

	arrowbox.cbacks [ 'render' ] = function ()
	{
		arrowbox.sb.render ( arrowbox.id + ":sb" );
	};

	console.debug ( "SB: %o", arrowbox.sb );

	arrowbox.clear = arrowbox.sb.clear;
	arrowbox.set_size = arrowbox.sb.set_size;
	arrowbox.set_item_size = arrowbox.sb.set_item_size;
	arrowbox.add_item = arrowbox.sb.add_item;

	arrowbox.set_arrow_w = function ( w )
	{
		arrowbox.arrow_width = w;
	};

	arrowbox.to_string = function ()
	{
		var s = new String.buffer ();
		var w = arrowbox.sb.width + arrowbox.arrow_width *2 ;
		var h = arrowbox.sb.height;
		
		s.add ( '<div class="wwl_' + arrowbox.type + '" style="width: ' + w + 'px; height: ' + h + 'px; position: relative">' );
		s.add ( String.formatDict ( WWL.arrowbox.templates [ 'nav-next' ], { 'name' :  arrowbox.name } ) );
		s.add ( '<div id="' + arrowbox.id + ':sb" style="width: ' + arrowbox.sb.width + 'px; height: ' + arrowbox.sb.height + 'px; float: left"></div>' );
		s.add ( String.formatDict ( WWL.arrowbox.templates [ 'nav-prev' ], { 'name' :  arrowbox.name } ) );
                s.add ( '</div>' );

		return s.toString ();
	};

	return arrowbox;
};

WWL.arrowbox.get_instance = function ( instance_name )
{
	return WWL.get_instance ( "arrowbox", instance_name );
};

WWL.arrowbox.move_prev = function ( instance_name )
{
	WWL.arrowbox.get_instance ( instance_name ).sb.move_prev ();
};

WWL.arrowbox.move_next = function ( instance_name )
{
	WWL.arrowbox.get_instance ( instance_name ).sb.move_next ();
};
WWL.arrowbox.templates = {
	"nav-next" : '<div class="wwl_arrowbox_next" onclick="WWL.arrowbox.move_next("%(name)s")"></div>',
	"nav-prev" : '<div class="wwl_arrowbox_prev" onclick="WWL.arrowbox.move_prev("%(name)s")"></div>'
};
var media_manager=liwe.module("media_manager");WWL.arrowbox.templates={"nav-next":'<div class="wwl_arrowbox_next"> <div id="mm-nav-next" class="nav next" onclick=WWL.arrowbox.move_next("%(name)s")></div></div>',"nav-prev":'<div class="wwl_arrowbox_prev"> <div id="mm-nav-prev" class="nav prev" onclick=WWL.arrowbox.move_prev("%(name)s")></div></div>',};media_manager._mm_panel="mm-panel";media_manager._tmpl={"arrow-box":{tmpl:"arrowbox-render",cback:"_render_arrowbox"},icons:{tmpl:"start-view",cback:"_render_icons"}};function MediaManagerItem(b,c,d){var a=this;this.data=b;this._t_preview=c;this._t_full=d;this.preview=function(e){if(!e){e="icon"}this.data._mode=e;return String.formatDict(this._t_preview,this.data)};this.toString=function(){return String.formatDict(this._t_full,this.data)};this.load=function(g){if(this.data.kind!="image"){if(g){g()}return}var f=media_manager.instances[a.data.module+":"+a.data.id_obj];var h=f.sizes;var e=new Image();e.onload=function(){var i=parseInt(h.full.W,10)+40,j=parseInt(h.full.H,10)+140;$("mm-show-div").style.width=i+"px";$("mm-show-div").style.height=j+"px";liwe.lightbox.set_size(i,j,-1,-1);if(g){g()}};e.src=String.formatDict("/site/media_manager/image/full/%(id_media)s.jpg",this.data)}}MediaManagerItem.templates={"image-preview":'<img src="/site/media_manager/image/%(_mode)s/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',"image-render":'<img src="/site/media_manager/image/full/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',"youtube-preview":'<img src="/site/media_manager/youtube/%(_mode)s/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',"youtube-render":'<object width="618" height="500"><param name="movie" value="http://www.youtube.com/v/%(data)s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/%(data)s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="618" height="500"></embed></object>',"start-view":"<a href=\"javascript:media_manager.show('%(module)s','%(id_obj)s',%(_pos)d)\">%(_img)s</a>","flash-preview":'<object width="200" height="200"><param name="movie" value="/site/media_manager/flash/orig/%(id_media)s.swf"></param><param name="wmode" value="transparent"></param><embed src="/site/media_manager/flash/orig/%(id_media)s.swf" type="application/x-shockwave-flash" wmode="transparent" width="200" height="200"></embed></object>',"flash-render":'<object width="200" height="200"><param name="movie" value="/site/media_manager/flash/orig/%(id_media)s.swf"></param><param name="wmode" value="transparent"></param><embed src="/site/media_manager/flash/orig/%(id_media)s.swf" type="application/x-shockwave-flash" wmode="transparent" width="200" height="200"></embed></object>',wait:'<div class="liwe_progress"><div class="medium_white"></div></div>',"arrowbox-render":'<div class="arrow-item" style="vertical-align:middle;" onclick ="media_manager.show(\'%(module)s\',\'%(id_obj)s\',%(_pos)d)">%(_img)s</div>',"ligth-box-panel":'<div id="mm-container" align="center"><div id="mm-tbar"><div id="mm-tbar-close" onclick="liwe.lightbox.close()"></div></div><div id="mm-object"></div><div id="mm-panel" class="panel"></div></div>',};media_manager.instances={};media_manager.get_items=function(d,a,b,c,e){if(media_manager.instances[d+":"+a]&&!e){if(b){b(media_manager.instances[d+":"+a])}return}media_manager.ajax({action:"media_manager.ajax.get_items",module:d,id_obj:a},function(f){media_manager._set_items(f,d,a,c,b)})};media_manager.get_items_list=function(b,a){if(media_manager.instances[b+":"+a]){return media_manager.instances[b+":"+a]}return[]};media_manager._set_items=function(i,a,b,g,h){if(!g){g=MediaManagerItem.templates}var f=i.media_items;var k=i.get("sizes");if(!f){f=[]}var j,c=f.length;var e=[],d;for(j=0;j<c;j++){d=i.media_items[j];e.push(media_manager._create(d,g))}e.sizes=k;media_manager.instances[a+":"+b]=e;if(h){return h(e)}return e};media_manager._create=function(d,b){var e,a;var c;e=b[d.kind+"-preview"];a=b[d.kind+"-render"];c=new MediaManagerItem(d,e,a);return c};media_manager.set_items=function(a,b,d){if(!a){return}var c=a;c=c.get("media_items",a);if(!c||c.length==0){return}return media_manager._set_items({media_items:c,sizes:d},c[0]["module"],c[0]["id_obj"],b)};media_manager.panel=function(c,e,d,b,a){if(!e){e="icon"}if(!d){d=8}if(!b){b=media_manager._render_icons}if(!a){a="start-view"}return b(c,e,MediaManagerItem.templates[a],d)};media_manager.show=function(f,g,n,d,c,k,i,e,p){var m=media_manager.instances[f+":"+g];if(!m||!m.length){$("mm-object","");$("mm-panel","");return}var j=m[n];var a,l;var b=liwe.lightbox.created();if(!k){k="icon"}if(!i){i=4}var h=media_manager._tmpl.get(e,media_manager._tmpl["arrow-box"]);if(!p){p=media_manager[h.cback]}var o=h.tmpl;if(!d){d=1000}if(!b||c){liwe.lightbox.events.click=function(){liwe.lightbox.close()};if(!b){a=liwe.lightbox.create("mm-show-div",d);a.innerHTML=MediaManagerItem.templates["ligth-box-panel"]}l=media_manager.panel(m,k,i,p,o);if(l){$("mm-panel",l)}if(!b){liwe.lightbox.show()}}j.load(function(){$("mm-object",j.toString())})};media_manager._render_arrowbox=function(e,c,h,i){var j=parseInt(e.sizes.full.W,10);var k=e.sizes[c];var g=parseInt(e.length*(k.W+20),10);if(j>g){var f=MediaManagerItem.templates["start-view"];return media_manager._render_icons(e,"icon",f,i)}var b=media_manager._mm_panel;var a=new WWL.arrowbox("arrow_box");a.set_size(j-78,parseInt(k.H,10)+2);a.set_item_size(parseInt(k.W,10)+20,parseInt(k.H,10)+2);a.set_arrow_w(36);e.iterate(function(m,l){if(l=="sizes"){return}dct={id_obj:m.data.id_obj,module:m.data.module,_pos:l,_img:m.preview(c)};a.add_item(String.formatDict(h,dct))});a.render(b);var d=Math.floor((k.H-36)/2);$("mm-nav-next").style.marginTop=d+"px";$("mm-nav-prev").style.marginTop=d+"px"};media_manager._render_icons=function(h,d,i,c){var j,b=h.length;var g=new String.buffer();var e,a;var f=0;g.add('<table border="0" class="media_manager_icons">');for(j=0;j<b;j++){if(!f){g.add("<tr>")}f++;e=h[j];a={id_obj:e.data.id_obj,module:e.data.module,_pos:j,_img:e.preview(d)};g.add("<td>");g.add(String.formatDict(i,a));g.add("</td>");if(f==c){g.add("</tr>");f=0}}if(f){g.add("</td></tr>")}g.add("</table>");return g.toString()};var user=liwe.module("user");user.events={login:null,logout:null};user._evt_login=function(){var a=false;if(user.events.login){a=user.events.login()}return false};user.login_box=function(){var a=new liwe.form.instance("user-login-form");a.text({label:"Login",name:"login",size:30,maxlength:50,mandatory:true});a.password({label:"Password",name:"pwd",size:30,maxlength:30,mandatory:true});a.button({value:"Accedi",onclick:"user._login()"});a.sep();a.descr("Hai dimenticato la password?");a.text({label:"Tua e-mail",name:"email",size:30,maxlength:50});a.button({value:"Richiedi",onclick:"user._lost_password()"});a.sep();a.descr("Registrazione nuovo utente");a.label({value:"&nbsp;<br />La registrazione a questo sito &egrave; totalmente gratuita!<br />&nbsp;<br />"});a.button({value:"Vuoi registrarti al sito? Clicca qui!",onclick:"user.registration()"});liwe.lightbox.easy("user-lightbox","Accesso utente",450,300,-1,100);a.set("user-lightbox")};user.registration=function(){var a=new liwe.form.instance("user-login-register");a.email({label:"Indirizzo e-mail",name:"email",size:30,maxlength:200,mandatory:true});a.password({label:"Password",name:"pwd",size:30,maxlength:30,mandatory:true});a.password({label:"Password (conferma)",name:"pwd2",size:30,maxlength:30,mandatory:true});a.button({value:"Registrati",onclick:"user._register()"});a.set("user-lightbox")};user._register=function(){var b=liwe.form.get("user-login-register");var a=b.get_values();if(a.pwd!=a.pwd2){alert("Verifcare la password inserita");return}user.ajax({action:"user.ajax.login_exists",email:a.email},function(c){if(c.exists){alert("L'indirizzo di email inserito e' gia' presente nel nostro database.");return}if(!a.login){a.login=a.email}a.action="user.ajax.register";user.ajax(a,function(d){alert("Utente creato con successo!");liwe.lightbox.close()})})};user.change_password=function(){var a=new liwe.form.instance("user-change-pwd-form");a.password({label:"Password",name:"pwd",size:30,maxlength:30,mandatory:true});a.password({label:"Password (verifica)",name:"pwd2",size:30,maxlength:30,mandatory:true});a.button({value:"Accedi",onclick:"user._change_pwd()"});liwe.lightbox.easy("user-lightbox","Modifica password",400,300);a.set("user-lightbox")};user._change_pwd=function(){var c=liwe.form.get("user-change-pwd-form");var b;if(!c.check()){return}b=c.get_values();if(b.pwd!=b.pwd2){alert("Le due password inserite non coincidono");return}liwe.AJAX.easy({action:"user.ajax.change_password",pwd:b.pwd},function(a){alert("Password aggiornata!");liwe.lightbox.close()})};user.logout=function(){liwe.AJAX.easy({action:"user.ajax.logout"},user.events.logout)};user._login=function(){var c=liwe.form.get("user-login-form");var b=c.get_values();b.action="user.ajax.login";liwe.AJAX.easy(b,function(a){liwe.lightbox.close();if(user.events.login){user.events.login(a)}})};user._lost_password=function(){var b=liwe.form.get("user-login-form");var a=b.get_value("email");liwe.AJAX.easy({action:"user.ajax.lost_password",email:a},function(c){alert("Una nuova password e' stata inviata all'indirizzo di email: "+a)})};liwe.AJAX.url = "/ajax.pyhp";

var site = {};

site.init = function ()
{
	console.debug ( "SITE INIT" );

	liwe.dom.tableize ();

	liwe.AJAX.cbacks [ 'serialize' ] = function ( s )
	{
		if ( typeof ( s ) != 'string' ) return s;

		return s.htmlEntities ();
	};

	// Set events callback
	user.events.login = shop.home.show;
	user.events.logout = site.user_login;
	
	// site.user_login ();
	liwe.history.init ();
};

site._imdb = {};

site._imdb.add_actors = function ( dest, actors )
{
	if ( ! actors.length ) return;

	var t, l = actors.length;
	var s = new String.buffer ();

	for ( t = 0; t < l; t ++ )
		s.add ( String.formatDict ( site.templates [ 'imdb_actor' ], actors [ t ] ) );

	dest.add ( String.formatDict ( site.templates [ 'imdb_actors' ], { "_actors" : s.get ( '<br />' ) } ) );
};

site._imdb.add_directors = function ( dest, directors )
{
	if ( ! directors.length ) return;

	var t, l = directors.length;
	var s = new String.buffer ();

	for ( t = 0; t < l; t ++ )
		s.add ( String.formatDict ( site.templates [ 'imdb_director' ], directors [ t ] ) );

	dest.add ( String.formatDict ( site.templates [ 'imdb_directors' ], { "_directors" : s.get ( '<br />' ) } ) );
};

product.cbacks [ 'show' ] = function ( prod )
{
	var imdb = prod [ 'imdb' ];
	var res = new String.buffer ();

	if ( imdb )
	{
		if ( imdb [ 'base' ] ) res.add ( String.formatDict ( site.templates [ 'imdb_base' ], imdb [ 'base' ] ) );
		if ( imdb [ 'directors' ] ) site._imdb.add_directors ( res, imdb [ 'directors' ] );
		if ( imdb [ 'actors' ] ) site._imdb.add_actors ( res, imdb [ 'actors' ] );
	}

	if ( res.length () )
		prod [ '_info_box' ] = String.formatDict ( site.templates [ 'imdb_info_box' ], { "_data" : res.toString () } );
	else
		prod [ '_info_box' ] = '';
};

/*
site.user_login = function ( v )
{
	liwe.AJAX.easy (  { action: "shop.ajax.client_get_data" },
		function ( v )
		{
			if ( $( "user-login-box" ) )
			{
				if ( v [ 'uid' ] > 0 ) 
					$( "user-login-box" ).innerHTML = String.formatDict ( site.templates [ "user-login" ], v );
				else
					$( "user-login-box" ).innerHTML = site.templates [ 'user-login-enter' ];
			}
		} );

};

site.show_divs = function ( mode )
{
	switch ( mode )
	{
		case "prod":
			$('filter_cnt').style.display = 'none';
			$('product_cnt').style.display = 'block';
			break;

		default:
			$('filter_cnt').style.display = 'block';
			$('product_cnt').style.display = 'none';
	}
};

liwe.history.init ();
*/
site.templates = {
	"user-login" : 	'Benvenuto %(name)s %(lastname)s! <a href="javascript:shop.list_orders()">I tuoi ordini</a> - <a href="javascript:user.change_password()">Modifica password</a> - ' + 
			'<a href="javascript:rma.home()">Richieste RMA</a> - <a href="javascript:user.logout()">Esci</a>',
	"user-login-enter" : '<a href="javascript:user.login_box()">Accedi</a>',
	
	"imdb_base" : '<tr><td class="desc">Titolo Orig:</td><td>%(orig_title)s</td></tr>' + 
		      '<tr><td class="desc">Anno prod:</td><td>%(year)s</td></tr>',

	"imdb_actor" : '<tr><td><a href="%(actor_code)s">%(actor)s</a></td><td><a href="%(character_code)s">%(cname)s</a></td></tr>',
	"imdb_actors" : '<tr><td class="desc">Interpreti:</td><td><div class="box"><table cellpadding="0" cellspacing="0">%(_actors)s</table></div></td></tr>',

	"imdb_director" : '<a href="/module/product/mode/search/director/%(actor_code)s/name/%(actor)s" onclick="return false;">%(actor)s</a>',
	"imdb_directors" : '<tr><td class="desc">Regia:</td><td>%(_directors)s</td></tr>',

	"imdb_info_box" : '<table class="imdb_info_box"><tr><td colspan="2" class="title">Informazioni</td></tr>%(_data)s</table>'
};

