function xpathLog(msg){};function xsltLog(msg){};function xsltLogXml(msg){};var ajaxsltIsIE6=navigator.appVersion.match(/MSIE 6.0/);function assert(b){if(!b){throw"Assertion failed";}}
function stringSplit(s,c){var a=s.indexOf(c);if(a==-1){return[s];}
var parts=[];parts.push(s.substr(0,a));while(a!=-1){var a1=s.indexOf(c,a+1);if(a1!=-1){parts.push(s.substr(a+1,a1-a-1));}else{parts.push(s.substr(a+1));}
a=a1;}
return parts;}
function xmlImportNode(doc,node){if(node.nodeType==DOM_TEXT_NODE){return domCreateTextNode(doc,node.nodeValue);}else if(node.nodeType==DOM_CDATA_SECTION_NODE){return domCreateCDATASection(doc,node.nodeValue);}else if(node.nodeType==DOM_ELEMENT_NODE){var newNode=domCreateElement(doc,node.nodeName);for(var i=0;i<node.attributes.length;++i){var an=node.attributes[i];var name=an.nodeName;var value=an.nodeValue;domSetAttribute(newNode,name,value);}
for(var c=node.firstChild;c;c=c.nextSibling){var cn=arguments.callee(doc,c);domAppendChild(newNode,cn);}
return newNode;}else{return domCreateComment(doc,node.nodeName);}}
function Set(){this.keys=[];}
Set.prototype.size=function(){return this.keys.length;}
Set.prototype.add=function(key,opt_value){var value=opt_value||1;if(!this.contains(key)){this[':'+key]=value;this.keys.push(key);}}
Set.prototype.set=function(key,opt_value){var value=opt_value||1;if(!this.contains(key)){this[':'+key]=value;this.keys.push(key);}else{this[':'+key]=value;}}
Set.prototype.inc=function(key){if(!this.contains(key)){this[':'+key]=1;this.keys.push(key);}else{this[':'+key]++;}}
Set.prototype.get=function(key){if(this.contains(key)){return this[':'+key];}else{var undefined;return undefined;}}
Set.prototype.remove=function(key){if(this.contains(key)){delete this[':'+key];removeFromArray(this.keys,key,true);}}
Set.prototype.contains=function(entry){return typeof this[':'+entry]!='undefined';}
Set.prototype.items=function(){var list=[];for(var i=0;i<this.keys.length;++i){var k=this.keys[i];var v=this[':'+k];list.push(v);}
return list;}
Set.prototype.map=function(f){for(var i=0;i<this.keys.length;++i){var k=this.keys[i];f.call(this,k,this[':'+k]);}}
Set.prototype.clear=function(){for(var i=0;i<this.keys.length;++i){delete this[':'+this.keys[i]];}
this.keys.length=0;}
function mapExec(array,func){for(var i=0;i<array.length;++i){func.call(this,array[i],i);}}
function mapExpr(array,func){var ret=[];for(var i=0;i<array.length;++i){ret.push(func(array[i]));}
return ret;};function reverseInplace(array){for(var i=0;i<array.length/2;++i){var h=array[i];var ii=array.length-i-1;array[i]=array[ii];array[ii]=h;}}
function removeFromArray(array,value,opt_notype){var shift=0;for(var i=0;i<array.length;++i){if(array[i]===value||(opt_notype&&array[i]==value)){array.splice(i--,1);shift++;}}
return shift;}
function copyArray(dst,src){if(!src)return;var dstLength=dst.length;for(var i=src.length-1;i>=0;--i){dst[i+dstLength]=src[i];}}
function copyArrayIgnoringAttributesWithoutValue(dst,src)
{if(!src)return;for(var i=src.length-1;i>=0;--i){if(src[i].nodeValue){dst.push(src[i]);}}}
function xmlValue(node){if(!node){return'';}
var ret='';if(node.nodeType==DOM_TEXT_NODE||node.nodeType==DOM_CDATA_SECTION_NODE){ret+=node.nodeValue;}else if(node.nodeType==DOM_ATTRIBUTE_NODE){if(ajaxsltIsIE6){ret+=xmlValueIE6Hack(node);}else{ret+=node.nodeValue;}}else if(node.nodeType==DOM_ELEMENT_NODE||node.nodeType==DOM_DOCUMENT_NODE||node.nodeType==DOM_DOCUMENT_FRAGMENT_NODE){for(var i=0;i<node.childNodes.length;++i){ret+=arguments.callee(node.childNodes[i]);}}
return ret;}
function xmlValueIE6Hack(node){var nodeName=node.nodeName;var nodeValue=node.nodeValue;if(nodeName.length!=4)return nodeValue;if(!/^href$/i.test(nodeName))return nodeValue;if(!/^javascript:/.test(nodeValue))return nodeValue;return unescape(nodeValue);}
function xmlText(node,opt_cdata){var buf=[];xmlTextR(node,buf,opt_cdata);return buf.join('');}
function xmlTextR(node,buf,cdata){if(node.nodeType==DOM_TEXT_NODE){buf.push(xmlEscapeText(node.nodeValue));}else if(node.nodeType==DOM_CDATA_SECTION_NODE){if(cdata){buf.push(node.nodeValue);}else{buf.push('<![CDATA['+node.nodeValue+']]>');}}else if(node.nodeType==DOM_COMMENT_NODE){buf.push('<!--'+node.nodeValue+'-->');}else if(node.nodeType==DOM_ELEMENT_NODE){buf.push('<'+xmlFullNodeName(node));for(var i=0;i<node.attributes.length;++i){var a=node.attributes[i];if(a&&a.nodeName&&a.nodeValue){buf.push(' '+xmlFullNodeName(a)+'="'+
xmlEscapeAttr(a.nodeValue)+'"');}}
if(node.childNodes.length==0){buf.push('/>');}else{buf.push('>');for(var i=0;i<node.childNodes.length;++i){arguments.callee(node.childNodes[i],buf,cdata);}
buf.push('</'+xmlFullNodeName(node)+'>');}}else if(node.nodeType==DOM_DOCUMENT_NODE||node.nodeType==DOM_DOCUMENT_FRAGMENT_NODE){for(var i=0;i<node.childNodes.length;++i){arguments.callee(node.childNodes[i],buf,cdata);}}}
function xmlFullNodeName(n){if(n.prefix&&n.nodeName.indexOf(n.prefix+':')!=0){return n.prefix+':'+n.nodeName;}else{return n.nodeName;}}
function xmlEscapeText(s){return(''+s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function xmlEscapeAttr(s){return xmlEscapeText(s).replace(/\"/g,'&quot;');}
function xmlEscapeTags(s){return s.replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function xmlOwnerDocument(node){if(node.nodeType==DOM_DOCUMENT_NODE){return node;}else{return node.ownerDocument;}}
function domGetAttribute(node,name){return node.getAttribute(name);}
function domSetAttribute(node,name,value){return node.setAttribute(name,value);}
function domRemoveAttribute(node,name){return node.removeAttribute(name);}
function domAppendChild(node,child){return node.appendChild(child);}
function domRemoveChild(node,child){return node.removeChild(child);}
function domReplaceChild(node,newChild,oldChild){return node.replaceChild(newChild,oldChild);}
function domInsertBefore(node,newChild,oldChild){return node.insertBefore(newChild,oldChild);}
function domRemoveNode(node){return domRemoveChild(node.parentNode,node);}
function domCreateTextNode(doc,text){return doc.createTextNode(text);}
function domCreateElement(doc,name){return doc.createElement(name);}
function domCreateAttribute(doc,name){return doc.createAttribute(name);}
function domCreateCDATASection(doc,data){return doc.createCDATASection(data);}
function domCreateComment(doc,text){return doc.createComment(text);}
function domCreateDocumentFragment(doc){return doc.createDocumentFragment();}
function domGetElementById(doc,id){return doc.getElementById(id);}
function windowSetInterval(win,fun,time){return win.setInterval(fun,time);}
function windowClearInterval(win,id){return win.clearInterval(id);}
var REGEXP_UNICODE=function(){var tests=[' ','\u0120',-1,'!','\u0120',-1,'\u0120','\u0120',0,'\u0121','\u0120',-1,'\u0121','\u0120|\u0121',0,'\u0122','\u0120|\u0121',-1,'\u0120','[\u0120]',0,'\u0121','[\u0120]',-1,'\u0121','[\u0120\u0121]',0,'\u0122','[\u0120\u0121]',-1,'\u0121','[\u0120-\u0121]',0,'\u0122','[\u0120-\u0121]',-1];for(var i=0;i<tests.length;i+=3){if(tests[i].search(new RegExp(tests[i+1]))!=tests[i+2]){return false;}}
return true;}();var XML_S='[ \t\r\n]+';var XML_EQ='('+XML_S+')?=('+XML_S+')?';var XML_CHAR_REF='&#[0-9]+;|&#x[0-9a-fA-F]+;';var XML10_VERSION_INFO=XML_S+'version'+XML_EQ+'("1\\.0"|'+"'1\\.0')";var XML10_BASE_CHAR=(REGEXP_UNICODE)?'\u0041-\u005a\u0061-\u007a\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff'+'\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3'+'\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386'+'\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc'+'\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c'+'\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb'+'\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea'+'\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be'+'\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d'+'\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2'+'\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a'+'\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36'+'\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d'+'\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9'+'\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30'+'\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a'+'\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4'+'\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10'+'\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c'+'\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1'+'\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61'+'\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84'+'\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5'+'\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4'+'\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103'+'\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c'+'\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169'+'\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af'+'\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b'+'\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d'+'\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc'+'\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec'+'\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182'+'\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3':'A-Za-z';var XML10_IDEOGRAPHIC=(REGEXP_UNICODE)?'\u4e00-\u9fa5\u3007\u3021-\u3029':'';var XML10_COMBINING_CHAR=(REGEXP_UNICODE)?'\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9'+'\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc'+'\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c'+'\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be'+'\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02'+'\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71'+'\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03'+'\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83'+'\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44'+'\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4'+'\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43'+'\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1'+'\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39'+'\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad'+'\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a':'';var XML10_DIGIT=(REGEXP_UNICODE)?'\u0030-\u0039\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef'+'\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f'+'\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29':'0-9';var XML10_EXTENDER=(REGEXP_UNICODE)?'\u00b7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035'+'\u309d-\u309e\u30fc-\u30fe':'';var XML10_LETTER=XML10_BASE_CHAR+XML10_IDEOGRAPHIC;var XML10_NAME_CHAR=XML10_LETTER+XML10_DIGIT+'\\._:'+
XML10_COMBINING_CHAR+XML10_EXTENDER+'-';var XML10_NAME='['+XML10_LETTER+'_:]['+XML10_NAME_CHAR+']*';var XML10_ENTITY_REF='&'+XML10_NAME+';';var XML10_REFERENCE=XML10_ENTITY_REF+'|'+XML_CHAR_REF;var XML10_ATT_VALUE='"(([^<&"]|'+XML10_REFERENCE+')*)"|'+"'(([^<&']|"+XML10_REFERENCE+")*)'";var XML10_ATTRIBUTE='('+XML10_NAME+')'+XML_EQ+'('+XML10_ATT_VALUE+')';var XML11_VERSION_INFO=XML_S+'version'+XML_EQ+'("1\\.1"|'+"'1\\.1')";var XML11_NAME_START_CHAR=(REGEXP_UNICODE)?':A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d'+'\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff'+'\uf900-\ufdcf\ufdf0-\ufffd':':A-Z_a-z';var XML11_NAME_CHAR=XML11_NAME_START_CHAR+
((REGEXP_UNICODE)?'\\.0-9\u00b7\u0300-\u036f\u203f-\u2040-':'\\.0-9-');var XML11_NAME='['+XML11_NAME_START_CHAR+']['+XML11_NAME_CHAR+']*';var XML11_ENTITY_REF='&'+XML11_NAME+';';var XML11_REFERENCE=XML11_ENTITY_REF+'|'+XML_CHAR_REF;var XML11_ATT_VALUE='"(([^<&"]|'+XML11_REFERENCE+')*)"|'+"'(([^<&']|"+XML11_REFERENCE+")*)'";var XML11_ATTRIBUTE='('+XML11_NAME+')'+XML_EQ+'('+XML11_ATT_VALUE+')';var XML_NC_NAME_CHAR=XML10_LETTER+XML10_DIGIT+'\\._'+
XML10_COMBINING_CHAR+XML10_EXTENDER+'-';var XML_NC_NAME='['+XML10_LETTER+'_]['+XML_NC_NAME_CHAR+']*';function xmlResolveEntities(s){var parts=stringSplit(s,'&');var ret=parts[0];for(var i=1;i<parts.length;++i){var rp=parts[i].indexOf(';');if(rp==-1){ret+=parts[i];continue;}
var entityName=parts[i].substring(0,rp);var remainderText=parts[i].substring(rp+1);var ch;switch(entityName){case'lt':ch='<';break;case'gt':ch='>';break;case'amp':ch='&';break;case'quot':ch='"';break;case'apos':ch='\'';break;case'nbsp':ch=String.fromCharCode(160);break;default:var span=domCreateElement(window.document,'span');span.innerHTML='&'+entityName+'; ';ch=span.childNodes[0].nodeValue.charAt(0);}
ret+=ch+remainderText;}
return ret;}
var XML10_TAGNAME_REGEXP=new RegExp('^('+XML10_NAME+')');var XML10_ATTRIBUTE_REGEXP=new RegExp(XML10_ATTRIBUTE,'g');var XML11_TAGNAME_REGEXP=new RegExp('^('+XML11_NAME+')');var XML11_ATTRIBUTE_REGEXP=new RegExp(XML11_ATTRIBUTE,'g');function xmlParse(xml){var regex_empty=/\/$/;var regex_tagname;var regex_attribute;if(xml.match(/^<\?xml/)){if(xml.search(new RegExp(XML10_VERSION_INFO))==5){regex_tagname=XML10_TAGNAME_REGEXP;regex_attribute=XML10_ATTRIBUTE_REGEXP;}else if(xml.search(new RegExp(XML11_VERSION_INFO))==5){regex_tagname=XML11_TAGNAME_REGEXP;regex_attribute=XML11_ATTRIBUTE_REGEXP;}else{alert('VersionInfo is missing, or unknown version number.');}}else{regex_tagname=XML10_TAGNAME_REGEXP;regex_attribute=XML10_ATTRIBUTE_REGEXP;}
var xmldoc=new XDocument();var root=xmldoc;var stack=[];var parent=root;stack.push(parent);var slurp='';var x=stringSplit(xml,'<');for(var i=1;i<x.length;++i){var xx=stringSplit(x[i],'>');var tag=xx[0];var text=xmlResolveEntities(xx[1]||'');if(slurp){var end=x[i].indexOf(slurp);if(end!=-1){var data=x[i].substring(0,end);parent.nodeValue+='<'+data;stack.pop();parent=stack[stack.length-1];text=x[i].substring(end+slurp.length);slurp='';}else{parent.nodeValue+='<'+x[i];text=null;}}else if(tag.indexOf('![CDATA[')==0){var start='![CDATA['.length;var end=x[i].indexOf(']]>');if(end!=-1){var data=x[i].substring(start,end);var node=domCreateCDATASection(xmldoc,data);domAppendChild(parent,node);}else{var data=x[i].substring(start);text=null;var node=domCreateCDATASection(xmldoc,data);domAppendChild(parent,node);parent=node;stack.push(node);slurp=']]>';}}else if(tag.indexOf('!--')==0){var start='!--'.length;var end=x[i].indexOf('-->');if(end!=-1){var data=x[i].substring(start,end);var node=domCreateComment(xmldoc,data);domAppendChild(parent,node);}else{var data=x[i].substring(start);text=null;var node=domCreateComment(xmldoc,data);domAppendChild(parent,node);parent=node;stack.push(node);slurp='-->';}}else if(tag.charAt(0)=='/'){stack.pop();parent=stack[stack.length-1];}else if(tag.charAt(0)=='?'){}else if(tag.charAt(0)=='!'){}else{var empty=tag.match(regex_empty);var tagname=regex_tagname.exec(tag)[1];var node=domCreateElement(xmldoc,tagname);var att;while(att=regex_attribute.exec(tag)){var val=xmlResolveEntities(att[5]||att[7]||'');domSetAttribute(node,att[1],val);}
domAppendChild(parent,node);if(!empty){parent=node;stack.push(node);}}
if(text&&parent!=root){domAppendChild(parent,domCreateTextNode(xmldoc,text));}}
return root;}
var DOM_ELEMENT_NODE=1;var DOM_ATTRIBUTE_NODE=2;var DOM_TEXT_NODE=3;var DOM_CDATA_SECTION_NODE=4;var DOM_ENTITY_REFERENCE_NODE=5;var DOM_ENTITY_NODE=6;var DOM_PROCESSING_INSTRUCTION_NODE=7;var DOM_COMMENT_NODE=8;var DOM_DOCUMENT_NODE=9;var DOM_DOCUMENT_TYPE_NODE=10;var DOM_DOCUMENT_FRAGMENT_NODE=11;var DOM_NOTATION_NODE=12;function domTraverseElements(node,opt_pre,opt_post){var ret;if(opt_pre){ret=opt_pre.call(null,node);if(typeof ret=='boolean'&&!ret){return false;}}
for(var c=node.firstChild;c;c=c.nextSibling){if(c.nodeType==DOM_ELEMENT_NODE){ret=arguments.callee.call(this,c,opt_pre,opt_post);if(typeof ret=='boolean'&&!ret){return false;}}}
if(opt_post){ret=opt_post.call(null,node);if(typeof ret=='boolean'&&!ret){return false;}}}
function XNode(type,name,opt_value,opt_owner){this.attributes=[];this.childNodes=[];XNode.init.call(this,type,name,opt_value,opt_owner);}
XNode.init=function(type,name,value,owner){this.nodeType=type-0;this.nodeName=''+name;this.nodeValue=''+value;this.ownerDocument=owner;this.firstChild=null;this.lastChild=null;this.nextSibling=null;this.previousSibling=null;this.parentNode=null;}
XNode.unused_=[];XNode.recycle=function(node){if(!node){return;}
if(node.constructor==XDocument){XNode.recycle(node.documentElement);return;}
if(node.constructor!=this){return;}
XNode.unused_.push(node);for(var a=0;a<node.attributes.length;++a){XNode.recycle(node.attributes[a]);}
for(var c=0;c<node.childNodes.length;++c){XNode.recycle(node.childNodes[c]);}
node.attributes.length=0;node.childNodes.length=0;XNode.init.call(node,0,'','',null);}
XNode.create=function(type,name,value,owner){if(XNode.unused_.length>0){var node=XNode.unused_.pop();XNode.init.call(node,type,name,value,owner);return node;}else{return new XNode(type,name,value,owner);}}
XNode.prototype.appendChild=function(node){if(this.childNodes.length==0){this.firstChild=node;}
node.previousSibling=this.lastChild;node.nextSibling=null;if(this.lastChild){this.lastChild.nextSibling=node;}
node.parentNode=this;this.lastChild=node;this.childNodes.push(node);}
XNode.prototype.replaceChild=function(newNode,oldNode){if(oldNode==newNode){return;}
for(var i=0;i<this.childNodes.length;++i){if(this.childNodes[i]==oldNode){this.childNodes[i]=newNode;var p=oldNode.parentNode;oldNode.parentNode=null;newNode.parentNode=p;p=oldNode.previousSibling;oldNode.previousSibling=null;newNode.previousSibling=p;if(newNode.previousSibling){newNode.previousSibling.nextSibling=newNode;}
p=oldNode.nextSibling;oldNode.nextSibling=null;newNode.nextSibling=p;if(newNode.nextSibling){newNode.nextSibling.previousSibling=newNode;}
if(this.firstChild==oldNode){this.firstChild=newNode;}
if(this.lastChild==oldNode){this.lastChild=newNode;}
break;}}}
XNode.prototype.insertBefore=function(newNode,oldNode){if(oldNode==newNode){return;}
if(oldNode.parentNode!=this){return;}
if(newNode.parentNode){newNode.parentNode.removeChild(newNode);}
var newChildren=[];for(var i=0;i<this.childNodes.length;++i){var c=this.childNodes[i];if(c==oldNode){newChildren.push(newNode);newNode.parentNode=this;newNode.previousSibling=oldNode.previousSibling;oldNode.previousSibling=newNode;if(newNode.previousSibling){newNode.previousSibling.nextSibling=newNode;}
newNode.nextSibling=oldNode;if(this.firstChild==oldNode){this.firstChild=newNode;}}
newChildren.push(c);}
this.childNodes=newChildren;}
XNode.prototype.removeChild=function(node){var newChildren=[];for(var i=0;i<this.childNodes.length;++i){var c=this.childNodes[i];if(c!=node){newChildren.push(c);}else{if(c.previousSibling){c.previousSibling.nextSibling=c.nextSibling;}
if(c.nextSibling){c.nextSibling.previousSibling=c.previousSibling;}
if(this.firstChild==c){this.firstChild=c.nextSibling;}
if(this.lastChild==c){this.lastChild=c.previousSibling;}}}
this.childNodes=newChildren;}
XNode.prototype.hasAttributes=function(){return this.attributes.length>0;}
XNode.prototype.setAttribute=function(name,value){for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName==name){this.attributes[i].nodeValue=''+value;return;}}
this.attributes.push(XNode.create(DOM_ATTRIBUTE_NODE,name,value,this));}
XNode.prototype.getAttribute=function(name){for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName==name){return this.attributes[i].nodeValue;}}
return null;}
XNode.prototype.removeAttribute=function(name){var a=[];for(var i=0;i<this.attributes.length;++i){if(this.attributes[i].nodeName!=name){a.push(this.attributes[i]);}}
this.attributes=a;}
XNode.prototype.getElementsByTagName=function(name){var ret=[];var self=this;if("*"==name){domTraverseElements(this,function(node){if(self==node)return;ret.push(node);},null);}else{domTraverseElements(this,function(node){if(self==node)return;if(node.nodeName==name){ret.push(node);}},null);}
return ret;}
XNode.prototype.getElementById=function(id){var ret=null;domTraverseElements(this,function(node){if(node.getAttribute('id')==id){ret=node;return false;}},null);return ret;}
function XDocument(){XNode.call(this,DOM_DOCUMENT_NODE,'#document',null,null);this.documentElement=null;}
XDocument.prototype=new XNode(DOM_DOCUMENT_NODE,'#document');XDocument.prototype.clear=function(){XNode.recycle(this.documentElement);this.documentElement=null;}
XDocument.prototype.appendChild=function(node){XNode.prototype.appendChild.call(this,node);this.documentElement=this.childNodes[0];}
XDocument.prototype.createElement=function(name){return XNode.create(DOM_ELEMENT_NODE,name,null,this);}
XDocument.prototype.createDocumentFragment=function(){return XNode.create(DOM_DOCUMENT_FRAGMENT_NODE,'#document-fragment',null,this);}
XDocument.prototype.createTextNode=function(value){return XNode.create(DOM_TEXT_NODE,'#text',value,this);}
XDocument.prototype.createAttribute=function(name){return XNode.create(DOM_ATTRIBUTE_NODE,name,null,this);}
XDocument.prototype.createComment=function(data){return XNode.create(DOM_COMMENT_NODE,'#comment',data,this);}
XDocument.prototype.createCDATASection=function(data){return XNode.create(DOM_CDATA_SECTION_NODE,'#cdata-section',data,this);}
function xpathParse(expr){xpathLog('parse '+expr);xpathParseInit();var cached=xpathCacheLookup(expr);if(cached){xpathLog(' ... cached');return cached;}
if(expr.match(/^(\$|@)?\w+$/i)){var ret=makeSimpleExpr(expr);xpathParseCache[expr]=ret;xpathLog(' ... simple');return ret;}
if(expr.match(/^\w+(\/\w+)*$/i)){var ret=makeSimpleExpr2(expr);xpathParseCache[expr]=ret;xpathLog(' ... simple 2');return ret;}
var cachekey=expr;var stack=[];var ahead=null;var previous=null;var done=false;var parse_count=0;var lexer_count=0;var reduce_count=0;while(!done){parse_count++;expr=expr.replace(/^\s*/,'');previous=ahead;ahead=null;var rule=null;var match='';for(var i=0;i<xpathTokenRules.length;++i){var result=xpathTokenRules[i].re.exec(expr);lexer_count++;if(result&&result.length>0&&result[0].length>match.length){rule=xpathTokenRules[i];match=result[0];break;}}
if(rule&&(rule==TOK_DIV||rule==TOK_MOD||rule==TOK_AND||rule==TOK_OR)&&(!previous||previous.tag==TOK_AT||previous.tag==TOK_DSLASH||previous.tag==TOK_SLASH||previous.tag==TOK_AXIS||previous.tag==TOK_DOLLAR)){rule=TOK_QNAME;}
if(rule){expr=expr.substr(match.length);xpathLog('token: '+match+' -- '+rule.label);ahead={tag:rule,match:match,prec:rule.prec?rule.prec:0,expr:makeTokenExpr(match)};}else{xpathLog('DONE');done=true;}
while(xpathReduce(stack,ahead)){reduce_count++;xpathLog('stack: '+stackToString(stack));}}
xpathLog('stack: '+stackToString(stack));if(stack.length!=1){throw'XPath parse error '+cachekey+':\n'+stackToString(stack);}
var result=stack[0].expr;xpathParseCache[cachekey]=result;xpathLog('XPath parse: '+parse_count+' / '+
lexer_count+' / '+reduce_count);return result;}
var xpathParseCache={};function xpathCacheLookup(expr){return xpathParseCache[expr];}
function xpathReduce(stack,ahead){var cand=null;if(stack.length>0){var top=stack[stack.length-1];var ruleset=xpathRules[top.tag.key];if(ruleset){for(var i=0;i<ruleset.length;++i){var rule=ruleset[i];var match=xpathMatchStack(stack,rule[1]);if(match.length){cand={tag:rule[0],rule:rule,match:match};cand.prec=xpathGrammarPrecedence(cand);break;}}}}
var ret;if(cand&&(!ahead||cand.prec>ahead.prec||(ahead.tag.left&&cand.prec>=ahead.prec))){for(var i=0;i<cand.match.matchlength;++i){stack.pop();}
xpathLog('reduce '+cand.tag.label+' '+cand.prec+' ahead '+(ahead?ahead.tag.label+' '+ahead.prec+
(ahead.tag.left?' left':''):' none '));var matchexpr=mapExpr(cand.match,function(m){return m.expr;});xpathLog('going to apply '+cand.rule[3].toString());cand.expr=cand.rule[3].apply(null,matchexpr);stack.push(cand);ret=true;}else{if(ahead){xpathLog('shift '+ahead.tag.label+' '+ahead.prec+
(ahead.tag.left?' left':'')+' over '+(cand?cand.tag.label+' '+
cand.prec:' none'));stack.push(ahead);}
ret=false;}
return ret;}
function xpathMatchStack(stack,pattern){var S=stack.length;var P=pattern.length;var p,s;var match=[];match.matchlength=0;var ds=0;for(p=P-1,s=S-1;p>=0&&s>=0;--p,s-=ds){ds=0;var qmatch=[];if(pattern[p]==Q_MM){p-=1;match.push(qmatch);while(s-ds>=0&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else if(pattern[p]==Q_01){p-=1;match.push(qmatch);while(s-ds>=0&&ds<2&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else if(pattern[p]==Q_1M){p-=1;match.push(qmatch);if(stack[s].tag==pattern[p]){while(s-ds>=0&&stack[s-ds].tag==pattern[p]){qmatch.push(stack[s-ds]);ds+=1;match.matchlength+=1;}}else{return[];}}else if(stack[s].tag==pattern[p]){match.push(stack[s]);ds+=1;match.matchlength+=1;}else{return[];}
reverseInplace(qmatch);qmatch.expr=mapExpr(qmatch,function(m){return m.expr;});}
reverseInplace(match);if(p==-1){return match;}else{return[];}}
function xpathTokenPrecedence(tag){return tag.prec||2;}
function xpathGrammarPrecedence(frame){var ret=0;if(frame.rule){if(frame.rule.length>=3&&frame.rule[2]>=0){ret=frame.rule[2];}else{for(var i=0;i<frame.rule[1].length;++i){var p=xpathTokenPrecedence(frame.rule[1][i]);ret=Math.max(ret,p);}}}else if(frame.tag){ret=xpathTokenPrecedence(frame.tag);}else if(frame.length){for(var j=0;j<frame.length;++j){var p=xpathGrammarPrecedence(frame[j]);ret=Math.max(ret,p);}}
return ret;}
function stackToString(stack){var ret='';for(var i=0;i<stack.length;++i){if(ret){ret+='\n';}
ret+=stack[i].tag.label;}
return ret;}
function ExprContext(node,opt_position,opt_nodelist,opt_parent,opt_caseInsensitive,opt_ignoreAttributesWithoutValue){this.node=node;this.position=opt_position||0;this.nodelist=opt_nodelist||[node];this.variables={};this.parent=opt_parent||null;this.caseInsensitive=opt_caseInsensitive||false;this.ignoreAttributesWithoutValue=opt_ignoreAttributesWithoutValue||false;if(opt_parent){this.root=opt_parent.root;}else if(this.node.nodeType==DOM_DOCUMENT_NODE){this.root=node;}else{this.root=node.ownerDocument;}}
ExprContext.prototype.clone=function(opt_node,opt_position,opt_nodelist){return new ExprContext(opt_node||this.node,typeof opt_position!='undefined'?opt_position:this.position,opt_nodelist||this.nodelist,this,this.caseInsensitive,this.ignoreAttributesWithoutValue);};ExprContext.prototype.setVariable=function(name,value){if(value instanceof StringValue||value instanceof BooleanValue||value instanceof NumberValue||value instanceof NodeSetValue){this.variables[name]=value;return;}
if('true'===value){this.variables[name]=new BooleanValue(true);}else if('false'===value){this.variables[name]=new BooleanValue(false);}else if(TOK_NUMBER.re.test(value)){this.variables[name]=new NumberValue(value);}else{this.variables[name]=new StringValue(value);}};ExprContext.prototype.getVariable=function(name){if(typeof this.variables[name]!='undefined'){return this.variables[name];}else if(this.parent){return this.parent.getVariable(name);}else{return null;}};ExprContext.prototype.setNode=function(position){this.node=this.nodelist[position];this.position=position;};ExprContext.prototype.contextSize=function(){return this.nodelist.length;};ExprContext.prototype.isCaseInsensitive=function(){return this.caseInsensitive;};ExprContext.prototype.setCaseInsensitive=function(caseInsensitive){return this.caseInsensitive=caseInsensitive;};ExprContext.prototype.isIgnoreAttributesWithoutValue=function(){return this.ignoreAttributesWithoutValue;};ExprContext.prototype.setIgnoreAttributesWithoutValue=function(ignore){return this.ignoreAttributesWithoutValue=ignore;};function StringValue(value){this.value=value;this.type='string';}
StringValue.prototype.stringValue=function(){return this.value;}
StringValue.prototype.booleanValue=function(){return this.value.length>0;}
StringValue.prototype.numberValue=function(){return this.value-0;}
StringValue.prototype.nodeSetValue=function(){throw this;}
function BooleanValue(value){this.value=value;this.type='boolean';}
BooleanValue.prototype.stringValue=function(){return''+this.value;}
BooleanValue.prototype.booleanValue=function(){return this.value;}
BooleanValue.prototype.numberValue=function(){return this.value?1:0;}
BooleanValue.prototype.nodeSetValue=function(){throw this;}
function NumberValue(value){this.value=value;this.type='number';}
NumberValue.prototype.stringValue=function(){return''+this.value;}
NumberValue.prototype.booleanValue=function(){return!!this.value;}
NumberValue.prototype.numberValue=function(){return this.value-0;}
NumberValue.prototype.nodeSetValue=function(){throw this;}
function NodeSetValue(value){this.value=value;this.type='node-set';}
NodeSetValue.prototype.stringValue=function(){if(this.value.length==0){return'';}else{return xmlValue(this.value[0]);}}
NodeSetValue.prototype.booleanValue=function(){return this.value.length>0;}
NodeSetValue.prototype.numberValue=function(){return this.stringValue()-0;}
NodeSetValue.prototype.nodeSetValue=function(){return this.value;};function TokenExpr(m){this.value=m;}
TokenExpr.prototype.evaluate=function(){return new StringValue(this.value);};function LocationExpr(){this.absolute=false;this.steps=[];}
LocationExpr.prototype.appendStep=function(s){var combinedStep=this._combineSteps(this.steps[this.steps.length-1],s);if(combinedStep){this.steps[this.steps.length-1]=combinedStep;}else{this.steps.push(s);}}
LocationExpr.prototype.prependStep=function(s){var combinedStep=this._combineSteps(s,this.steps[0]);if(combinedStep){this.steps[0]=combinedStep;}else{this.steps.unshift(s);}};LocationExpr.prototype._combineSteps=function(prevStep,nextStep){if(!prevStep)return null;if(!nextStep)return null;var hasPredicates=(prevStep.predicates&&prevStep.predicates.length>0);if(prevStep.nodetest instanceof NodeTestAny&&!hasPredicates){if(prevStep.axis==xpathAxis.DESCENDANT_OR_SELF){if(nextStep.axis==xpathAxis.CHILD){nextStep.axis=xpathAxis.DESCENDANT;return nextStep;}else if(nextStep.axis==xpathAxis.SELF){nextStep.axis=xpathAxis.DESCENDANT_OR_SELF;return nextStep;}}else if(prevStep.axis==xpathAxis.DESCENDANT){if(nextStep.axis==xpathAxis.SELF){nextStep.axis=xpathAxis.DESCENDANT;return nextStep;}}}
return null;}
LocationExpr.prototype.evaluate=function(ctx){var start;if(this.absolute){start=ctx.root;}else{start=ctx.node;}
var nodes=[];xPathStep(nodes,this.steps,0,start,ctx);return new NodeSetValue(nodes);};function xPathStep(nodes,steps,step,input,ctx){var s=steps[step];var ctx2=ctx.clone(input);var nodelist=s.evaluate(ctx2).nodeSetValue();for(var i=0;i<nodelist.length;++i){if(step==steps.length-1){nodes.push(nodelist[i]);}else{xPathStep(nodes,steps,step+1,nodelist[i],ctx);}}}
function StepExpr(axis,nodetest,opt_predicate){this.axis=axis;this.nodetest=nodetest;this.predicate=opt_predicate||[];}
StepExpr.prototype.appendPredicate=function(p){this.predicate.push(p);}
StepExpr.prototype.evaluate=function(ctx){var input=ctx.node;var nodelist=[];var skipNodeTest=false;if(this.nodetest instanceof NodeTestAny){skipNodeTest=true;}
if(this.axis==xpathAxis.ANCESTOR_OR_SELF){nodelist.push(input);for(var n=input.parentNode;n;n=n.parentNode){nodelist.push(n);}}else if(this.axis==xpathAxis.ANCESTOR){for(var n=input.parentNode;n;n=n.parentNode){nodelist.push(n);}}else if(this.axis==xpathAxis.ATTRIBUTE){if(ctx.ignoreAttributesWithoutValue){copyArrayIgnoringAttributesWithoutValue(nodelist,input.attributes);}
else{copyArray(nodelist,input.attributes);}}else if(this.axis==xpathAxis.CHILD){copyArray(nodelist,input.childNodes);}else if(this.axis==xpathAxis.DESCENDANT_OR_SELF){if(this.nodetest.evaluate(ctx).booleanValue()){nodelist.push(input);}
var tagName=xpathExtractTagNameFromNodeTest(this.nodetest);xpathCollectDescendants(nodelist,input,tagName);if(tagName)skipNodeTest=true;}else if(this.axis==xpathAxis.DESCENDANT){var tagName=xpathExtractTagNameFromNodeTest(this.nodetest);xpathCollectDescendants(nodelist,input,tagName);if(tagName)skipNodeTest=true;}else if(this.axis==xpathAxis.FOLLOWING){for(var n=input;n;n=n.parentNode){for(var nn=n.nextSibling;nn;nn=nn.nextSibling){nodelist.push(nn);xpathCollectDescendants(nodelist,nn);}}}else if(this.axis==xpathAxis.FOLLOWING_SIBLING){for(var n=input.nextSibling;n;n=n.nextSibling){nodelist.push(n);}}else if(this.axis==xpathAxis.NAMESPACE){alert('not implemented: axis namespace');}else if(this.axis==xpathAxis.PARENT){if(input.parentNode){nodelist.push(input.parentNode);}}else if(this.axis==xpathAxis.PRECEDING){for(var n=input;n;n=n.parentNode){for(var nn=n.previousSibling;nn;nn=nn.previousSibling){nodelist.push(nn);xpathCollectDescendantsReverse(nodelist,nn);}}}else if(this.axis==xpathAxis.PRECEDING_SIBLING){for(var n=input.previousSibling;n;n=n.previousSibling){nodelist.push(n);}}else if(this.axis==xpathAxis.SELF){nodelist.push(input);}else{throw'ERROR -- NO SUCH AXIS: '+this.axis;}
if(!skipNodeTest){var nodelist0=nodelist;nodelist=[];for(var i=0;i<nodelist0.length;++i){var n=nodelist0[i];if(this.nodetest.evaluate(ctx.clone(n,i,nodelist0)).booleanValue()){nodelist.push(n);}}}
for(var i=0;i<this.predicate.length;++i){var nodelist0=nodelist;nodelist=[];for(var ii=0;ii<nodelist0.length;++ii){var n=nodelist0[ii];if(this.predicate[i].evaluate(ctx.clone(n,ii,nodelist0)).booleanValue()){nodelist.push(n);}}}
return new NodeSetValue(nodelist);};function NodeTestAny(){this.value=new BooleanValue(true);}
NodeTestAny.prototype.evaluate=function(ctx){return this.value;};function NodeTestElementOrAttribute(){}
NodeTestElementOrAttribute.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_ELEMENT_NODE||ctx.node.nodeType==DOM_ATTRIBUTE_NODE);}
function NodeTestText(){}
NodeTestText.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_TEXT_NODE);}
function NodeTestComment(){}
NodeTestComment.prototype.evaluate=function(ctx){return new BooleanValue(ctx.node.nodeType==DOM_COMMENT_NODE);}
function NodeTestPI(target){this.target=target;}
NodeTestPI.prototype.evaluate=function(ctx){return new
BooleanValue(ctx.node.nodeType==DOM_PROCESSING_INSTRUCTION_NODE&&(!this.target||ctx.node.nodeName==this.target));}
function NodeTestNC(nsprefix){this.regex=new RegExp("^"+nsprefix+":");this.nsprefix=nsprefix;}
NodeTestNC.prototype.evaluate=function(ctx){var n=ctx.node;return new BooleanValue(this.regex.match(n.nodeName));}
function NodeTestName(name){this.name=name;this.re=new RegExp('^'+name+'$',"i");}
NodeTestName.prototype.evaluate=function(ctx){var n=ctx.node;if(ctx.caseInsensitive){if(n.nodeName.length!=this.name.length)return new BooleanValue(false);return new BooleanValue(this.re.test(n.nodeName));}else{return new BooleanValue(n.nodeName==this.name);}}
function PredicateExpr(expr){this.expr=expr;}
PredicateExpr.prototype.evaluate=function(ctx){var v=this.expr.evaluate(ctx);if(v.type=='number'){return new BooleanValue(ctx.position==v.numberValue()-1);}else{return new BooleanValue(v.booleanValue());}};function FunctionCallExpr(name){this.name=name;this.args=[];}
FunctionCallExpr.prototype.appendArg=function(arg){this.args.push(arg);};FunctionCallExpr.prototype.evaluate=function(ctx){var fn=''+this.name.value;var f=this.xpathfunctions[fn];if(f){return f.call(this,ctx);}else{xpathLog('XPath NO SUCH FUNCTION '+fn);return new BooleanValue(false);}};FunctionCallExpr.prototype.xpathfunctions={'last':function(ctx){assert(this.args.length==0);return new NumberValue(ctx.contextSize());},'position':function(ctx){assert(this.args.length==0);return new NumberValue(ctx.position+1);},'count':function(ctx){assert(this.args.length==1);var v=this.args[0].evaluate(ctx);return new NumberValue(v.nodeSetValue().length);},'id':function(ctx){assert(this.args.length==1);var e=this.args[0].evaluate(ctx);var ret=[];var ids;if(e.type=='node-set'){ids=[];var en=e.nodeSetValue();for(var i=0;i<en.length;++i){var v=xmlValue(en[i]).split(/\s+/);for(var ii=0;ii<v.length;++ii){ids.push(v[ii]);}}}else{ids=e.stringValue().split(/\s+/);}
var d=ctx.root;for(var i=0;i<ids.length;++i){var n=d.getElementById(ids[i]);if(n){ret.push(n);}}
return new NodeSetValue(ret);},'local-name':function(ctx){alert('not implmented yet: XPath function local-name()');},'namespace-uri':function(ctx){alert('not implmented yet: XPath function namespace-uri()');},'name':function(ctx){assert(this.args.length==1||this.args.length==0);var n;if(this.args.length==0){n=[ctx.node];}else{n=this.args[0].evaluate(ctx).nodeSetValue();}
if(n.length==0){return new StringValue('');}else{return new StringValue(n[0].nodeName);}},'string':function(ctx){assert(this.args.length==1||this.args.length==0);if(this.args.length==0){return new StringValue(new NodeSetValue([ctx.node]).stringValue());}else{return new StringValue(this.args[0].evaluate(ctx).stringValue());}},'concat':function(ctx){var ret='';for(var i=0;i<this.args.length;++i){ret+=this.args[i].evaluate(ctx).stringValue();}
return new StringValue(ret);},'starts-with':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();return new BooleanValue(s0.indexOf(s1)==0);},'contains':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();return new BooleanValue(s0.indexOf(s1)!=-1);},'substring-before':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var i=s0.indexOf(s1);var ret;if(i==-1){ret='';}else{ret=s0.substr(0,i);}
return new StringValue(ret);},'substring-after':function(ctx){assert(this.args.length==2);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var i=s0.indexOf(s1);var ret;if(i==-1){ret='';}else{ret=s0.substr(i+s1.length);}
return new StringValue(ret);},'substring':function(ctx){assert(this.args.length==2||this.args.length==3);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).numberValue();var ret;if(this.args.length==2){var i1=Math.max(0,Math.round(s1)-1);ret=s0.substr(i1);}else{var s2=this.args[2].evaluate(ctx).numberValue();var i0=Math.round(s1)-1;var i1=Math.max(0,i0);var i2=Math.round(s2)-Math.max(0,-i0);ret=s0.substr(i1,i2);}
return new StringValue(ret);},'string-length':function(ctx){var s;if(this.args.length>0){s=this.args[0].evaluate(ctx).stringValue();}else{s=new NodeSetValue([ctx.node]).stringValue();}
return new NumberValue(s.length);},'normalize-space':function(ctx){var s;if(this.args.length>0){s=this.args[0].evaluate(ctx).stringValue();}else{s=new NodeSetValue([ctx.node]).stringValue();}
s=s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');return new StringValue(s);},'translate':function(ctx){assert(this.args.length==3);var s0=this.args[0].evaluate(ctx).stringValue();var s1=this.args[1].evaluate(ctx).stringValue();var s2=this.args[2].evaluate(ctx).stringValue();for(var i=0;i<s1.length;++i){s0=s0.replace(new RegExp(s1.charAt(i),'g'),s2.charAt(i));}
return new StringValue(s0);},'boolean':function(ctx){assert(this.args.length==1);return new BooleanValue(this.args[0].evaluate(ctx).booleanValue());},'not':function(ctx){assert(this.args.length==1);var ret=!this.args[0].evaluate(ctx).booleanValue();return new BooleanValue(ret);},'true':function(ctx){assert(this.args.length==0);return new BooleanValue(true);},'false':function(ctx){assert(this.args.length==0);return new BooleanValue(false);},'lang':function(ctx){assert(this.args.length==1);var lang=this.args[0].evaluate(ctx).stringValue();var xmllang;var n=ctx.node;while(n&&n!=n.parentNode){xmllang=n.getAttribute('xml:lang');if(xmllang){break;}
n=n.parentNode;}
if(!xmllang){return new BooleanValue(false);}else{var re=new RegExp('^'+lang+'$','i');return new BooleanValue(xmllang.match(re)||xmllang.replace(/_.*$/,'').match(re));}},'number':function(ctx){assert(this.args.length==1||this.args.length==0);if(this.args.length==1){return new NumberValue(this.args[0].evaluate(ctx).numberValue());}else{return new NumberValue(new NodeSetValue([ctx.node]).numberValue());}},'sum':function(ctx){assert(this.args.length==1);var n=this.args[0].evaluate(ctx).nodeSetValue();var sum=0;for(var i=0;i<n.length;++i){sum+=xmlValue(n[i])-0;}
return new NumberValue(sum);},'floor':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.floor(num));},'ceiling':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.ceil(num));},'round':function(ctx){assert(this.args.length==1);var num=this.args[0].evaluate(ctx).numberValue();return new NumberValue(Math.round(num));},'ext-join':function(ctx){assert(this.args.length==2);var nodes=this.args[0].evaluate(ctx).nodeSetValue();var delim=this.args[1].evaluate(ctx).stringValue();var ret='';for(var i=0;i<nodes.length;++i){if(ret){ret+=delim;}
ret+=xmlValue(nodes[i]);}
return new StringValue(ret);},'ext-if':function(ctx){assert(this.args.length==3);if(this.args[0].evaluate(ctx).booleanValue()){return this.args[1].evaluate(ctx);}else{return this.args[2].evaluate(ctx);}},'ext-cardinal':function(ctx){assert(this.args.length>=1);var c=this.args[0].evaluate(ctx).numberValue();var ret=[];for(var i=0;i<c;++i){ret.push(ctx.node);}
return new NodeSetValue(ret);}};function UnionExpr(expr1,expr2){this.expr1=expr1;this.expr2=expr2;}
UnionExpr.prototype.evaluate=function(ctx){var nodes1=this.expr1.evaluate(ctx).nodeSetValue();var nodes2=this.expr2.evaluate(ctx).nodeSetValue();var I1=nodes1.length;for(var i2=0;i2<nodes2.length;++i2){var n=nodes2[i2];var inBoth=false;for(var i1=0;i1<I1;++i1){if(nodes1[i1]==n){inBoth=true;i1=I1;}}
if(!inBoth){nodes1.push(n);}}
return new NodeSetValue(nodes1);};function PathExpr(filter,rel){this.filter=filter;this.rel=rel;}
PathExpr.prototype.evaluate=function(ctx){var nodes=this.filter.evaluate(ctx).nodeSetValue();var nodes1=[];for(var i=0;i<nodes.length;++i){var nodes0=this.rel.evaluate(ctx.clone(nodes[i],i,nodes)).nodeSetValue();for(var ii=0;ii<nodes0.length;++ii){nodes1.push(nodes0[ii]);}}
return new NodeSetValue(nodes1);};function FilterExpr(expr,predicate){this.expr=expr;this.predicate=predicate;}
FilterExpr.prototype.evaluate=function(ctx){var nodes=this.expr.evaluate(ctx).nodeSetValue();for(var i=0;i<this.predicate.length;++i){var nodes0=nodes;nodes=[];for(var j=0;j<nodes0.length;++j){var n=nodes0[j];if(this.predicate[i].evaluate(ctx.clone(n,j,nodes0)).booleanValue()){nodes.push(n);}}}
return new NodeSetValue(nodes);}
function UnaryMinusExpr(expr){this.expr=expr;}
UnaryMinusExpr.prototype.evaluate=function(ctx){return new NumberValue(-this.expr.evaluate(ctx).numberValue());};function BinaryExpr(expr1,op,expr2){this.expr1=expr1;this.expr2=expr2;this.op=op;}
BinaryExpr.prototype.evaluate=function(ctx){var ret;switch(this.op.value){case'or':ret=new BooleanValue(this.expr1.evaluate(ctx).booleanValue()||this.expr2.evaluate(ctx).booleanValue());break;case'and':ret=new BooleanValue(this.expr1.evaluate(ctx).booleanValue()&&this.expr2.evaluate(ctx).booleanValue());break;case'+':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()+
this.expr2.evaluate(ctx).numberValue());break;case'-':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()-
this.expr2.evaluate(ctx).numberValue());break;case'*':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()*this.expr2.evaluate(ctx).numberValue());break;case'mod':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()%this.expr2.evaluate(ctx).numberValue());break;case'div':ret=new NumberValue(this.expr1.evaluate(ctx).numberValue()/this.expr2.evaluate(ctx).numberValue());break;case'=':ret=this.compare(ctx,function(x1,x2){return x1==x2;});break;case'!=':ret=this.compare(ctx,function(x1,x2){return x1!=x2;});break;case'<':ret=this.compare(ctx,function(x1,x2){return x1<x2;});break;case'<=':ret=this.compare(ctx,function(x1,x2){return x1<=x2;});break;case'>':ret=this.compare(ctx,function(x1,x2){return x1>x2;});break;case'>=':ret=this.compare(ctx,function(x1,x2){return x1>=x2;});break;default:alert('BinaryExpr.evaluate: '+this.op.value);}
return ret;};BinaryExpr.prototype.compare=function(ctx,cmp){var v1=this.expr1.evaluate(ctx);var v2=this.expr2.evaluate(ctx);var ret;if(v1.type=='node-set'&&v2.type=='node-set'){var n1=v1.nodeSetValue();var n2=v2.nodeSetValue();ret=false;for(var i1=0;i1<n1.length;++i1){for(var i2=0;i2<n2.length;++i2){if(cmp(xmlValue(n1[i1]),xmlValue(n2[i2]))){ret=true;i2=n2.length;i1=n1.length;}}}}else if(v1.type=='node-set'||v2.type=='node-set'){if(v1.type=='number'){var s=v1.numberValue();var n=v2.nodeSetValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i])-0;if(cmp(s,nn)){ret=true;break;}}}else if(v2.type=='number'){var n=v1.nodeSetValue();var s=v2.numberValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i])-0;if(cmp(nn,s)){ret=true;break;}}}else if(v1.type=='string'){var s=v1.stringValue();var n=v2.nodeSetValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i]);if(cmp(s,nn)){ret=true;break;}}}else if(v2.type=='string'){var n=v1.nodeSetValue();var s=v2.stringValue();ret=false;for(var i=0;i<n.length;++i){var nn=xmlValue(n[i]);if(cmp(nn,s)){ret=true;break;}}}else{ret=cmp(v1.booleanValue(),v2.booleanValue());}}else if(v1.type=='boolean'||v2.type=='boolean'){ret=cmp(v1.booleanValue(),v2.booleanValue());}else if(v1.type=='number'||v2.type=='number'){ret=cmp(v1.numberValue(),v2.numberValue());}else{ret=cmp(v1.stringValue(),v2.stringValue());}
return new BooleanValue(ret);}
function LiteralExpr(value){this.value=value;}
LiteralExpr.prototype.evaluate=function(ctx){return new StringValue(this.value);};function NumberExpr(value){this.value=value;}
NumberExpr.prototype.evaluate=function(ctx){return new NumberValue(this.value);};function VariableExpr(name){this.name=name;}
VariableExpr.prototype.evaluate=function(ctx){return ctx.getVariable(this.name);}
function makeTokenExpr(m){return new TokenExpr(m);}
function passExpr(e){return e;}
function makeLocationExpr1(slash,rel){rel.absolute=true;return rel;}
function makeLocationExpr2(dslash,rel){rel.absolute=true;rel.prependStep(makeAbbrevStep(dslash.value));return rel;}
function makeLocationExpr3(slash){var ret=new LocationExpr();ret.appendStep(makeAbbrevStep('.'));ret.absolute=true;return ret;}
function makeLocationExpr4(dslash){var ret=new LocationExpr();ret.absolute=true;ret.appendStep(makeAbbrevStep(dslash.value));return ret;}
function makeLocationExpr5(step){var ret=new LocationExpr();ret.appendStep(step);return ret;}
function makeLocationExpr6(rel,slash,step){rel.appendStep(step);return rel;}
function makeLocationExpr7(rel,dslash,step){rel.appendStep(makeAbbrevStep(dslash.value));rel.appendStep(step);return rel;}
function makeStepExpr1(dot){return makeAbbrevStep(dot.value);}
function makeStepExpr2(ddot){return makeAbbrevStep(ddot.value);}
function makeStepExpr3(axisname,axis,nodetest){return new StepExpr(axisname.value,nodetest);}
function makeStepExpr4(at,nodetest){return new StepExpr('attribute',nodetest);}
function makeStepExpr5(nodetest){return new StepExpr('child',nodetest);}
function makeStepExpr6(step,predicate){step.appendPredicate(predicate);return step;}
function makeAbbrevStep(abbrev){switch(abbrev){case'//':return new StepExpr('descendant-or-self',new NodeTestAny);case'.':return new StepExpr('self',new NodeTestAny);case'..':return new StepExpr('parent',new NodeTestAny);}}
function makeNodeTestExpr1(asterisk){return new NodeTestElementOrAttribute;}
function makeNodeTestExpr2(ncname,colon,asterisk){return new NodeTestNC(ncname.value);}
function makeNodeTestExpr3(qname){return new NodeTestName(qname.value);}
function makeNodeTestExpr4(typeo,parenc){var type=typeo.value.replace(/\s*\($/,'');switch(type){case'node':return new NodeTestAny;case'text':return new NodeTestText;case'comment':return new NodeTestComment;case'processing-instruction':return new NodeTestPI('');}}
function makeNodeTestExpr5(typeo,target,parenc){var type=typeo.replace(/\s*\($/,'');if(type!='processing-instruction'){throw type;}
return new NodeTestPI(target.value);}
function makePredicateExpr(pareno,expr,parenc){return new PredicateExpr(expr);}
function makePrimaryExpr(pareno,expr,parenc){return expr;}
function makeFunctionCallExpr1(name,pareno,parenc){return new FunctionCallExpr(name);}
function makeFunctionCallExpr2(name,pareno,arg1,args,parenc){var ret=new FunctionCallExpr(name);ret.appendArg(arg1);for(var i=0;i<args.length;++i){ret.appendArg(args[i]);}
return ret;}
function makeArgumentExpr(comma,expr){return expr;}
function makeUnionExpr(expr1,pipe,expr2){return new UnionExpr(expr1,expr2);}
function makePathExpr1(filter,slash,rel){return new PathExpr(filter,rel);}
function makePathExpr2(filter,dslash,rel){rel.prependStep(makeAbbrevStep(dslash.value));return new PathExpr(filter,rel);}
function makeFilterExpr(expr,predicates){if(predicates.length>0){return new FilterExpr(expr,predicates);}else{return expr;}}
function makeUnaryMinusExpr(minus,expr){return new UnaryMinusExpr(expr);}
function makeBinaryExpr(expr1,op,expr2){return new BinaryExpr(expr1,op,expr2);}
function makeLiteralExpr(token){var value=token.value.substring(1,token.value.length-1);return new LiteralExpr(value);}
function makeNumberExpr(token){return new NumberExpr(token.value);}
function makeVariableReference(dollar,name){return new VariableExpr(name.value);}
function makeSimpleExpr(expr){if(expr.charAt(0)=='$'){return new VariableExpr(expr.substr(1));}else if(expr.charAt(0)=='@'){var a=new NodeTestName(expr.substr(1));var b=new StepExpr('attribute',a);var c=new LocationExpr();c.appendStep(b);return c;}else if(expr.match(/^[0-9]+$/)){return new NumberExpr(expr);}else{var a=new NodeTestName(expr);var b=new StepExpr('child',a);var c=new LocationExpr();c.appendStep(b);return c;}}
function makeSimpleExpr2(expr){var steps=stringSplit(expr,'/');var c=new LocationExpr();for(var i=0;i<steps.length;++i){var a=new NodeTestName(steps[i]);var b=new StepExpr('child',a);c.appendStep(b);}
return c;}
var xpathAxis={ANCESTOR_OR_SELF:'ancestor-or-self',ANCESTOR:'ancestor',ATTRIBUTE:'attribute',CHILD:'child',DESCENDANT_OR_SELF:'descendant-or-self',DESCENDANT:'descendant',FOLLOWING_SIBLING:'following-sibling',FOLLOWING:'following',NAMESPACE:'namespace',PARENT:'parent',PRECEDING_SIBLING:'preceding-sibling',PRECEDING:'preceding',SELF:'self'};var xpathAxesRe=[xpathAxis.ANCESTOR_OR_SELF,xpathAxis.ANCESTOR,xpathAxis.ATTRIBUTE,xpathAxis.CHILD,xpathAxis.DESCENDANT_OR_SELF,xpathAxis.DESCENDANT,xpathAxis.FOLLOWING_SIBLING,xpathAxis.FOLLOWING,xpathAxis.NAMESPACE,xpathAxis.PARENT,xpathAxis.PRECEDING_SIBLING,xpathAxis.PRECEDING,xpathAxis.SELF].join('|');var TOK_PIPE={label:"|",prec:17,re:new RegExp("^\\|")};var TOK_DSLASH={label:"//",prec:19,re:new RegExp("^//")};var TOK_SLASH={label:"/",prec:30,re:new RegExp("^/")};var TOK_AXIS={label:"::",prec:20,re:new RegExp("^::")};var TOK_COLON={label:":",prec:1000,re:new RegExp("^:")};var TOK_AXISNAME={label:"[axis]",re:new RegExp('^('+xpathAxesRe+')')};var TOK_PARENO={label:"(",prec:34,re:new RegExp("^\\(")};var TOK_PARENC={label:")",re:new RegExp("^\\)")};var TOK_DDOT={label:"..",prec:34,re:new RegExp("^\\.\\.")};var TOK_DOT={label:".",prec:34,re:new RegExp("^\\.")};var TOK_AT={label:"@",prec:34,re:new RegExp("^@")};var TOK_COMMA={label:",",re:new RegExp("^,")};var TOK_OR={label:"or",prec:10,re:new RegExp("^or\\b")};var TOK_AND={label:"and",prec:11,re:new RegExp("^and\\b")};var TOK_EQ={label:"=",prec:12,re:new RegExp("^=")};var TOK_NEQ={label:"!=",prec:12,re:new RegExp("^!=")};var TOK_GE={label:">=",prec:13,re:new RegExp("^>=")};var TOK_GT={label:">",prec:13,re:new RegExp("^>")};var TOK_LE={label:"<=",prec:13,re:new RegExp("^<=")};var TOK_LT={label:"<",prec:13,re:new RegExp("^<")};var TOK_PLUS={label:"+",prec:14,re:new RegExp("^\\+"),left:true};var TOK_MINUS={label:"-",prec:14,re:new RegExp("^\\-"),left:true};var TOK_DIV={label:"div",prec:15,re:new RegExp("^div\\b"),left:true};var TOK_MOD={label:"mod",prec:15,re:new RegExp("^mod\\b"),left:true};var TOK_BRACKO={label:"[",prec:32,re:new RegExp("^\\[")};var TOK_BRACKC={label:"]",re:new RegExp("^\\]")};var TOK_DOLLAR={label:"$",re:new RegExp("^\\$")};var TOK_NCNAME={label:"[ncname]",re:new RegExp('^'+XML_NC_NAME)};var TOK_ASTERISK={label:"*",prec:15,re:new RegExp("^\\*"),left:true};var TOK_LITERALQ={label:"[litq]",prec:20,re:new RegExp("^'[^\\']*'")};var TOK_LITERALQQ={label:"[litqq]",prec:20,re:new RegExp('^"[^\\"]*"')};var TOK_NUMBER={label:"[number]",prec:35,re:new RegExp('^\\d+(\\.\\d*)?')};var TOK_QNAME={label:"[qname]",re:new RegExp('^('+XML_NC_NAME+':)?'+XML_NC_NAME)};var TOK_NODEO={label:"[nodetest-start]",re:new RegExp('^(processing-instruction|comment|text|node)\\(')};var xpathTokenRules=[TOK_DSLASH,TOK_SLASH,TOK_DDOT,TOK_DOT,TOK_AXIS,TOK_COLON,TOK_AXISNAME,TOK_NODEO,TOK_PARENO,TOK_PARENC,TOK_BRACKO,TOK_BRACKC,TOK_AT,TOK_COMMA,TOK_OR,TOK_AND,TOK_NEQ,TOK_EQ,TOK_GE,TOK_GT,TOK_LE,TOK_LT,TOK_PLUS,TOK_MINUS,TOK_ASTERISK,TOK_PIPE,TOK_MOD,TOK_DIV,TOK_LITERALQ,TOK_LITERALQQ,TOK_NUMBER,TOK_QNAME,TOK_NCNAME,TOK_DOLLAR];var XPathLocationPath={label:"LocationPath"};var XPathRelativeLocationPath={label:"RelativeLocationPath"};var XPathAbsoluteLocationPath={label:"AbsoluteLocationPath"};var XPathStep={label:"Step"};var XPathNodeTest={label:"NodeTest"};var XPathPredicate={label:"Predicate"};var XPathLiteral={label:"Literal"};var XPathExpr={label:"Expr"};var XPathPrimaryExpr={label:"PrimaryExpr"};var XPathVariableReference={label:"Variablereference"};var XPathNumber={label:"Number"};var XPathFunctionCall={label:"FunctionCall"};var XPathArgumentRemainder={label:"ArgumentRemainder"};var XPathPathExpr={label:"PathExpr"};var XPathUnionExpr={label:"UnionExpr"};var XPathFilterExpr={label:"FilterExpr"};var XPathDigits={label:"Digits"};var xpathNonTerminals=[XPathLocationPath,XPathRelativeLocationPath,XPathAbsoluteLocationPath,XPathStep,XPathNodeTest,XPathPredicate,XPathLiteral,XPathExpr,XPathPrimaryExpr,XPathVariableReference,XPathNumber,XPathFunctionCall,XPathArgumentRemainder,XPathPathExpr,XPathUnionExpr,XPathFilterExpr,XPathDigits];var Q_01={label:"?"};var Q_MM={label:"*"};var Q_1M={label:"+"};var ASSOC_LEFT=true;var xpathGrammarRules=[[XPathLocationPath,[XPathRelativeLocationPath],18,passExpr],[XPathLocationPath,[XPathAbsoluteLocationPath],18,passExpr],[XPathAbsoluteLocationPath,[TOK_SLASH,XPathRelativeLocationPath],18,makeLocationExpr1],[XPathAbsoluteLocationPath,[TOK_DSLASH,XPathRelativeLocationPath],18,makeLocationExpr2],[XPathAbsoluteLocationPath,[TOK_SLASH],0,makeLocationExpr3],[XPathAbsoluteLocationPath,[TOK_DSLASH],0,makeLocationExpr4],[XPathRelativeLocationPath,[XPathStep],31,makeLocationExpr5],[XPathRelativeLocationPath,[XPathRelativeLocationPath,TOK_SLASH,XPathStep],31,makeLocationExpr6],[XPathRelativeLocationPath,[XPathRelativeLocationPath,TOK_DSLASH,XPathStep],31,makeLocationExpr7],[XPathStep,[TOK_DOT],33,makeStepExpr1],[XPathStep,[TOK_DDOT],33,makeStepExpr2],[XPathStep,[TOK_AXISNAME,TOK_AXIS,XPathNodeTest],33,makeStepExpr3],[XPathStep,[TOK_AT,XPathNodeTest],33,makeStepExpr4],[XPathStep,[XPathNodeTest],33,makeStepExpr5],[XPathStep,[XPathStep,XPathPredicate],33,makeStepExpr6],[XPathNodeTest,[TOK_ASTERISK],33,makeNodeTestExpr1],[XPathNodeTest,[TOK_NCNAME,TOK_COLON,TOK_ASTERISK],33,makeNodeTestExpr2],[XPathNodeTest,[TOK_QNAME],33,makeNodeTestExpr3],[XPathNodeTest,[TOK_NODEO,TOK_PARENC],33,makeNodeTestExpr4],[XPathNodeTest,[TOK_NODEO,XPathLiteral,TOK_PARENC],33,makeNodeTestExpr5],[XPathPredicate,[TOK_BRACKO,XPathExpr,TOK_BRACKC],33,makePredicateExpr],[XPathPrimaryExpr,[XPathVariableReference],33,passExpr],[XPathPrimaryExpr,[TOK_PARENO,XPathExpr,TOK_PARENC],33,makePrimaryExpr],[XPathPrimaryExpr,[XPathLiteral],30,passExpr],[XPathPrimaryExpr,[XPathNumber],30,passExpr],[XPathPrimaryExpr,[XPathFunctionCall],31,passExpr],[XPathFunctionCall,[TOK_QNAME,TOK_PARENO,TOK_PARENC],-1,makeFunctionCallExpr1],[XPathFunctionCall,[TOK_QNAME,TOK_PARENO,XPathExpr,XPathArgumentRemainder,Q_MM,TOK_PARENC],-1,makeFunctionCallExpr2],[XPathArgumentRemainder,[TOK_COMMA,XPathExpr],-1,makeArgumentExpr],[XPathUnionExpr,[XPathPathExpr],20,passExpr],[XPathUnionExpr,[XPathUnionExpr,TOK_PIPE,XPathPathExpr],20,makeUnionExpr],[XPathPathExpr,[XPathLocationPath],20,passExpr],[XPathPathExpr,[XPathFilterExpr],19,passExpr],[XPathPathExpr,[XPathFilterExpr,TOK_SLASH,XPathRelativeLocationPath],19,makePathExpr1],[XPathPathExpr,[XPathFilterExpr,TOK_DSLASH,XPathRelativeLocationPath],19,makePathExpr2],[XPathFilterExpr,[XPathPrimaryExpr,XPathPredicate,Q_MM],31,makeFilterExpr],[XPathExpr,[XPathPrimaryExpr],16,passExpr],[XPathExpr,[XPathUnionExpr],16,passExpr],[XPathExpr,[TOK_MINUS,XPathExpr],-1,makeUnaryMinusExpr],[XPathExpr,[XPathExpr,TOK_OR,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_AND,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_EQ,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_NEQ,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_LT,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_LE,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_GT,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_GE,XPathExpr],-1,makeBinaryExpr],[XPathExpr,[XPathExpr,TOK_PLUS,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_MINUS,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_ASTERISK,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_DIV,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathExpr,[XPathExpr,TOK_MOD,XPathExpr],-1,makeBinaryExpr,ASSOC_LEFT],[XPathLiteral,[TOK_LITERALQ],-1,makeLiteralExpr],[XPathLiteral,[TOK_LITERALQQ],-1,makeLiteralExpr],[XPathNumber,[TOK_NUMBER],-1,makeNumberExpr],[XPathVariableReference,[TOK_DOLLAR,TOK_QNAME],200,makeVariableReference]];var xpathRules=[];function xpathParseInit(){if(xpathRules.length){return;}
xpathGrammarRules.sort(function(a,b){var la=a[1].length;var lb=b[1].length;if(la<lb){return 1;}else if(la>lb){return-1;}else{return 0;}});var k=1;for(var i=0;i<xpathNonTerminals.length;++i){xpathNonTerminals[i].key=k++;}
for(i=0;i<xpathTokenRules.length;++i){xpathTokenRules[i].key=k++;}
xpathLog('XPath parse INIT: '+k+' rules');function push_(array,position,element){if(!array[position]){array[position]=[];}
array[position].push(element);}
for(i=0;i<xpathGrammarRules.length;++i){var rule=xpathGrammarRules[i];var pattern=rule[1];for(var j=pattern.length-1;j>=0;--j){if(pattern[j]==Q_1M){push_(xpathRules,pattern[j-1].key,rule);break;}else if(pattern[j]==Q_MM||pattern[j]==Q_01){push_(xpathRules,pattern[j-1].key,rule);--j;}else{push_(xpathRules,pattern[j].key,rule);break;}}}
xpathLog('XPath parse INIT: '+xpathRules.length+' rule bins');var sum=0;mapExec(xpathRules,function(i){if(i){sum+=i.length;}});xpathLog('XPath parse INIT: '+(sum/xpathRules.length)+' average bin size');}
function xpathCollectDescendants(nodelist,node,opt_tagName){if(opt_tagName&&node.getElementsByTagName){copyArray(nodelist,node.getElementsByTagName(opt_tagName));return;}
for(var n=node.firstChild;n;n=n.nextSibling){nodelist.push(n);xpathCollectDescendants(nodelist,n);}}
function xpathExtractTagNameFromNodeTest(nodetest){if(nodetest instanceof NodeTestName){return nodetest.name;}else if(nodetest instanceof NodeTestAny||nodetest instanceof NodeTestElementOrAttribute){return"*";}}
function xpathCollectDescendantsReverse(nodelist,node){for(var n=node.lastChild;n;n=n.previousSibling){nodelist.push(n);xpathCollectDescendantsReverse(nodelist,n);}}
function xpathDomEval(expr,node){var expr1=xpathParse(expr);var ret=expr1.evaluate(new ExprContext(node));return ret;}
function xpathSort(input,sort){if(sort.length==0){return;}
var sortlist=[];for(var i=0;i<input.contextSize();++i){var node=input.nodelist[i];var sortitem={node:node,key:[]};var context=input.clone(node,0,[node]);for(var j=0;j<sort.length;++j){var s=sort[j];var value=s.expr.evaluate(context);var evalue;if(s.type=='text'){evalue=value.stringValue();}else if(s.type=='number'){evalue=value.numberValue();}
sortitem.key.push({value:evalue,order:s.order});}
sortitem.key.push({value:i,order:'ascending'});sortlist.push(sortitem);}
sortlist.sort(xpathSortByKey);var nodes=[];for(var i=0;i<sortlist.length;++i){nodes.push(sortlist[i].node);}
input.nodelist=nodes;input.setNode(0);}
function xpathSortByKey(v1,v2){for(var i=0;i<v1.key.length;++i){var o=v1.key[i].order=='descending'?-1:1;if(v1.key[i].value>v2.key[i].value){return+1*o;}else if(v1.key[i].value<v2.key[i].value){return-1*o;}}
return 0;}
function xpathEval(select,context){var expr=xpathParse(select);var ret=expr.evaluate(context);return ret;}
function xsltProcess(xmlDoc,stylesheet){var output=domCreateDocumentFragment(new XDocument);xsltProcessContext(new ExprContext(xmlDoc),stylesheet,output);var ret=xmlText(output);return ret;}
function xsltProcessContext(input,template,output){var outputDocument=xmlOwnerDocument(output);var nodename=template.nodeName.split(/:/);if(nodename.length==1||nodename[0]!='xsl'){xsltPassThrough(input,template,output,outputDocument);}else{switch(nodename[1]){case'apply-imports':alert('not implemented: '+nodename[1]);break;case'apply-templates':var select=xmlGetAttribute(template,'select');var nodes;if(select){nodes=xpathEval(select,input).nodeSetValue();}else{nodes=input.node.childNodes;}
var sortContext=input.clone(nodes[0],0,nodes);xsltWithParam(sortContext,template);xsltSort(sortContext,template);var mode=xmlGetAttribute(template,'mode');var top=template.ownerDocument.documentElement;var templates=[];for(var i=0;i<top.childNodes.length;++i){var c=top.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:template'&&c.getAttribute('mode')==mode){templates.push(c);}}
for(var j=0;j<sortContext.contextSize();++j){var nj=sortContext.nodelist[j];for(var i=0;i<templates.length;++i){xsltProcessContext(sortContext.clone(nj,j),templates[i],output);}}
break;case'attribute':var nameexpr=xmlGetAttribute(template,'name');var name=xsltAttributeValue(nameexpr,input);var node=domCreateDocumentFragment(outputDocument);xsltChildNodes(input,template,node);var value=xmlValue(node);domSetAttribute(output,name,value);break;case'attribute-set':alert('not implemented: '+nodename[1]);break;case'call-template':var name=xmlGetAttribute(template,'name');var top=template.ownerDocument.documentElement;var paramContext=input.clone();xsltWithParam(paramContext,template);for(var i=0;i<top.childNodes.length;++i){var c=top.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:template'&&domGetAttribute(c,'name')==name){xsltChildNodes(paramContext,c,output);break;}}
break;case'choose':xsltChoose(input,template,output);break;case'comment':var node=domCreateDocumentFragment(outputDocument);xsltChildNodes(input,template,node);var commentData=xmlValue(node);var commentNode=domCreateComment(outputDocument,commentData);output.appendChild(commentNode);break;case'copy':var node=xsltCopy(output,input.node,outputDocument);if(node){xsltChildNodes(input,template,node);}
break;case'copy-of':var select=xmlGetAttribute(template,'select');var value=xpathEval(select,input);if(value.type=='node-set'){var nodes=value.nodeSetValue();for(var i=0;i<nodes.length;++i){xsltCopyOf(output,nodes[i],outputDocument);}}else{var node=domCreateTextNode(outputDocument,value.stringValue());domAppendChild(output,node);}
break;case'decimal-format':alert('not implemented: '+nodename[1]);break;case'element':var nameexpr=xmlGetAttribute(template,'name');var name=xsltAttributeValue(nameexpr,input);var node=domCreateElement(outputDocument,name);domAppendChild(output,node);xsltChildNodes(input,template,node);break;case'fallback':alert('not implemented: '+nodename[1]);break;case'for-each':xsltForEach(input,template,output);break;case'if':var test=xmlGetAttribute(template,'test');if(xpathEval(test,input).booleanValue()){xsltChildNodes(input,template,output);}
break;case'import':alert('not implemented: '+nodename[1]);break;case'include':alert('not implemented: '+nodename[1]);break;case'key':alert('not implemented: '+nodename[1]);break;case'message':alert('not implemented: '+nodename[1]);break;case'namespace-alias':alert('not implemented: '+nodename[1]);break;case'number':alert('not implemented: '+nodename[1]);break;case'otherwise':alert('error if here: '+nodename[1]);break;case'output':break;case'preserve-space':alert('not implemented: '+nodename[1]);break;case'processing-instruction':alert('not implemented: '+nodename[1]);break;case'sort':break;case'strip-space':alert('not implemented: '+nodename[1]);break;case'stylesheet':case'transform':xsltChildNodes(input,template,output);break;case'template':var match=xmlGetAttribute(template,'match');if(match&&xsltMatch(match,input)){xsltChildNodes(input,template,output);}
break;case'text':var text=xmlValue(template);var node=domCreateTextNode(outputDocument,text);output.appendChild(node);break;case'value-of':var select=xmlGetAttribute(template,'select');var value=xpathEval(select,input).stringValue();var node=domCreateTextNode(outputDocument,value);output.appendChild(node);break;case'param':xsltVariable(input,template,false);break;case'variable':xsltVariable(input,template,true);break;case'when':alert('error if here: '+nodename[1]);break;case'with-param':alert('error if here: '+nodename[1]);break;default:alert('error if here: '+nodename[1]);break;}}}
function xsltWithParam(input,template){for(var i=0;i<template.childNodes.length;++i){var c=template.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:with-param'){xsltVariable(input,c,true);}}}
function xsltSort(input,template){var sort=[];for(var i=0;i<template.childNodes.length;++i){var c=template.childNodes[i];if(c.nodeType==DOM_ELEMENT_NODE&&c.nodeName=='xsl:sort'){var select=xmlGetAttribute(c,'select');var expr=xpathParse(select);var type=xmlGetAttribute(c,'data-type')||'text';var order=xmlGetAttribute(c,'order')||'ascending';sort.push({expr:expr,type:type,order:order});}}
xpathSort(input,sort);}
function xsltVariable(input,template,override){var name=xmlGetAttribute(template,'name');var select=xmlGetAttribute(template,'select');var value;if(template.childNodes.length>0){var root=domCreateDocumentFragment(template.ownerDocument);xsltChildNodes(input,template,root);value=new NodeSetValue([root]);}else if(select){value=xpathEval(select,input);}else{value=new StringValue('');}
if(override||!input.getVariable(name)){input.setVariable(name,value);}}
function xsltChoose(input,template,output){for(var i=0;i<template.childNodes.length;++i){var childNode=template.childNodes[i];if(childNode.nodeType!=DOM_ELEMENT_NODE){continue;}else if(childNode.nodeName=='xsl:when'){var test=xmlGetAttribute(childNode,'test');if(xpathEval(test,input).booleanValue()){xsltChildNodes(input,childNode,output);break;}}else if(childNode.nodeName=='xsl:otherwise'){xsltChildNodes(input,childNode,output);break;}}}
function xsltForEach(input,template,output){var select=xmlGetAttribute(template,'select');var nodes=xpathEval(select,input).nodeSetValue();var sortContext=input.clone(nodes[0],0,nodes);xsltSort(sortContext,template);for(var i=0;i<sortContext.contextSize();++i){var ni=sortContext.nodelist[i];xsltChildNodes(sortContext.clone(ni,i),template,output);}}
function xsltChildNodes(input,template,output){var context=input.clone();for(var i=0;i<template.childNodes.length;++i){xsltProcessContext(context,template.childNodes[i],output);}}
function xsltPassThrough(input,template,output,outputDocument){if(template.nodeType==DOM_TEXT_NODE){if(xsltPassText(template)){var node=domCreateTextNode(outputDocument,template.nodeValue);domAppendChild(output,node);}}else if(template.nodeType==DOM_ELEMENT_NODE){var node=domCreateElement(outputDocument,template.nodeName);for(var i=0;i<template.attributes.length;++i){var a=template.attributes[i];if(a){var name=a.nodeName;var value=xsltAttributeValue(a.nodeValue,input);domSetAttribute(node,name,value);}}
domAppendChild(output,node);xsltChildNodes(input,template,node);}else{xsltChildNodes(input,template,output);}}
function xsltPassText(template){if(!template.nodeValue.match(/^\s*$/)){return true;}
var element=template.parentNode;if(element.nodeName=='xsl:text'){return true;}
while(element&&element.nodeType==DOM_ELEMENT_NODE){var xmlspace=domGetAttribute(element,'xml:space');if(xmlspace){if(xmlspace=='default'){return false;}else if(xmlspace=='preserve'){return true;}}
element=element.parentNode;}
return false;}
function xsltAttributeValue(value,context){var parts=stringSplit(value,'{');if(parts.length==1){return value;}
var ret='';for(var i=0;i<parts.length;++i){var rp=stringSplit(parts[i],'}');if(rp.length!=2){ret+=parts[i];continue;}
var val=xpathEval(rp[0],context).stringValue();ret+=val+rp[1];}
return ret;}
function xmlGetAttribute(node,name){var value=domGetAttribute(node,name);if(value){return xmlResolveEntities(value);}else{return value;}};function xsltCopyOf(dst,src,dstDocument){if(src.nodeType==DOM_DOCUMENT_FRAGMENT_NODE||src.nodeType==DOM_DOCUMENT_NODE){for(var i=0;i<src.childNodes.length;++i){arguments.callee(dst,src.childNodes[i],dstDocument);}}else{var node=xsltCopy(dst,src,dstDocument);if(node){for(var i=0;i<src.attributes.length;++i){arguments.callee(node,src.attributes[i],dstDocument);}
for(var i=0;i<src.childNodes.length;++i){arguments.callee(node,src.childNodes[i],dstDocument);}}}}
function xsltCopy(dst,src,dstDocument){if(src.nodeType==DOM_ELEMENT_NODE){var node=domCreateElement(dstDocument,src.nodeName);domAppendChild(dst,node);return node;}
if(src.nodeType==DOM_TEXT_NODE){var node=domCreateTextNode(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_CDATA_SECTION_NODE){var node=domCreateCDATASection(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_COMMENT_NODE){var node=domCreateComment(dstDocument,src.nodeValue);domAppendChild(dst,node);}else if(src.nodeType==DOM_ATTRIBUTE_NODE){domSetAttribute(dst,src.nodeName,src.nodeValue);}
return null;}
function xsltMatch(match,context){var expr=xpathParse(match);var ret;if(expr.steps&&!expr.absolute&&expr.steps.length==1&&expr.steps[0].axis=='child'&&expr.steps[0].predicate.length==0){ret=expr.steps[0].nodetest.evaluate(context).booleanValue();}else{ret=false;var node=context.node;while(!ret&&node){var result=expr.evaluate(context.clone(node,0,[node])).nodeSetValue();for(var i=0;i<result.length;++i){if(result[i]==context.node){ret=true;break;}}
node=node.parentNode;}}
return ret;}
Config={WMC_URL:'ide/contexts/cabildo/cabildoBase.xml',WMC_COLLECTION_URL:'ide/contexts/cabildo/mineCollection.xml',EDITION_SUPPORT:true,WFSLAYERS:true,REPORT_NAME:'cabildo',ProxyHost:'../cgi-bin/proxy.cgi?url=',ADMIN_URL:'http://www.mapasdelapalma.es/IDEAdmin_Cabildo',LOGIN_URL:'http://www.mapasdelapalma.es/wsLogin/login?key=495d5f3988d11213827b325f4504a30f',FILEUPLOAD_URL:'http://www.mapasdelapalma.es/wsFileUpload/fileupload?key=495d5f3988d11213827b325f4504a30f',PRINTWMC_URL:'http://www.mapasdelapalma.es/wsPrintWMC/printwmc?key=495d5f3988d11213827b325f4504a30f',CSW_URL:"http://www.mapasdelapalma.es/geonetwork/srv/es/csw"};Login={LOGIN_URL:Config.ProxyHost+Config.LOGIN_URL,initialized:false,validated:false,userNameField:new Ext.form.TextField({fieldLabel:Locale.getText("txt_usuario"),name:'loginUsername',allowBlank:false}),passwordField:new Ext.form.TextField({fieldLabel:Locale.getText("txt_contraseña"),name:'loginPassword',inputType:'password',allowBlank:false,enableKeyEvents:true}),form:new Ext.FormPanel({labelWidth:100,frame:true,bodyStyle:'padding:5px 5px 0',autoHeight:true,defaultType:'textfield',defaultButton:0,buttons:[{text:Locale.getText("txt_aceptar"),formBind:true,handler:function(){Login.doValidation();}},{text:Locale.getText("txt_cancelar"),handler:function(){Login.close()}}]}),win:new Ext.Window({layout:'fit',modal:true,title:Locale.getText("txt_login"),id:'formLogin',width:300,autoHeight:true,resizable:false,draggable:false,closeAction:"hide",plain:true,border:false}),doValidation:function(){if(Login.form.getForm().isValid()){Login.form.getForm().submit({url:Login.LOGIN_URL,method:'POST',waitTitle:Locale.getText("msg_conectando"),waitMsg:Locale.getText("msg_enviando_datos"),success:function(){Login.success();},failure:function(form,action){if(action.failureType=='server'){obj=Ext.util.JSON.decode(action.response.responseText);UtilsUI.showMessageWindow('',obj.errors.reason,Ext.MessageBox.ERROR);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_sin_conexion_servicio_login"),Ext.MessageBox.ERROR);}
Login.form.getForm().reset();Login.userNameField.focus('',10);}})}},keyEventHandler:function(object,event){if(event.getCharCode()==event.ENTER)
Login.doValidation();},initialize:function(){if(!this.initialized){this.form.add(this.userNameField);this.form.add(this.passwordField);this.passwordField.on('keypress',this.keyEventHandler,this);this.win.add(this.form);this.win.on("close",this.close,this);this.initialized=true;}},checkLogin:function(){this.success();},success:function(){this.validated=true;Layout.toolBar.enableEditionItems(true);Layout.toolBar.loginButton.setIconClass('logout');Layout.showAdminFrame();this.close();},logout:function(){Layout.workLayerCombo.setValue(IDEOL.layersMgr.defaultVector.name);IDEOL.editionMgr.setLayerByName(IDEOL.layersMgr.defaultVector.name);Layout.toolBar.enableEditionItems(false);Layout.toolBar.loginButton.setIconClass('loginService');Layout.hideAdminFrame();this.validated=false;},show:function(){if(!this.validated){this.form.getForm().reset();this.win.show();this.userNameField.focus('',10);}
else{this.logout();}},close:function(){this.win.hide();}};Util={};Util.getIconUrl=function(wmsUrl,options){if(!options.layer){OpenLayers.Console.warn('Missing required layer option in mapfish.Util.getIconUrl');return'';}
if(wmsUrl.indexOf("?")<0){wmsUrl+="?";}else if(wmsUrl.lastIndexOf('&')!=(wmsUrl.length-1)){if(wmsUrl.indexOf("?")!=(wmsUrl.length-1)){wmsUrl+="&";}}
var options=OpenLayers.Util.extend({layer:"",service:"WMS",version:"1.1.1",request:"GetLegendGraphic",format:"image/png",width:22,height:22},options);options=OpenLayers.Util.upperCaseObject(options);return wmsUrl+OpenLayers.Util.getParameterString(options);};Util.fixArray=function(subs){if(subs==''||subs==null){return[];}else if(subs instanceof Array){return subs;}else{return subs.split(',');}};Util.encode=function(string){string=string.replace(/rn/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;};Util.decode=function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;};UtilsUI={showMessageWindow:function(title,msg,icon){Ext.MessageBox.show({title:title,msg:msg,buttons:Ext.MessageBox.OK,icon:icon});}};WFSLayers={layers:{incidenciasCabildo:null},initialize:function(){this.layers.incidenciasCabildo=new OpenLayers.Layer.WFS("Incidencias","http://www.mapasdelapalma.es/geoserver/wfs",{typename:'cabildo:incidencias'},{typename:"incidencias",featureNS:"http://cabildo.iver.es",projection:"EPSG:32628",extractAttributes:true,isBaseLayer:false,visibility:false,displayInLayerSwitcher:false,commitSuccess:this.onCommitSuccess,commitFailure:this.onCommitFailure});}};InfoWFSBBoxControl=OpenLayers.Class(OpenLayers.Control,{layer:null,describeFeature:null,out:false,draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.showInfo},{keyMask:this.keyMask});},initialize:function(layer,options){this.layer=layer;OpenLayers.Control.prototype.initialize.apply(this,[options]);},showInfo:function(position){if(this.layer instanceof OpenLayers.Layer.WFS){var bounds=this.getBounds(position);if(bounds!=null){bounds.transform(new OpenLayers.Projection(this.map.getProjection()),new OpenLayers.Projection(this.layer.projection.projCode));IDEOL.infoWFSWindow.show(this.layer,bounds);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_trabajo"),Ext.MessageBox.WARNING);}},getBounds:function(position){var bounds=null;if(position instanceof OpenLayers.Bounds){if(!this.out){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}else{var pixWidth=Math.abs(position.right-position.left);var pixHeight=Math.abs(position.top-position.bottom);var zoomFactor=Math.min((this.map.size.h/pixHeight),(this.map.size.w/pixWidth));var extent=this.map.getExtent();var center=this.map.getLonLatFromPixel(position.getCenterPixel());var xmin=center.lon-(extent.getWidth()/2)*zoomFactor;var xmax=center.lon+(extent.getWidth()/2)*zoomFactor;var ymin=center.lat-(extent.getHeight()/2)*zoomFactor;var ymax=center.lat+(extent.getHeight()/2)*zoomFactor;bounds=new OpenLayers.Bounds(xmin,ymin,xmax,ymax);}}
else{if(!this.out){this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()+1);}else{this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()-1);}}
return bounds;},CLASS_NAME:"InfoWFSControl"});InfoWMSControl=OpenLayers.Class(OpenLayers.Control,{map:null,layer:null,xslMetadataURL:'ide/xsl/infoWMS.xsl',xslMetadataString:null,initialize:function(map,options){this.map=map;OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{'click':this.onClick},this.handlerOptions);},onClick:function(evt){var selectedNode=IDEOL.toc.selectedNode;if(selectedNode){var arrayLayers=this.map.getLayersByName(selectedNode.text);if(arrayLayers.length==1)
this.layer=arrayLayers[0];if(this.layer!=null){if(this.layer.queryable){if(this.layer.getVisibility()){var xy=evt.xy;var featuresString=WMSMgr.getFeaturesString(this.layer,xy);this.showXSLWMSInfo(featuresString);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_capa_seleccionada_no_visible_mapa"),Ext.MessageBox.WARNING);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_capa_seleccionada_no_consultable"),Ext.MessageBox.WARNING);}}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_consultable_obtener_info"),Ext.MessageBox.WARNING);}},showXSLWMSInfo:function(featuresString){if(!this.xslMetadataString){this.xslMetadataString=this.getXSLString(this.xslMetadataURL);}
IDEOL.infoXSLWMSWindow.show(featuresString,this.xslMetadataString);},getXSLString:function(url){var request=OpenLayers.Request.GET({url:url,async:false});return request.responseText;},CLASS_NAME:"InfoWMSControl"});InfoImagesControl=OpenLayers.Class(OpenLayers.Control,{map:null,layer:null,initialize:function(map,options){this.map=map;OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{'click':this.onClick},this.handlerOptions);},onClick:function(evt){var selectedNode=IDEOL.toc.selectedNode;if(selectedNode){var arrayLayers=this.map.getLayersByName(selectedNode.text);if(arrayLayers.length==1)
this.layer=arrayLayers[0];if(this.layer!=null){if(this.layer.getVisibility()){var xy=evt.xy;var features=WMSMgr.getFeatures(this.layer,xy);IDEOL.infoImagesWindow.show(features,this.layer.name);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_capa_seleccionada_no_visible_mapa"),Ext.MessageBox.WARNING);}
OpenLayers.Event.stop(evt);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_consultable_obtener_info"),Ext.MessageBox.WARNING);}},CLASS_NAME:"InfoImagesControl"});InfoLinksControl=OpenLayers.Class(OpenLayers.Control,{map:null,layer:null,initialize:function(map,options){this.map=map;OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{'click':this.onClick},this.handlerOptions);},onClick:function(evt){var selectedNode=IDEOL.toc.selectedNode;if(selectedNode){var arrayLayers=this.map.getLayersByName(selectedNode.text);if(arrayLayers.length==1)
this.layer=arrayLayers[0];if(this.layer!=null){if(this.layer.queryable){if(this.layer.getVisibility()){var xy=evt.xy;var features=WMSMgr.getFeatures(this.layer,xy);IDEOL.infoLinksWindow.show(features,this.layer.name);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_capa_seleccionada_no_visible_mapa"),Ext.MessageBox.WARNING);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_capa_seleccionada_no_consultable"),Ext.MessageBox.WARNING);}}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_consultable_obtener_info"),Ext.MessageBox.WARNING);}
OpenLayers.Event.stop(evt);},CLASS_NAME:"InfoLinksControl"});StreetViewControl=OpenLayers.Class(OpenLayers.Control,{map:null,layer:null,initialize:function(map,options){this.map=map;OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{'click':this.onClick},this.handlerOptions);},onClick:function(evt){var lonlat=this.map.getLonLatFromViewPortPx(evt.xy);IDEOL.streetViewWindow.show(lonlat);},CLASS_NAME:"StreetViewControl"});IncidenciasControl=OpenLayers.Class(OpenLayers.Control,{map:null,initialize:function(map,options){this.map=map;OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{'click':this.onClick},this.handlerOptions);},onClick:function(evt){var lonlat=this.map.getLonLatFromViewPortPx(evt.xy);IDEOL.incidencias.show(lonlat);},CLASS_NAME:"IncidenciasControl"});ProjectionCombo=Ext.extend(Ext.form.ComboBox,{id:'projectionCombo',displayField:'desc',valueField:'projection',mode:'local',triggerAction:'all',typeAhead:true,selectOnFocus:true,editable:false,width:100,store:new Ext.data.SimpleStore({fields:['desc','projection'],data:[['EPSG:32628 (UTM28N)','EPSG:32628'],['EPSG:4326 (Lat-Long)','EPSG:4326']]}),initComponent:function(){ProjectionCombo.superclass.initComponent.call(this);this.on('expand',function(comboBox){this.list.setWidth('auto');this.innerList.setWidth('auto');},this,{single:true});this.on('beforeselect',function(combo,record,index){combo.collapse();if(combo.getRawValue()!=record.data.projection){var map=IDEOL.mapMgr.map;IDEOL.initialize(map.contextURL,"",record.data[combo.valueField]);}
combo.setRawValue(record.data[combo.valueField]);return false;},this);}});LocaleCombo=Ext.extend(Ext.form.ComboBox,{displayField:'language',typeAhead:true,mode:'local',triggerAction:'all',emptyText:Locale.getText("msg_seleccionar_idioma"),selectOnFocus:true,editable:false,width:70,iconClsField:'flag',listeners:{beforeselect:function(combo,record,index){if(combo.getValue()!=record.data.language){window.location.search=Ext.urlEncode({"lang":record.data.code});}}},store:new Ext.data.SimpleStore({fields:['code','language','charset','flag'],data:Languages}),setDefaultLocale:function(){var record;if(Locale.lang){record=this.store.data.find(function(item,key){if(item.data.code==Locale.lang){return true;}
return false;});}
if(record){this.setValue(record.data.language);}},initComponent:function(){Ext.apply(this,{tpl:'<tpl for=".">'
+'<div class="x-combo-list-item locale-icon-combo-item '
+'{'+this.iconClsField+'}">'
+'{'+this.displayField+'}'
+'</div></tpl>'});LocaleCombo.superclass.initComponent.call(this);this.on('expand',function(comboBox){this.list.setWidth('auto');this.innerList.setWidth('auto');},this,{single:true});this.setDefaultLocale();},onRender:function(ct,position){LocaleCombo.superclass.onRender.call(this,ct,position);this.wrap.applyStyles({position:'relative'});this.el.addClass('locale-icon-combo-input');this.icon=Ext.DomHelper.append(this.el.up('div.x-form-field-wrap'),{tag:'div',style:'position:absolute'});},setIconCls:function(){var rec=this.store.query(this.valueField,this.getValue()).itemAt(0);if(rec){this.icon.className='locale-icon-combo-icon '+rec.get(this.iconClsField);}},setValue:function(value){LocaleCombo.superclass.setValue.call(this,value);this.setIconCls();}});WorkLayerCombo=Ext.extend(Ext.form.ComboBox,{id:'workLayerCombo',displayField:'layerName',mode:'local',triggerAction:'all',typeAhead:true,forceSelection:true,selectOnFocus:true,editable:false,width:100,value:'Default',listeners:{select:function(combo,record,index){IDEOL.editionMgr.setLayerByName(combo.lastSelectionText);},render:function(){}},store:new Ext.data.SimpleStore({fields:['layerName'],data:[]}),initComponent:function(){WorkLayerCombo.superclass.initComponent.call(this);this.on('expand',function(comboBox){this.list.setWidth('auto');this.innerList.setWidth('auto');},this,{single:true});},loadLayers:function(map){var layers=map.layers;var layerNames=[];for(key in layers){if(layers[key]instanceof OpenLayers.Layer.WFS||layers[key]instanceof OpenLayers.Layer.Vector)
layerNames.push([layers[key].name]);}
this.store.loadData(layerNames);}});ToolBar=Ext.extend(Ext.Toolbar,{map:null,id:'toolbar',height:28,listeners:{render:function(){this.addItems(this.mapButtons);this.addSeparator();this.addItems(this.toolsButtons);this.addSeparator();if(Config.EDITION_SUPPORT){this.addItem(this.loginButton);this.addSeparator();}
this.addItems(this.editionButtons);this.enableEditionItems(false);}},mapButtons:{localeCombo:new LocaleCombo(),zoomFull:new Ext.Toolbar.Button({iconCls:'zoomfull',tooltip:Locale.getText("txt_zoom_completo"),handler:function(){IDEOL.controlsMgr.controls.zoomFull.trigger();}}),zoomIn:new Ext.Toolbar.Button({iconCls:'zoomin',tooltip:Locale.getText("txt_zoom_mas"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.zoomIn)},toggleGroup:'map'}),zoomOut:new Ext.Toolbar.Button({iconCls:'zoomout',tooltip:Locale.getText("txt_zoom_menos"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.zoomOut)},toggleGroup:'map'}),pan:new Ext.Toolbar.Button({iconCls:'pan',tooltip:Locale.getText("txt_desplazar_mapa"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.pan)},toggleGroup:'map',enableToggle:true,pressed:true}),back:new Ext.Toolbar.Button({iconCls:'back',tooltip:Locale.getText("txt_vista_anterior"),handler:function(){IDEOL.controlsMgr.controls.nav.previous.trigger();}}),next:new Ext.Toolbar.Button({iconCls:'next',tooltip:Locale.getText("txt_vista_siguiente"),handler:function(){IDEOL.controlsMgr.controls.nav.next.trigger();}}),measureDistance:new Ext.Toolbar.Button({iconCls:'distance',tooltip:Locale.getText("txt_medir_distancias"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.measureDistance);},toggleGroup:'map'}),measureArea:new Ext.Toolbar.Button({iconCls:'area',tooltip:Locale.getText("txt_medir_areas"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.measureArea);},toggleGroup:'map'})},toolsButtons:{incidencias:new Ext.Toolbar.Button({iconCls:'incidencias',tooltip:Locale.getText("txt_incidencias"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.incidencias);},toggleGroup:'map'}),infoLinks:new Ext.Toolbar.Button({iconCls:'infoImages',tooltip:{title:Locale.getText("txt_informacion_imagenes"),text:Locale.getText("msg_descripcion_herramienta_imagenes")},handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.infoLinks);},toggleGroup:'map'}),infoWMS:new Ext.Toolbar.Button({iconCls:'infoWMS',tooltip:Locale.getText("txt_informacion_wms"),handler:function(){IDEOL.controlsMgr.activateControl(IDEOL.controlsMgr.controls.infoWMS);},toggleGroup:'map'}),catalogo:new Ext.Toolbar.Button({iconCls:'catalogo',tooltip:Locale.getText("txt_catalogo"),handler:function(){IDEOL.cswClient.show();}}),uploadWMCFile:new Ext.Toolbar.Button({iconCls:'uploadWMCFileButton',tooltip:Locale.getText("txt_cargar_mapa"),handler:function(){IDEOL.uploadFileWindow.show();}}),saveWMCFile:new Ext.Toolbar.Button({iconCls:'saveWMCFileButton',tooltip:Locale.getText("txt_exportar_mapa"),handler:function(){IDEOL.saveFileWindow.show();}}),printWMCFile:new Ext.Toolbar.Button({iconCls:'printWMCFileButton',tooltip:Locale.getText("txt_imprimir_mapa"),handler:function(){PrintMgr.print(Config.REPORT_NAME);}}),wmsService:new Ext.Toolbar.Button({iconCls:'wmsService',tooltip:Locale.getText("txt_servicio_wms"),handler:function(){IDEOL.wmsService.show();}}),cleanMap:new Ext.Toolbar.Button({iconCls:'cleanMap',tooltip:Locale.getText("txt_limpiar_mapa"),handler:function(){IDEOL.layersMgr.cleanLayers();}}),help:new Ext.Toolbar.Button({iconCls:'help',tooltip:Locale.getText("txt_ayuda"),handler:function(){IDEOL.helpWindow.show();}}),separator1:new Ext.Toolbar.Separator(),projectionCombo:new ProjectionCombo()},loginButton:new Ext.Toolbar.Button({iconCls:'loginService',handler:function(){Login.show();}}),editionButtons:{infoWFSBBox:new Ext.Toolbar.Button({iconCls:'infoWFSBBox',tooltip:Locale.getText("txt_informacion_wfs"),handler:function(){IDEOL.editionMgr.activateControl(IDEOL.editionMgr.controls.infoWFSBBox);},toggleGroup:'map'}),wfsService:new Ext.Toolbar.Button({iconCls:'wfsService',tooltip:{title:Locale.getText("txt_servicio_wfs"),text:''},handler:function(){IDEOL.wfsService.show(IDEOL.editionMgr.layer);}}),workLayerCombo:new WorkLayerCombo()},visibleItems:function(items,bool){for(key in items){items[key].setVisible(bool);}},enableItems:function(items,bool){for(key in items){items[key].setDisabled(bool);}},enableEditionItems:function(bool){this.visibleItems(this.editionButtons,bool);},addSeparator:function(){this.addItem(new Ext.Toolbar.Separator());},addItems:function(items){for(key in items)
this.addItem(items[key])},initComponent:function(){ToolBar.superclass.initComponent.call(this);}});MainMenuButton=Ext.extend(Ext.Toolbar.Button,{text:Locale.getText("txt_menu"),menu:new Ext.menu.Menu(),initialize:function(){this.dateItem.menu=this.dateMenu;this.colorItem.menu=this.colorMenu;this.menu.add(this.dateItem);this.menu.add(this.colorItem);},dateItem:new Ext.menu.Item({text:'Choose a Date',iconCls:'calendar'}),colorItem:new Ext.menu.Item({text:'Choose a Color',iconCls:'calendar'}),dateMenu:new Ext.menu.DateMenu({scope:this,handler:function(dp,date){alert('Date Selected '+date.format('M j, Y'));}}),colorMenu:new Ext.menu.ColorMenu({scope:this,handler:function(cm,color){alert('Color Selected '+color);}}),initComponent:function(){MainMenuButton.superclass.initComponent.call(this);this.initialize();}});MenuBar=Ext.extend(Ext.Toolbar,{height:25,listeners:{render:function(){}},initComponent:function(){MenuBar.superclass.initComponent.call(this);}});StatusBar=Ext.extend(Ext.StatusBar,{defaultText:'',defaultIconCls:'statusBarIcon',items:[{xtype:"panel",contentEl:"mousePositionInfo",border:false},'-',{xtype:"panel",contentEl:"scalePanel",border:false},'-',{xtype:"panel",contentEl:"measureInfo",border:false}],border:false,initComponent:function(){StatusBar.superclass.initComponent.call(this);}});RadioTreeNodeUI=Ext.extend(Ext.tree.TreeNodeUI,{renderElements:function(n,a,targetNode,bulkRender){this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():'';var cb=typeof a.checked=='boolean';var radioGrp=n.attributes.radioGrp||"radioGrp";var href=a.href?a.href:Ext.isGecko?"":"#";var buf=['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',a.cls,'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />','<img src="',a.icon||this.emptyIcon,'" class="x-tree-node-icon',(a.icon?" x-tree-node-inline-icon":""),(a.iconCls?" "+a.iconCls:""),'" unselectable="on" />',cb?('<input class="x-tree-node-cb" type="radio" id="'+n.id+'" name="'+radioGrp+'" '+(a.checked?'checked="checked" />':'/>')):'','<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',a.hrefTarget?' target="'+a.hrefTarget+'"':"",'><span unselectable="on">',n.text,"</span></a></div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join('');var nel;if(bulkRender!==true&&n.nextSibling&&(nel=n.nextSibling.ui.getEl())){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",nel,buf);}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",targetNode,buf);}
this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.childNodes;this.indentNode=cs[0];this.ecNode=cs[1];this.iconNode=cs[2];var index=3;if(cb){this.checkbox=cs[3];index++;}
this.anchor=cs[index];this.textNode=cs[index].firstChild;},_unused_renderElements:function(n,a,targetNode,bulkRender){RadioTreeNodeUI.superclass.renderElements.apply(this,arguments);var cbNode=Ext.DomQuery.selectNode(".x-tree-node-cb",this.elNode);var radioGrp=n.attributes.radioGrp||"radioGrp";cbNode.setAttribute("type","radio");cbNode.setAttribute("id",n.id);cbNode.setAttribute("name",radioGrp);},onRadioChange:function(){var checked=this.checkbox.checked;this.node.attributes.checked=checked;this.fireEvent('radiochange',this.node,checked);}});LayerTreeEventModel=Ext.extend(Ext.tree.TreeEventModel,{delegateClick:function(e,t){if(!this.beforeEvent(e)){return;}
if(e.getTarget('input[type=checkbox]',1)){this.onCheckboxClick(e,this.getNode(e));}
else if(e.getTarget('input[type=radio]',1)){this.onRadioClick(e,this.getNode(e));}
else if(e.getTarget('.x-tree-ec-icon',1)){this.onIconClick(e,this.getNode(e));}
else if(this.getNodeTarget(e)){this.onNodeClick(e,this.getNode(e));}},onRadioClick:function(e,node){if(!node.ui.onRadioChange){OpenLayers.Console.error("Invalid TreeNodeUI Class, no "+"onRadioChange is available");return;}
node.ui.onRadioChange(e);}});LayerTree=function(config){Ext.apply(this,config);LayerTree.superclass.constructor.call(this);};Ext.extend(LayerTree,Ext.tree.TreePanel,{separator:":",model:null,showWmsLegend:false,rootVisible:false,animate:true,autoScroll:true,loader:new Ext.tree.TreeLoader({}),enableDD:false,containerScroll:true,ascending:true,_automaticModel:true,layerNameToLayer:{},baseLayerNames:[],layersWithSublayers:{},layerToNodeIds:{},nodeIdToNode:{},nodeIdToLayers:{},hasCheckbox:function(node){return typeof(node.attributes.checked)=="boolean";},setNodeChecked:function(nodeOrId,checked,fireEvent){var node=(nodeOrId instanceof Ext.data.Node)?nodeOrId:this.getNodeById(nodeOrId);if(!node||!this.hasCheckbox(node)){return;}
if(checked===undefined){checked=!node.attributes.checked;}
node.attributes.checked=checked;if(node.ui&&node.ui.checkbox){node.ui.checkbox.checked=checked;}
if(fireEvent||(fireEvent===undefined)){node.fireEvent('checkchange',node,checked);}},_updateCachedObjects:function(){if(!this.map){OpenLayers.Console.error("map Object needs to be available when "+"calling _updateCachedObjects");return;}
this.layerNameToLayer={};this.baseLayerNames=[];this.layersWithSublayers={};this.layerToNodeIds={};this.nodeIdToNode={};this.nodeIdToLayers={};Ext.each(this.map.layers,function(layer){var name=layer.name;this.layerNameToLayer[name]=layer;if(layer.isBaseLayer)
this.baseLayerNames.push(name);},this);this.getRootNode().cascade(function(node){if(!node.attributes.layerNames)
return true;var layerNames=node.attributes.layerNames;for(var i=0;i<layerNames.length;i++){var name=layerNames[i];if(name.indexOf(this.separator)!=-1){var name=name.split(this.separator)[0];this.layersWithSublayers[name]=true;}
if(!this.nodeIdToLayers[node.id])
this.nodeIdToLayers[node.id]=[];this.nodeIdToLayers[node.id].push(this.layerNameToLayer[name]);}},this);this.getRootNode().cascade(function(node){var checked=node.attributes.checked;var layerNames=node.attributes.layerNames;if(!layerNames)
return;for(var i=0;i<layerNames.length;i++){var layerName=layerNames[i];if(!layerName)
continue;if(!this.layerToNodeIds[layerName])
this.layerToNodeIds[layerName]=[];this.layerToNodeIds[layerName].push(node.id);this.nodeIdToNode[node.id]=node;}},this);},_updateCheckboxAncestors:function(){var unvisitedNodeIds={};var tree=this;function updateNodeCheckbox(node){if(!tree.hasCheckbox(node)){throw new Error(arguments.callee.name+" should only be called on checkbox nodes");}
var checkboxChildren=[];node.eachChild(function(child){if(tree.hasCheckbox(child))
checkboxChildren.push(child);},this);if(checkboxChildren.length==0){return node.attributes.checked;}
var allChecked=true;Ext.each(checkboxChildren,function(child){if(!updateNodeCheckbox(child)){allChecked=false;return false;}},this);tree.setNodeChecked(node,allChecked,false);delete unvisitedNodeIds[node.id];return allChecked;}
var checkboxNodes=[];this.getRootNode().cascade(function(node){if(this.hasCheckbox(node)){checkboxNodes.push(node);unvisitedNodeIds[node.id]=true;}},this);var node;while(node=checkboxNodes.shift()){if(unvisitedNodeIds[node.id])
updateNodeCheckbox(node);}},_handleModelChange:function LT__handleModelChange(clickedNode,checked){if(clickedNode){clickedNode.cascade(function(node){this.setNodeChecked(node,checked,false);},this);}
this._updateCheckboxAncestors();if(!this.map){return;}
this._updateCachedObjects();function getVisibilityFromMap(){var layerVisibility={};Ext.each(this.map.layers,function(layer){var name=layer.name;layerVisibility[name]=layer.visibility;if(!(layer instanceof OpenLayers.Layer.WMS)&&!(layer instanceof OpenLayers.Layer.WMS.Untiled)&&!(layer instanceof OpenLayers.Layer.MapServer)&&!(layer instanceof OpenLayers.Layer.Google))
{return;}
if(!this.layersWithSublayers[layer.name])
return;if(layer.isBaseLayer){OpenLayers.Console.error("Using sublayers on a base layer "+"is not supported (base layer is "+
name+")");}
if(!layer._origLayers){layer._origLayers=layer.params.LAYERS||layer.params.layers;}
var sublayers=layer._origLayers;if(sublayers instanceof Array){for(var j=0;j<sublayers.length;j++){var sublayer=sublayers[j];layerVisibility[name+this.separator+sublayer]=layer.visibility;}}},this);return layerVisibility;}
function updateVisibilityFromTree(layerVisibility){var forcedVisibility={};this.getRootNode().cascade(function(node){var checked=node.attributes.checked;var layerNames=node.attributes.layerNames;var radioGrp=null;if(!layerNames)
return;for(var i=0;i<layerNames.length;i++){var layerName=layerNames[i];if(!layerName)
continue;if(layerVisibility[layerName]==undefined)
OpenLayers.Console.error("Invalid layer: ",layerName);if(node.attributes.radio){radioGrp=node.attributes.radioGrp||"radioGrp";if(!radioButton[radioGrp])
radioButton[radioGrp]={};radioButton[radioGrp][layerName]=checked;}
if(forcedVisibility[layerName])
continue;if(node==clickedNode){if(this.baseLayerNames.indexOf(layerName)!=-1){clickedBaseLayer=layerName;}
if(radioGrp){clickedRadioButton[0]=radioGrp;clickedRadioButton[1]=layerName;}
forcedVisibility[layerName]=true;}
layerVisibility[layerName]=checked;}},this);return layerVisibility;}
function applyBaseLayerRestriction(layerVisibility,clickedBaseLayer,currentBaseLayerName){var numBaseLayer=0;for(var i=0;i<this.baseLayerNames.length;i++){if(layerVisibility[this.baseLayerNames[i]])
numBaseLayer++;}
if(numBaseLayer==1)
return layerVisibility;for(var i=0;i<this.baseLayerNames.length;i++){layerVisibility[this.baseLayerNames[i]]=false;}
if(clickedBaseLayer){layerVisibility[clickedBaseLayer]=true;return layerVisibility;}
if(!currentBaseLayerName)
return layerVisibility;layerVisibility[currentBaseLayerName]=true;return layerVisibility;}
function applyRadioButtonRestriction(layerVisibility,clickedRadioButton,radioButton){for(var radioGrp in radioButton){for(var layerName in radioButton[radioGrp]){if(clickedRadioButton[0]==radioGrp){layerVisibility[layerName]=layerName==clickedRadioButton[1];}else{layerVisibility[layerName]=radioButton[radioGrp][layerName];}}}
return layerVisibility;}
function updateTreeFromVisibility(layerVisibility){for(var layerName in layerVisibility){var nodeIds=this.layerToNodeIds[layerName];if(!nodeIds)
continue;for(var i=0;i<nodeIds.length;i++){var node=this.nodeIdToNode[nodeIds[i]];if(!node)
continue;var layerNames=node.attributes.layerNames;if(!layerNames){OpenLayers.Console.error("unexpected state");continue;}
var allChecked=true;for(var j=0;j<layerNames.length;j++){var layerName=layerNames[j];if(!layerName)
continue;if(!layerVisibility[layerName]){allChecked=false;break;}}
this.setNodeChecked(node,allChecked,false);}}}
function updateMapFromVisibility(layerVisibility){var wmsLayers={};for(var layerName in layerVisibility){var visible=layerVisibility[layerName];var splitName=layerName.split(this.separator);if(splitName.length!=2)
continue;delete layerVisibility[layerName];layerName=splitName[0];var sublayerName=splitName[1];if(!wmsLayers[layerName]){wmsLayers[layerName]=[];}
if(visible){wmsLayers[layerName].push(sublayerName);}}
for(layerName in wmsLayers){if(layerVisibility[layerName]!==undefined)
delete layerVisibility[layerName];}
for(var layerName in layerVisibility){var layer=this.layerNameToLayer[layerName];if(!layer){OpenLayers.Console.error("Non existing layer name",layerName);continue;}
if(this.baseLayerNames.indexOf(layerName)!=-1){if(layerVisibility[layerName]){this.map.setBaseLayer(layer);}}else{layer.setVisibility(layerVisibility[layerName]);}}
for(var layerName in wmsLayers){var layer=this.layerNameToLayer[layerName];var sublayers=wmsLayers[layerName];if(layer.isBaseLayer){OpenLayers.Console.error("base layer for sublayer "+"are not supported");return;}
if(sublayers.length==0){layer.setVisibility(false,true);}else{if(!this.enableDD){if(!layer._origLayers){OpenLayers.Console.error("Assertion failure");}
var origLayers=layer._origLayers;var orderedLayers=[];for(var i=0;i<origLayers.length;i++){var l=origLayers[i];if(sublayers.indexOf(l)!=-1)
orderedLayers.push(l);}
sublayers=orderedLayers;}
var layerParamName=layer.params.LAYERS?"LAYERS":"layers";if(!mapfish.Util.arrayEqual(layer.params[layerParamName],sublayers)){layer.params[layerParamName]=sublayers;layer.redraw();}
layer.setVisibility(true,true);}}}
var currentBaseLayerName;if(this.map.baseLayer)
currentBaseLayerName=this.map.baseLayer.name;var clickedBaseLayer;var radioButton={};var clickedRadioButton=[];var layerVisibility=getVisibilityFromMap.call(this);layerVisibility=updateVisibilityFromTree.call(this,layerVisibility);applyBaseLayerRestriction.call(this,layerVisibility,clickedBaseLayer,currentBaseLayerName);applyRadioButtonRestriction.call(this,layerVisibility,clickedRadioButton,radioButton);updateTreeFromVisibility.call(this,layerVisibility);updateMapFromVisibility.call(this,layerVisibility);},_extractOLModel:function LT__extractOLModel(){var layers=[];var layersArray=this.map.layers.slice();if(!this.ascending){layersArray.reverse();}
for(var i=0;i<layersArray.length;i++){var l=layersArray[i];var wmsChildren=[];if(l instanceof OpenLayers.Layer.WMS||l instanceof OpenLayers.Layer.WMS.Untiled||l instanceof OpenLayers.Layer.MapServer){var sublayers=l.params.LAYERS||l.params.layers;if(sublayers instanceof Array){for(var j=0;j<sublayers.length;j++){var w=sublayers[j];var iconUrl;if(this.showWmsLegend){iconUrl=mapfish.Util.getIconUrl(l.url,{layer:w});}
var wmsChild={text:w,checked:l.getVisibility(),icon:iconUrl,layerName:l.name+this.separator+w,children:[],cls:"cf-wms-node"};if(this.ascending){wmsChildren.push(wmsChild);}else{wmsChildren.unshift(wmsChild);}}}}
var info={text:l.name,checked:l.getVisibility(),layerName:(wmsChildren.length>0?null:l.name),children:wmsChildren};if(!l.displayInLayerSwitcher){info.uiProvider=function(){};info.uiProvider.prototype={render:function(){},renderIndent:function(){}};}
layers.push(info);}
return layers;},_updateOrder:function(){this._updateCachedObjects();function layerIndex(layers,name){for(var i=0;i<layers.length;i++){var l=layers[i];if(l.name==name)
return i;}
return-1;}
var orderedLayers=this.map.layers.slice();var seenLayers={};var nodes=[];this.getRootNode().cascade(function(node){if(this.ascending)
nodes.push(node);else
nodes.unshift(node);},this);Ext.each(nodes,function(node){var layers=this.nodeIdToLayers[node.id];if(!layers)
return;Ext.each(layers,function(layer){var layerName=layer.name;if(seenLayers[layerName])
return;seenLayers[layerName]=true;var index=layerIndex(orderedLayers,layerName);if(index==-1||!this.layerNameToLayer[layerName]){throw new Error("Layer "+layerName+" not available");}
orderedLayers.splice(index,1);orderedLayers.push(this.layerNameToLayer[layerName]);},this);},this);this._updateCheckboxAncestors();this.map.layers=orderedLayers;for(var i=0;i<this.map.layers.length;i++){this.map.setLayerZIndex(this.map.layers[i],i);}},_fixupModel:function(){this.getRootNode().cascade(function(node){var attrs=node.attributes;if(!attrs.layerNames&&attrs.layerName){attrs.layerNames=[attrs.layerName];delete attrs.layerName;}},this);if(this.map)
this._updateCachedObjects();this.getRootNode().cascade(function(node){var layers;if(!node.attributes.radio&&(!this.map||!(layers=this.nodeIdToLayers[node.id])))
return;var isBaseLayer=false;if(layers){isBaseLayer=true;Ext.each(layers,function(layer){if(!layer.isBaseLayer){isBaseLayer=false;return false;}},this);}
if(isBaseLayer||node.attributes.radio){node.attributes.uiProvider=RadioTreeNodeUI;if(node.ui)
node.ui=new RadioTreeNodeUI(node);}},this);},initComponent:function(){this.eventModel=new LayerTreeEventModel(this);LayerTree.superclass.initComponent.call(this);this.addListener("checkchange",function checkChange(node,checked){this._handleModelChange(node,checked);},this);this.addListener("radiochange",function radioChange(node,checked){this._handleModelChange(node,checked);},this);this._automaticModel=!this.model;if(!this.model){this.model=this._extractOLModel();}
var root={text:'Capas',draggable:false,id:'source',children:this.model,leaf:false};function buildTree(attributes){var node=new Ext.tree.TreeNode(attributes);var cs=attributes.children;node.leaf=!cs;if(!cs)
return node;for(var i=0;i<cs.length;i++){if(!cs[i]){continue;}
node.appendChild(buildTree(cs[i]));}
return node;}
var rootNode=buildTree(root);this.setRootNode(rootNode);this._fixupModel();this.addListener("dragdrop",function(){this._updateOrder(arguments);},this);if(!this._automaticModel){this._handleModelChange(null,null);if(this.enableDD)
this._updateOrder();}},onRender:function(container,position){if(!this.el){this.el=document.createElement('div');}
LayerTree.superclass.onRender.apply(this,arguments);}});Ext.reg('layertree',LayerTree);LayerTree.getNodeLayers=function(layerTree,node){var olLayers=[];node.cascade(function(subNode){var curLayers=layerTree.nodeIdToLayers[subNode.id];if(curLayers){olLayers=olLayers.concat(curLayers);}});return olLayers;};LayerTree.removeNode=function(layerTree,node){node.cascade(function(subNode){if(subNode.attributes&&subNode.attributes.layerNames){var layerNames=subNode.attributes.layerNames;for(var i=0;i<layerNames.length;++i){var layerName=layerNames[i].split(layerTree.separator);var olLayer=layerTree.layerNameToLayer[layerName[0]];var wmsLayer=layerName[1];var layerList;if(olLayer.params.LAYERS){layerList=olLayer.params.LAYERS=Util.fixArray(olLayer.params.LAYERS);}else{layerList=olLayer.params.layers=Util.fixArray(olLayer.params.layers);}
if(wmsLayer&&layerList){layerList.remove(wmsLayer);}
if(!wmsLayer||!layerList||layerList.length==0){olLayer.destroy();}else{olLayer.redraw();}}}});node.remove();layerTree._updateCachedObjects();};LayerTree.MenuFeatures={opacitySlide:function(layerTree,node,olLayers){if(olLayers.length==0)return null;return{iconCls:'opacityLayer',text:Locale.getText("txt_opacidad"),menu:{plain:true,items:[LayerTree.MenuFeatures.opacitySlideDirect(layerTree,node,olLayers)]}};},opacitySlideDirect:function(layerTree,node,olLayers){if(olLayers.length==0)return null;var value=0;for(var i=0;i<olLayers.length;++i){value+=olLayers[i].opacity==null?1.0:olLayers[i].opacity;}
value=value/olLayers.length;return new Ext.menu.Adapter(new Ext.Slider({width:100,value:value*100,listeners:{change:function(slider,value){for(var j=0;j<olLayers.length;++j){olLayers[j].setOpacity(value/100.0);}}}}));},remove:function(layerTree,node,olLayers){for(var i=0;i<olLayers.length;++i){var layer=olLayers[i];if(layer.isBaseLayer&&layer.getVisibility()){return null;}}
return{iconCls:'removeLayer',text:Locale.getText("txt_eliminar"),handler:function(){LayerTree.removeNode(layerTree,node);}};},zoomToExtent:function(layerTree,node,olLayers){if(olLayers.length==0)return null;var bbox=null;for(var i=0;i<olLayers.length;++i){var layer=olLayers[i];if(bbox){bbox.extend(layer.maxExtent);}else{bbox=layer.maxExtent.clone();}}
return{iconCls:'zoomToExtent',text:Locale.getText('txt_zoom'),handler:function(){bbox.transform(olLayers[0].projection,new OpenLayers.Projection(layerTree.map.getProjection()));layerTree.map.zoomToExtent(bbox);}};},sldStyle:function(layerTree,node,olLayers){return{iconCls:'sldStyle',text:OpenLayers.Lang.translate('SLD'),scope:this,handler:function(){Ext.MessageBox.prompt('SLD URL','URL:',this.showSLDURL);}};showSLDURL=function(btn,text){if(btn=='ok'){alert(text);}};},createGroup:function(layerTree,node,olLayers){return{iconCls:'groupNode',text:Locale.getText("txt_grupo"),qtip:Locale.getText("txt_nuevo_grupo"),scope:this,handler:function(){IDEOL.toc.createGroup(Locale.getText("txt_grupo"),false);IDEOL.toc.updateTree();}};},editNode:function(layerTree,node,olLayers){return{text:Locale.getText("txt_renombrar"),qtip:Locale.getText("txt_renombrar"),scope:this,handler:function(){if(node.attributes.iconCls!='legendNode'){IDEOL.toc.treeEditor.editNode=node;IDEOL.toc.treeEditor.startEdit(node.getUI().getTextEl());}}};}};LayerTree.createContextualMenuPlugin=function(options){return{init:function(layerTree){function openMenu(node,e){var olLayers=LayerTree.getNodeLayers(layerTree,node);var items=[];for(var j=0;j<options.length;++j){var constructor=LayerTree.MenuFeatures[options[j]];var menuItem=constructor(layerTree,node,olLayers);if(menuItem){items.push(menuItem);}}
if(items.length>0){var menu=new Ext.menu.Menu({ignoreParentClick:true,defaults:{scope:layerTree},items:items});menu.showAt(e.getXY());menu.on('hide',function(){menu.destroy();});}}
if(Ext.isOpera){layerTree.on('click',function(node,e){if(e.hasModifier()){e.stopEvent();openMenu(node,e);}});}else{layerTree.on('contextMenu',function(node,e){e.stopEvent();openMenu(node,e);});}}};};function Toc(){this.div;this.map;this.tree;this.treeEditor;this.selectedNode;this.mask;this.initialize=function(divID,mapOL,rootTitle){this.div=divID;this.map=mapOL;if(this.tree!=null){this.selectedNode=null;this.destroyTree();}
this.tree=new LayerTree({title:Locale.getText("txt_capas"),titleCollapse:true,collapsible:true,collapsed:false,border:false,autoScroll:true,height:350,iconCls:'treeLayerPanel',map:this.map,el:this.div,bodyStyle:'padding:5px 0 5px 0',enableDD:true,rootVisible:false,ascending:false,plugins:[LayerTree.createContextualMenuPlugin(['opacitySlide','zoomToExtent','remove','createGroup','editNode'])]});this.tree.on('click',function(node,event){if(this.selectedNode!=node){this.selectedNode=node;}},this);this.tree.on('expand',function(tree){this.lastSize=tree.lastSize;tree.body.setHeight(tree.adjustBodyHeight(this.lastSize.height-tree.getFrameHeight()));},this);this.tree.on('resize',function(tree){if(this.lastSize!=null)
tree.body.setHeight(tree.adjustBodyHeight(this.lastSize.height-tree.getFrameHeight()));},this);this.treeEditor=new Ext.tree.TreeEditor(this.tree,{cancelOnEsc:true,completeOnEnter:true,ignoreNoChange:true});this.treeEditor.on('beforestartedit',function(editor,boundEl,value){if(editor.editNode.attributes.iconCls=='legendNode')
return false;return true;},this);this.treeEditor.on('beforecomplete',function(editor,newValue,originalValue){if(newValue!=originalValue){if(editor.editNode.attributes.iconCls!='groupNode'&&editor.editNode.attributes.iconCls!='legendNode'){var layer=this.getLayerMap(newValue);if(!layer){var layer=this.getLayerMap(originalValue);layer.name=newValue;editor.editNode.attributes.layerNames=[newValue];this.tree._updateCachedObjects();return true;}
else{editor.cancelEdit();UtilsUI.showMessageWindow("Información","La capa "+layer.name+" ya existe en el mapa.",Ext.MessageBox.ERROR);return false;}}}
return true;},this);this.reloadTree(rootTitle);};this.destroyTree=function(){if(this.tree.rendered){this.tree.body.removeAllListeners();Ext.dd.ScrollManager.unregister(this.tree.body);if(this.tree.dropZone){this.tree.dropZone.unreg();}
if(this.tree.dragZone){this.tree.dragZone.unreg();}}
this.tree.root.destroy();this.tree.nodeHash=null;};this.reloadTree=function(rootTitle){this.deleteAllNodes();this.tree.getRootNode().setText(rootTitle);this.createBaseLayer();this.createLayers();this.updateTree();},this.updateTree=function(){this.tree._extractOLModel();this.tree._fixupModel();this.tree._handleModelChange(null,null);this.tree._updateOrder();this.tree.render();};this.addLayer=function(layer){if(!this.isLayerMap(layer)){layer.events.register('visibilitychanged',null,function(){if(this.visibility)
Layout.statusBar.showBusy("Obteniendo la capa "+this.name+" ...");});layer.events.register('loadend',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});layer.events.register('loadcancel',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});this.map.addLayer(layer);var layerNode=this.createLayerNode(layer);var rootNode=this.tree.getRootNode();var index=this.tree.baseLayerNames.length;rootNode.insertBefore(layerNode,rootNode.item(index));this.updateTree();}
else{UtilsUI.showMessageWindow("Información","La capa "+layer.name+" ya existe en el mapa.",Ext.MessageBox.ERROR);}};this.isLayerMap=function(layer){var layers=this.map.getLayersByName(layer.name)
if(layers.length>0)
return true;return false;};this.getLayerMap=function(layerName){var arrayLayers=this.map.getLayersByName(layerName);if(arrayLayers.length==1)
return arrayLayers[0];return null;};this.deleteAllNodes=function(){var node=this.tree.getRootNode();while(node.firstChild){node.removeChild(node.firstChild);}};this.getTree=function(){return this.tree;};this.createBaseLayer=function(){var layers=this.map.layers;var rootnode=this.tree.getRootNode();for(var i=0;i<layers.length;i++){if(layers[i].isBaseLayer){this.tree.baseLayerNames.push(layers[i].name);var layerNode=new Ext.tree.TreeNode({text:layers[i].name,radio:true,layerNames:[layers[i].name],expanded:false,draggable:false,isTarget:false,checked:layers[i].getVisibility(),iconCls:'baseNode',qtip:layers[i].name});rootnode.appendChild(layerNode);}}};this.createGroup=function(group,append){var rootnode=this.tree.getRootNode();var node={text:group,expanded:true,checked:false,iconCls:'groupNode',draggable:true,allowDrop:true,qtip:group};var nodeGroup=new Ext.tree.TreeNode(node);nodeGroup.on('beforeappend',function(tree,node,childNode,refNode){var iconCls=childNode.attributes.iconCls;if(iconCls=='groupNode')
return false;},this);nodeGroup.on('beforeinsert',function(tree,node,childNode,refNode){var iconCls=childNode.attributes.iconCls;if(iconCls=='groupNode')
return false;},this);nodeGroup.on('textchange',function(node,text,oldText){var childNodes=node.childNodes;for(var i=0;i<childNodes.length;i++){var layerName=childNodes[i].attributes.text;var layer=this.getLayerMap(layerName);layer.groupDisplayLayerSwitcher=node.attributes.text;}},this);if(append)
rootnode.appendChild(nodeGroup);else{var index=this.tree.baseLayerNames.length;rootnode.insertBefore(nodeGroup,rootnode.item(index));}};this.createLayers=function(){var layers=this.map.layers;var rootnode=this.tree.getRootNode();for(var i=layers.length-1;i>=0;i--){var layer=layers[i];if(!layer.isBaseLayer&&layer.displayInLayerSwitcher){var layerNode=this.createLayerNode(layer);layerNode.on('move',function(tree,node,oldParent,newParent,index){var layerName=node.attributes.text;var layer=this.getLayerMap(layerName);if(newParent.attributes.iconCls=='groupNode'){layer.groupDisplayLayerSwitcher=newParent.attributes.text;}
else{layer.groupDisplayLayerSwitcher='';}},this);if(layer.groupDisplayLayerSwitcher){var group=rootnode.findChild('text',layer.groupDisplayLayerSwitcher);if(group){group.appendChild(layerNode);}
else{this.createGroup(layer.groupDisplayLayerSwitcher,true);group=rootnode.findChild('text',layer.groupDisplayLayerSwitcher);group.appendChild(layerNode);}}
else{rootnode.appendChild(layerNode);}}}};this.createLayerNode=function(layer){var layerNode;if(layer.name){var styleUrl=this.getFirstLayerStyleUrl(layer);if(styleUrl){legendNode=new Ext.tree.TreeNode({draggable:false,allowChildren:false,iconCls:'legendNode',leaf:true,icon:styleUrl});}
else{legendNode=new Ext.tree.TreeNode({draggable:false,allowChildren:false,iconCls:'legendNode',leaf:true,icon:Util.getIconUrl(layer.url,{layer:layer.params.LAYERS})});}
var inconClsLayer='layerNode';var qtipText=layer.name;if(layer.queryable){inconClsLayer='layerNodeInfo';qtipText=layer.name+" ("+Locale.getText("txt_consultable")+")";}
layerNode=new Ext.tree.TreeNode({text:layer.name,layerNames:[layer.name],expanded:false,checked:layer.getVisibility(),allowDrop:false,iconCls:inconClsLayer,qtip:qtipText});layerNode.appendChild(legendNode);}
return layerNode;};this.getFirstLayerStyleUrl=function(layer){var url=null;if(layer.styles){if(layer.styles.length>0){if(layer.styles[0].legend){if(layer.styles[0].legend.href){url=layer.styles[0].legend.href;}}}}
return url;};};Ext.form.FileUploadField=Ext.extend(Ext.form.TextField,{buttonText:'Browse...',buttonOnly:false,buttonOffset:3,readOnly:true,autoSize:Ext.emptyFn,initComponent:function(){Ext.form.FileUploadField.superclass.initComponent.call(this);this.addEvents('fileselected');},onRender:function(ct,position){Ext.form.FileUploadField.superclass.onRender.call(this,ct,position);this.wrap=this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});this.el.addClass('x-form-file-text');this.el.dom.removeAttribute('name');this.fileInput=this.wrap.createChild({id:this.getFileInputId(),name:this.name||this.getId(),cls:'x-form-file',tag:'input',type:'file',size:1});var btnCfg=Ext.applyIf(this.buttonCfg||{},{text:this.buttonText});this.button=new Ext.Button(Ext.apply(btnCfg,{renderTo:this.wrap,cls:'x-form-file-btn'+(btnCfg.iconCls?' x-btn-icon':'')}));if(this.buttonOnly){this.el.hide();this.wrap.setWidth(this.button.getEl().getWidth());}
this.fileInput.on('change',function(){var v=this.fileInput.dom.value;this.setValue(v);this.fireEvent('fileselected',this,v);},this);},getFileInputId:function(){return this.id+'-file';},onResize:function(w,h){Ext.form.FileUploadField.superclass.onResize.call(this,w,h);this.wrap.setWidth(w);if(!this.buttonOnly){var w=this.wrap.getWidth()-this.button.getEl().getWidth()-this.buttonOffset;this.el.setWidth(w);}},preFocus:Ext.emptyFn,getResizeEl:function(){return this.wrap;},getPositionEl:function(){return this.wrap;},alignErrorIcon:function(){this.errorIcon.alignTo(this.wrap,'tl-tr',[2,0]);}});Ext.reg('fileuploadfield',Ext.form.FileUploadField);XSLMgr={transformXML:function(xmlDocument,xslString){var xmlString=new XMLSerializer().serializeToString(xmlDocument);var xml=xmlParse(xmlString);var xslt=xmlParse(xslString);var html=xsltProcess(xml,xslt);return html;},transformString:function(xmlString,xslString){var xml=xmlParse(xmlString);var xslt=xmlParse(xslString);var html=xsltProcess(xml,xslt);return html;}};MapMgr=OpenLayers.Class({map:null,initialize:function(){},setMap:function(mapOL){this.map=mapOL;},refreshMap:function(){this.map.updateSize();},CLASS_NAME:"MapMgr"});ExportMgr={format:new OpenLayers.Format.WMC(),getWMCString:function(map){var WMCString=this.format.write(map);return WMCString;}}
LayersMgr=OpenLayers.Class({styles:null,map:null,marker:null,defaultVector:null,defaultMarker:null,initializeLayers:function(){this.defaultVector=new OpenLayers.Layer.Vector("Default",{displayInLayerSwitcher:false});this.defaultMarker=new OpenLayers.Layer.Markers("Markers",{displayInLayerSwitcher:false});},initialize:function(map,styles){this.map=map;this.styles=styles;this.initializeLayers();this.loadMarkerLayers();this.loadVectorLayers();if(Config.WFSLAYERS)
this.loadWFSLayers();},loadMarkerLayers:function(){this.map.addLayer(this.defaultMarker);},loadVectorLayers:function(){this.defaultVector.styleMap=this.styles.vectorStyleMap;this.map.addLayer(this.defaultVector);},loadWFSLayers:function(){var layers=WFSLayers.layers;for(key in layers){if(layers[key].isVector){layers[key].styleMap=this.styles.vectorStyleMap;}
this.map.addLayer(layers[key]);}},moveLayerToTop:function(layer){var index=Math.max(this.map.Z_INDEX_BASE['Feature']-1,layer.getZIndex())+1;layer.setZIndex(index);},cleanLayers:function(){this.defaultVector.destroyFeatures();this.defaultMarker.clearMarkers();},drawMarker:function(lonlat,srs,clean,zoom){var size=new OpenLayers.Size(20,34);var offset=new OpenLayers.Pixel(-(size.w/2),-size.h);var icon=new OpenLayers.Icon('ide/images/yellowMarker.png',size,offset);lonlat.transform(new OpenLayers.Projection(srs),this.map.getProjectionObject());var mapMaxExtent=this.map.getMaxExtent();if(mapMaxExtent.containsLonLat(lonlat)){var marker=new OpenLayers.Marker(lonlat,icon);if(clean){this.defaultMarker.clearMarkers();}
if(marker){this.moveLayerToTop(this.defaultMarker);this.defaultMarker.addMarker(marker);}
if(zoom){var maxZoom=this.map.getNumZoomLevels();var zoom=(75*maxZoom)/100;this.map.setCenter(lonlat,zoom);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_lonlat_elemento_fuera_maxextent"),Ext.MessageBox.ERROR);}},drawObjects:function(objects,srs,clean,zoom){if(clean){this.defaultVector.destroyFeatures();}
this.moveLayerToTop(this.defaultVector);var src=new OpenLayers.Projection(srs);var dest=new OpenLayers.Projection(this.map.getProjection());var features=[];for(var i=0;i<objects.length;i++){if(objects[i]instanceof OpenLayers.Geometry.Point||objects[i]instanceof OpenLayers.Geometry.Polygon||objects[i]instanceof OpenLayers.Geometry.LineString||objects[i]instanceof OpenLayers.Geometry.MultiPoint||objects[i]instanceof OpenLayers.Geometry.MultiPolygon||objects[i]instanceof OpenLayers.Geometry.MultiLineString){objects[i].transform(src,dest);var feature=new OpenLayers.Feature.Vector(objects[i]);features.push(feature);}
else if(objects[i]instanceof OpenLayers.Feature.Vector){objects[i].geometry.transform(src,dest);features.push(objects[i])}
this.defaultVector.drawFeature(objects[i]);}
this.defaultVector.addFeatures(features);if(zoom){var bounds=this.defaultVector.getDataExtent();this.map.zoomToExtent(bounds,false);}},CLASS_NAME:"LayersMgr"});ControlsMgr=OpenLayers.Class({map:null,styles:null,controls:{zoomIn:null,zoomOut:null,pan:null,zoomFull:null,nav:null,infoLinks:null,infoImages:null,infoWMS:null,measureDistance:null,measureArea:null,mousePositionControl:null,scaleControl:null,streetView:null,incidencias:null,overViewMap:null},initialize:function(mapOL,stylesOL){this.map=mapOL;this.styles=stylesOL;this.controls.zoomIn=new OpenLayers.Control.ZoomBox();this.controls.zoomOut=new OpenLayers.Control.ZoomBox({out:true,cursorClass:'olControlZoomOutBoxCursor',handlerOptions:{cursorClasses:{'startBox':'crossHair','endBox':'olControlZoomOutBoxCursor'}}});this.controls.pan=new OpenLayers.Control.DragPan({isDefault:true});this.controls.zoomFull=new OpenLayers.Control.ZoomToMaxExtent();this.controls.nav=new OpenLayers.Control.NavigationHistory();this.controls.infoLinks=new InfoLinksControl(this.map);this.controls.infoWMS=new InfoWMSControl(this.map);this.controls.infoImages=new InfoImagesControl(this.map);this.controls.measureDistance=new OpenLayers.Control.Measure(OpenLayers.Handler.Path,{handlerOptions:{style:"default",layerOptions:{styleMap:this.styles.measureStyleMap}}});this.controls.measureArea=new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon,{handlerOptions:{style:"default",layerOptions:{styleMap:this.styles.measureStyleMap}}});this.controls.measureDistance.events.on({"measure":this.handleMeasurements,"measurepartial":this.handleMeasurements});this.controls.measureArea.events.on({"measure":this.handleMeasurements,"measurepartial":this.handleMeasurements});this.controls.mousePositionControl=new OpenLayers.Control.MousePosition({element:$('mousePositionInfo')});this.controls.mousePositionControl.suffix='&nbsp;&nbsp;<b>'+this.map.displayProjection.projCode+' </b>';this.controls.scaleControl=new OpenLayers.Control.Scale("scalePanel");this.controls.streetView=new StreetViewControl(this.map);this.controls.incidencias=new IncidenciasControl(this.map);var ovMapLayers=[];for(var i=0;i<this.map.layers.length;i++){var layer=this.map.layers[i].clone();ovMapLayers.push(layer);}
var ovMapOptions=null;if(this.map.projection!="EPSG:900913"){this.controls.overViewMap=new OpenLayers.Control.OverviewMap({div:$('overViewMapPanel'),size:new OpenLayers.Size(235,180)});this.controls.overViewMap.layers=ovMapLayers;}
else{this.controls.overViewMap=null;}
for(key in this.controls){if(this.controls[key]!=null)
this.map.addControl(this.controls[key]);}},handleMeasurements:function(event){var geometry=event.geometry;var units=event.units;var order=event.order;var measure=event.measure;var element=document.getElementById('measureInfo');var out="";if(order==1){out+="<b>"+Locale.getText("txt_longitud")+"</b>: "+measure.toFixed(3)+" "+units;}else{out+="<b>"+Locale.getText("txt_area")+"</b>: "+measure.toFixed(3)+" "+units+"2";}
element.visibility='visible';element.innerHTML=out;},cleanMeasurements:function(){var element=document.getElementById('measureInfo');element.innerHTML='';},activateControl:function(control){this.cleanMeasurements();this.deactivateControls();control.activate();},deactivateControls:function(){var controls=this.map.controls;for(var i=0;i<controls.length;i++){if(controls[i]instanceof OpenLayers.Control.NavigationHistory==false){controls[i].deactivate();}}},CLASS_NAME:"ControlsMgr"});EditionMgr=OpenLayers.Class({map:null,layer:null,LAYER_PROJECTION:null,styleMap:null,controls:{editControl:null,drawFreeHand:null,drawPoint:null,drawLine:null,drawPolygon:null,drawRegularPolygon:null,deleteFeatures:null,infoWFSBBox:null},editModes:{DEFAULT:0,RESIZE:1,ROTATE:2,DRAG:3},initialize:function(map,layer,styleMap){this.map=map;this.layer=layer;this.LAYER_PROJECTION=this.layer.projection.projCode;OpenLayers.Util.extend(this.layer,{scope:this,commitSuccess:this.onCommitSuccess,commitFailure:this.onCommitFailure})
this.styleMap=styleMap;this.initializeControls(this.layer);},initializeControls:function(layer){this.destroyControls();this.controls.editControl=new OpenLayers.Control.ModifyFeature(layer,{onModification:this.afterFeatureModified,clickout:true,toogle:true}),this.controls.drawFreeHand=new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Path,{scope:this,featureAdded:this.onFeatureAdded,handlerOptions:{freehand:true,style:"default",layerOptions:{styleMap:this.styleMap}}});this.controls.drawPoint=new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Point,{scope:this,featureAdded:this.onFeatureAdded,handlerOptions:{style:"default",layerOptions:{styleMap:this.styleMap}}});this.controls.drawLine=new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Path,{scope:this,featureAdded:this.onFeatureAdded,handlerOptions:{style:"default",layerOptions:{styleMap:this.styleMap}}});this.controls.drawPolygon=new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Polygon,{scope:this,featureAdded:this.onFeatureAdded,handlerOptions:{style:"default",layerOptions:{styleMap:this.styleMap}}});this.controls.drawRegularPolygon=new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.RegularPolygon,{scope:this,featureAdded:this.onFeatureAdded,handlerOptions:{sides:6,style:"default",layerOptions:{styleMap:this.styleMap}}});this.controls.deleteFeatures=new OpenLayers.Control.SelectFeature(layer,{scope:this,multiple:true,clickout:true,toogle:true,hover:false,box:false,onSelect:this.onDeleteFeatureSelect,onUnselect:this.onDeleteFeatureUnselect});this.controls.infoWFSBBox=new InfoWFSBBoxControl(layer);for(key in this.controls)
this.map.addControl(this.controls[key]);},onFeatureAdded:function(feature){feature.state=OpenLayers.State.INSERT;this.layer.drawFeature(feature,"insert");},afterFeatureModified:function(feature){if(feature.state!=OpenLayers.State.INSERT){feature.state=OpenLayers.State.UPDATE;this.layer.drawFeature(feature,"update");}},onDeleteFeatureSelect:function(feature){this.unselect(feature);if(this.layer instanceof OpenLayers.Layer.Vector){this.layer.destroyFeatures(feature);}
else if(this.layer instanceof OpenLayers.Layer.WFS){if(feature.state==OpenLayers.State.INSERT){this.layer.destroyFeatures(feature);}
else{feature.state=OpenLayers.State.DELETE;this.layer.drawFeature(feature,"delete");}}},onDeleteFeatureUnselect:function(feature){this.layer.drawFeature(feature,"default");},deleteFeatures:function(features){if(features.length>0){for(var i=0;i<features.length;i++){var layer=features[i].layer;if(layer instanceof OpenLayers.Layer.Vector){layer.destroyFeatures(features[i]);}
else if(this.layer instanceof OpenLayers.Layer.WFS){if(features[i].state==OpenLayers.State.INSERT){layer.destroyFeatures(features[i]);}
else{features[i].state=OpenLayers.State.DELETE;layer.drawFeature(features[i],"delete");}}}
this.saveFeatures();}},moveLayerToTop:function(){var index=Math.max(this.map.Z_INDEX_BASE['Feature']-1,this.layer.getZIndex())+1;this.layer.setZIndex(index);},checkDeleteFeatures:function(){var confirm;if(deleteFeatures.length>0){Ext.MessageBox.confirm(Locale.getText("txt_confirmacion"),Locale.getText("msg_eliminar_geometrias_seleccionadas?"),function(button){if(button=="yes")
confirm=true;else
confirm=false;});}
if(!confirm){for(var i=0;i<deleteFeatures.length;i++){deleteFeatures[i].state=null;this.layer.drawFeature(feature,"default");}
this.deleteFeatures=[];}},checkChanges:function(){var features=this.layer.features;for(i=0;i<features.length;i++){if(features[i].state!=null)
return true;}
return false;},getControl:function(control){alert("test remove");for(key in this.controls){if(key==control){return this.controls[key]}}},getControls:function(){return this.controls;},activateControl:function(control){this.unselectAll();this.deactivateControls();this.moveLayerToTop();control.activate();},deactivateControls:function(){var controls=this.map.controls;for(var i=0;i<controls.length;i++){if(controls[i]instanceof OpenLayers.Control.NavigationHistory==false){controls[i].deactivate();}}},destroyControls:function(){for(key in this.controls){if(this.controls[key]!=null){if(this.controls[key].layer){this.controls[key].destroy();this.controls[key]=null;}}}},unselectAll:function(){if(this.layer.selectedFeatures!=null){this.controls.deleteFeatures.unselectAll();this.controls.editControl.selectControl.unselectAll();}},selectFeatureByFid:function(fid){this.unselectAll();var feature=this.getFeatureByFid(fid);},saveFeatures:function(){if(this.layer instanceof OpenLayers.Layer.WFS){if(this.checkChanges()){this.unselectAll();this.commitLayer();this.revertFeatures();}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_cambios_capa_trabajo"),Ext.MessageBox.WARNING);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_trabajo"),Ext.MessageBox.WARNING);}},saveDataFeatures:function(features){for(var i=0;i<features.length;i++){this.updateFeatureData(features[i]);}
this.saveFeatures();},updateFeatureData:function(updateFeature){if(updateFeature.fid!=null){var feature=this.getFeatureByFid(updateFeature.fid);if(feature!=null){feature.attributes=null;feature.data=null;feature.attributes=new Object();feature.data=new Object();for(key in updateFeature.data){if(key!='the_geom'){feature.attributes[key]=updateFeature.data[key];feature.data[key]=updateFeature.data[key];}}
if(feature.state!=OpenLayers.State.INSERT)
feature.state=OpenLayers.State.UPDATE;}}},getFeatureByFid:function(fid){var features=this.layer.features;for(i=0;i<features.length;i++){if(features[i].fid==fid)
return features[i];}},resetFeaturesState:function(){var features=this.layer.features;for(key in features)
features[key].state=null;},revertFeatures:function(){if(this.layer instanceof OpenLayers.Layer.WFS){if(this.checkChanges()){this.refreshLayer();}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_cambios_capa_trabajo"),Ext.MessageBox.WARNING);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capa_trabajo"),Ext.MessageBox.WARNING);}},setLayerByName:function(layerName){var arrayLayers=this.map.getLayersByName(layerName);var layer=null;if(arrayLayers.length==1)
layer=arrayLayers[0];if(layer!=null){if(layer instanceof OpenLayers.Layer.WFS)
OpenLayers.Util.extend(layer,{scope:this,commitSuccess:this.onCommitSuccess,commitFailure:this.onCommitFailure})
if(this.layer!=null)
this.layer.setVisibility(false);this.layer=layer;this.moveLayerToTop();this.layer.setVisibility(true);this.initializeControls(layer);}},cleanLayer:function(){this.unselectAll();if(this.layer instanceof OpenLayers.Layer.Vector){this.layer.destroyFeatures(this.layer.features);}
else if(this.layer instanceof OpenLayers.Layer.WFS){this.refreshLayer();}},refreshLayer:function(){this.unselectAll();this.layer.setVisibility(false);this.layer.redraw();this.layer.setVisibility(true);},refreshWMSLayers:function(){for(i=0;i<this.map.layers.length;i++){var layer=this.map.layers[i];if(layer instanceof OpenLayers.Layer.WMS&&layer.getVisibility()&&!layer.isBaseLayer)
layer.redraw();}},commitLayer:function(){if(this.layer instanceof OpenLayers.Layer.WFS)
this.layer.commit();},onCommitSuccess:function(response){if(response.responseText.indexOf('ServiceException')>=0){this.scope.revertFeatures();UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_realizar_transaccion"),Ext.MessageBox.INFO);}
else{this.scope.refreshWMSLayers();this.scope.layer.redraw();UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_transaccion_ok"),Ext.MessageBox.INFO);}},onCommitFailure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_realizar_transaccion"),Ext.MessageBox.INFO);},startEditionMode:function(editionMode){var modifyFeature=OpenLayers.Control.ModifyFeature;this.controls.editControl.mode=modifyFeature.RESHAPE;switch(editionMode){case 0:break;case 1:this.controls.editControl.mode|=modifyFeature.RESIZE;break;case 2:this.controls.editControl.mode|=modifyFeature.ROTATE;break;case 3:this.controls.editControl.mode|=modifyFeature.DRAG;break;}
if(editionMode==1||editionMode==2||editionMode==3)
this.controls.editControl.mode&=~modifyFeature.RESHAPE;this.activateControl(this.controls.editControl);},CLASS_NAME:"EditionMgr"});WMSMgr={getCapabilities:function(url){var xml=new OpenLayers.Format.XML();var wms=new OpenLayers.Format.WMS({'layerOptions':{buffer:0}});var doc=null;var request=OpenLayers.Request.GET({url:url,scope:this,params:{service:"WMS",request:"GetCapabilities"},async:false});if(request.responseXML==null)
return false;if(request.responseText.indexOf('ServiceException')>=0)
return false;if(!request.responseXML.documentElement){doc=xml.read(request.responseText);}
else{doc=request.responseXML;}
var capabilites=wms.read(doc,{});return capabilites;},getBoundingBox:function(layerInfo,srs){var bbox=layerInfo.bbox;for(var i=0;i<bbox.length;i++){if(bbox[i].srs==srs)
return bbox[i].bounds;}
return null;},isSupportedSRS:function(layer,srs){var url=layer.url;return true;},isValidSRS:function(layerInfo,srs){var bbox=layerInfo.bbox;if(bbox!=null){for(var i=0;i<bbox.length;i++){if(bbox[i].srs==srs)
return true;}}
var srsArray=layerInfo.srs;if(srsArray!=null){for(var i=0;i<srsArray.length;i++){if(srsArray[i]==srs)
return true;}}
return false;},getFeatures:function(layer,xy){Layout.statusBar.showBusy(Locale.getText("msg_obteniendo_informacion_capa")+" "+layer.name+" ...");var features=null;try{var url=layer.getFullRequestString({REQUEST:"GetFeatureInfo",EXCEPTIONS:"application/vnd.ogc.se_xml",BBOX:layer.map.getExtent().toBBOX(),X:xy.x,Y:xy.y,BUFFER:20,INFO_FORMAT:'application/vnd.ogc.gml',QUERY_LAYERS:layer.params.LAYERS,FEATURE_COUNT:50,SRS:layer.map.projection,WIDTH:layer.map.size.w,HEIGHT:layer.map.size.h});var request=OpenLayers.Request.GET({url:url,failure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_contactar_servicio"),Ext.MessageBox.ERROR);},scope:this,async:false});if(request.responseText){var format=new OpenLayers.Format.WMSGetFeatureInfo();var text=Util.decode(request.responseText);var text=Util.encode(text);features=format.read(text);}
Layout.statusBar.clearStatus({useDefaults:true});}
catch(e){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_obtener_info_servidor"),Ext.MessageBox.ERROR);Layout.statusBar.clearStatus({useDefaults:true});}
return features;},getFeaturesString:function(layer,xy){Layout.statusBar.showBusy(Locale.getText("msg_obteniendo_informacion_capa")+" "+layer.name+" ...");try{var url=layer.getFullRequestString({REQUEST:"GetFeatureInfo",EXCEPTIONS:"application/vnd.ogc.se_xml",BBOX:layer.map.getExtent().toBBOX(),X:xy.x,Y:xy.y,BUFFER:20,INFO_FORMAT:'application/vnd.ogc.gml',QUERY_LAYERS:layer.params.LAYERS,FEATURE_COUNT:50,SRS:layer.map.projection,WIDTH:layer.map.size.w,HEIGHT:layer.map.size.h});var request=OpenLayers.Request.GET({url:url,failure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_contactar_servicio"),Ext.MessageBox.ERROR);},scope:this,async:false});if(request.responseText!=null){return request.responseText;}
Layout.statusBar.clearStatus({useDefaults:true});}
catch(e){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_obtener_info_servidor"),Ext.MessageBox.ERROR);Layout.statusBar.clearStatus({useDefaults:true});}
return null;}};WMCMgr={format:new OpenLayers.Format.WMC({version:"1_1_0g"}),initialize:function(){},mapOptions:{units:"m",numZoomLevels:15,maxResolution:'auto',controls:[new OpenLayers.Control.KeyboardDefaults(),new OpenLayers.Control.MouseDefaults({'performedDrag':false}),new OpenLayers.Control.ScaleLine()]},sphericalMercatorOptions:{projection:new OpenLayers.Projection("EPSG:900913"),displayProjection:new OpenLayers.Projection("EPSG:900913"),units:"m",numZoomLevels:18,maxResolution:156543.0339,controls:[new OpenLayers.Control.KeyboardDefaults(),new OpenLayers.Control.MouseDefaults({'performedDrag':false}),new OpenLayers.Control.ScaleLine()]},getWMCString:function(contextURL){var wmcText;var request=OpenLayers.Request.GET({url:contextURL,success:function(transport){wmcText=transport.responseText;},failure:function(transport){wmcText=null;},async:false});return wmcText;},contextToMap:function(oldMap,contextURL,divID){var map;var context=this.isValidWMC(contextURL);if(context!=null&&divID!=null){if(oldMap!=null){oldMap.destroy();}
map=new OpenLayers.Map(divID,this.mapOptions);map.contextURL=contextURL;map.maxExtent=context.maxExtent;map.projection=new OpenLayers.Projection(context.projection);map.displayProjection=new OpenLayers.Projection(context.projection);map.addControl(new OpenLayers.Control.PanZoomBar({zoomWorldIcon:true}));if(map.projection=='EPSG:900913'){this.loadSphericalMercatorLayers(map);map.displayProjection=new OpenLayers.Projection("EPSG:4326");map.numZoomLevels=20;map.maxResolution=156543.0339;}
for(var i=0;i<context.layers.length;i++){var layer=context.layers[i];layer.events.register('visibilitychanged',null,function(){if(this.visibility)
Layout.statusBar.showBusy(Locale.getText("msg_obteniendo_capa")+" "+this.name+" ...");});layer.events.register('loadend',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});layer.events.register('loadcancel',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});}
var bounds=context.bounds;map.addLayers(context.layers);map.setCenter(bounds.getCenterLonLat(),map.getZoomForExtent(bounds,true));}
return map;},reprojectedContextToMap:function(oldMap,contextURL,divID,projCode){var map;var context=this.isValidWMC(contextURL);if(context!=null&&divID!=null){if(this.isValidReprojection(context,projCode)){var oldBoundsMap=null;var oldProjectionMap=null;if(oldMap!=null){if(oldMap.getExtent()!=null){oldBoundsMap=oldMap.getExtent().clone();}
oldProjectionMap=new String(oldMap.getProjection());oldMap.destroy();}
map=new OpenLayers.Map(divID,this.mapOptions);map.contextURL=contextURL;map.maxExtent=context.maxExtent;map.maxExtent.transform(new OpenLayers.Projection(context.projection),new OpenLayers.Projection(projCode));map.projection=new OpenLayers.Projection(projCode);map.displayProjection=new OpenLayers.Projection(projCode);map.addControl(new OpenLayers.Control.PanZoomBar({zoomWorldIcon:true}));if(map.projection=='EPSG:900913'){this.loadSphericalMercatorLayers(map);map.displayProjection=new OpenLayers.Projection("EPSG:4326");map.numZoomLevels=20;map.maxResolution=156543.0339;}
for(var i=0;i<context.layers.length;i++){var layer=context.layers[i];layer.maxExtent.transform(new OpenLayers.Projection(context.projection),new OpenLayers.Projection(projCode));layer.events.register('visibilitychanged',null,function(){if(this.visibility)
Layout.statusBar.showBusy(Locale.getText("msg_obteniendo_capa")+" "+this.name+" ...");});layer.events.register('loadend',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});layer.events.register('loadcancel',null,function(){Layout.statusBar.clearStatus({useDefaults:true});});}
var bounds=context.bounds;map.addLayers(context.layers);bounds.transform(new OpenLayers.Projection(context.projection),new OpenLayers.Projection(projCode));if(oldBoundsMap!=null){oldBoundsMap.transform(new OpenLayers.Projection(oldProjectionMap),new OpenLayers.Projection(projCode));map.setCenter(oldBoundsMap.getCenterLonLat(),map.getZoomForExtent(oldBoundsMap,true));}
else{map.setCenter(bounds.getCenterLonLat(),map.getZoomForExtent(bounds,true));}}}
return map;},createWMCMap:function(oldMap,contextURL,divID,projCode){var map;if(projCode==null){map=this.contextToMap(oldMap,contextURL,divID);}
else{map=this.reprojectedContextToMap(oldMap,contextURL,divID,projCode);}
return map;},isValidReprojection:function(context,projCode){var baseLayers=this.getBaseLayers(context);var baseLayer=baseLayers[0];var valid=WMSMgr.isSupportedSRS(baseLayer,projCode);return valid;},isValidWMC:function(contextURL){if(contextURL!=null){var wmcText=this.getWMCString(contextURL);if(wmcText!=null){var context=this.format.read(wmcText,{});if(context.version!=null&&context.projection!=null&&context.maxExtent!=null){return context;}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_error_obtener_contexto")+" '"+contextURL+"'",Ext.MessageBox.ERROR);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_sin_especificar_contexto"),Ext.MessageBox.ERROR);}
return null;},getWMCStringMap:function(map){var WMCString=this.format.write(map);return WMCString;},getBaseLayers:function(context){var layers=context.layers;var baseLayers=[];for(var int=0;int<layers.length;int++){if(layers[int].isBaseLayer)
baseLayers.push(layers[int]);}
return baseLayers;},loadSphericalMercatorLayers:function(map){layers={gmap:new OpenLayers.Layer.Google("Google Streets",{'sphericalMercator':true,numZoomLevels:20}),gsat:new OpenLayers.Layer.Google("Google Satellite",{type:G_SATELLITE_MAP,'sphericalMercator':true,numZoomLevels:22}),ghyb:new OpenLayers.Layer.Google("Google Hybrid",{type:G_HYBRID_MAP,'sphericalMercator':true,numZoomLevels:22}),yahoo:new OpenLayers.Layer.Yahoo("Yahoo Street",{'sphericalMercator':true}),yahoosat:new OpenLayers.Layer.Yahoo("Yahoo Satellite",{'type':YAHOO_MAP_SAT,'sphericalMercator':true}),yahoohyb:new OpenLayers.Layer.Yahoo("Yahoo Hybrid",{'type':YAHOO_MAP_HYB,'sphericalMercator':true})}
for(key in layers){map.addLayer(layers[key]);}}};WFSMgr={queryOperators:{IGUAL:"IGUAL",DISTINTO:"DISTINTO",MAYOR:"MAYOR",MAYOR_IGUAL:"MAYOR O IGUAL",MENOR:"MENOR",MENOR_IGUAL:"MENOR O IGUAL",NULO:"NULO"},wfsDescribeFeatureFormat:new OpenLayers.Format.WFSDescribeFeatureType(),getFeaturesQuery:function(layer,propertiesToFilter,bbox,outputformat){var xml=this.queryRequest(layer,propertiesToFilter,bbox,outputformat);var features;if(xml){var gmlFormat=new OpenLayers.Format.GML();features=gmlFormat.read(xml);}
return features;},queryRequest:function(layer,propertiesToFilter,bbox,outputformat){var data=this.getQueryData(layer.typename,propertiesToFilter,bbox,outputformat);var request=OpenLayers.Request.POST({url:layer.url,data:data,async:false});return request.responseXML;},getQueryData:function(typename,propertiesToFilter,bbox,outputformat){var properties_to_request="";var filter_properties="";for(var i=0;i<propertiesToFilter.length;i++){if(propertiesToFilter[i]['value']){filter_properties+=this.getQueryFilter(propertiesToFilter[i]);}}
var bbox_aux='';if(bbox){var bounds=bbox.geometry.getBounds();bbox_aux='<ogc:BBOX>'
+'<ogc:PropertyName>the_geom</ogc:PropertyName>'
+'<gml:Envelope>'
+'<gml:lowerCorner>'+bounds.left+' '+bounds.bottom+'</gml:lowerCorner>'
+'<gml:upperCorner>'+bounds.right+' '+bounds.top+'</gml:upperCorner>'
+'</gml:Envelope>'
+'</ogc:BBOX>';}
var data='<wfs:GetFeature service="WFS" version="1.1.0" outputFormat="'+outputformat+'"'
+' xmlns:app="http://www.deegree.org/app"'
+' xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc"'
+' xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
+' xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd"'
+' resultType="results">'
+'<wfs:Query typeName="'+typename+'">'
+properties_to_request
+'<ogc:Filter>'
if(propertiesToFilter.length>1){data=data+'<ogc:And>'
+filter_properties
+bbox_aux
+'</ogc:And>'}
else{data=data+filter_properties
+bbox_aux}
data+='</ogc:Filter>'
+'</wfs:Query>'
+'</wfs:GetFeature>';return data;},getQueryFilter:function(propertie){var filterName='<ogc:PropertyName>'+propertie['name']+'</ogc:PropertyName>';var filterLiteral='<ogc:Literal>'+propertie['value']+'</ogc:Literal>';var filter='';if(propertie['operator']==this.queryOperators.IGUAL){filter='<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="!">'
+filterName+filterLiteral
+'</ogc:PropertyIsLike>';}
else if(propertie['operator']==this.queryOperators.DISTINTO){filter='<ogc:PropertyIsNotEqualTo>'
+filterName+filterLiteral
+'</ogc:PropertyIsNotEqualTo>';}
else if(propertie['operator']==this.queryOperators.MAYOR){filter='<ogc:PropertyIsGreaterThan>'
+filterName+filterLiteral
+'</ogc:PropertyIsGreaterThan>';}
else if(propertie['operator']==this.queryOperators.MAYOR_IGUAL){filter='<ogc:PropertyIsGreaterThanOrEqualTo>'
+filterName+filterLiteral
+'</ogc:PropertyIsGreaterThanOrEqualTo>';}
else if(propertie['operator']==this.queryOperators.MENOR){filter='<ogc:PropertyIsLessThan>'
+filterName+filterLiteral
+'</ogc:PropertyIsLessThan>';}
else if(propertie['operator']==this.queryOperators.MENOR_IGUAL){filter='<ogc:PropertyIsLessThanOrEqualTo>'
+filterName+filterLiteral
+'</ogc:PropertyIsLessThanOrEqualTo>';}
else if(propertie['operator']==this.queryOperators.NULO){filter='<ogc:PropertyIsNull>'
+filterName
+'</ogc:PropertyIsNull>';}
return filter;},getDescribeFeatureUrl:function(layer){var url=layer.getFullRequestString({REQUEST:"DescribeFeatureType"});return url;},getDescribeFeature:function(layer){var urlDescribeFeature=this.getDescribeFeatureUrl(layer);var response=OpenLayers.Request.GET({url:urlDescribeFeature,success:function(){},failure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_obtener_atributos_capa"),Ext.MessageBox.ERROR);},scope:this,async:false});var describeFeature=this.wfsDescribeFeatureFormat.read(response.responseXML);return describeFeature;},getFeatureAttributes:function(layer){var describeFeature=this.getDescribeFeature(layer);var attributes=[];for(var i=0;i<describeFeature.length;i++){attributes.push(describeFeature[i].name);}
return attributes;},getInfoBBOXURL:function(layer,bounds){var url=layer.getFullRequestString({BBOX:bounds.toBBOX()});return url;},getFeaturesByBBOX:function(layer,bounds){var features=null;try{Layout.statusBar.showBusy(Locale.getText("msg_obteniendo_informacion de la capa")+" "+layer.name+" ...");if(bounds!=null){var url=this.getInfoBBOXURL(layer,bounds);var response=OpenLayers.Request.GET({url:url,success:function(){},failure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_obtener_features_bbox"),Ext.MessageBox.ERROR);},scope:this,async:false});var wfsFormat=new OpenLayers.Format.GML();features=wfsFormat.read(response.responseXML);}}
catch(e){Layout.statusBar.clearStatus({useDefaults:true});}
Layout.statusBar.clearStatus({useDefaults:true});return features;},updateFeatures:function(layer,features){var wfsFormat=new OpenLayers.Format.WFS({},layer);var updateData=wfsFormat.write(features);OpenLayers.Request.POST({url:layer.url,data:updateData,success:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_cambios_guardados_ok"),Ext.MessageBox.INFO);},failure:function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_guardar_cambios"),Ext.MessageBox.ERROR);},scope:this});}};FileMgr={url:Config.FILEUPLOAD_URL,saveFile:function(text,fileName){var requestMPD=this.getMultipartRequest(text,fileName)
var request=OpenLayers.Request.POST({url:this.url,data:requestMPD.data,headers:requestMPD.headers,success:function(request){window.open(request.responseText);},failure:function(request){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_contactar_servicio"),Ext.MessageBox.ERROR);}});},getMultipartRequest:function(text,fileName){var request={};request.headers={"Content-Type":"multipart/form-data; boundary=AaB03x","Content-Length":text.length}
request.data="Content-Type: multipart/form-data; boundary=AaB03x\r\n"+"Content-Length:"+text.length+"\r\n"+"\r\n--AaB03x\r\n"+"Content-Disposition: form-data; name=\"path\"; filename=\""+fileName+"\"\r\n"+"\r\n"+text+"\r\n"+"--AaB03x--\r\n"
return request;}}
PrintMgr={url:Config.PRINTWMC_URL,print:function(templateName){Layout.statusBar.showBusy(Locale.getText("msg_preparando_documento")+" ...");var context=WMCMgr.getWMCStringMap(IDEOL.mapMgr.map);var request=OpenLayers.Request.POST({url:this.url+'&template='+templateName,data:context,success:function(request){Layout.statusBar.clearStatus({useDefaults:true});window.open(request.responseText);},failure:function(request){Layout.statusBar.clearStatus({useDefaults:true});UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_contactar_servicio_impresion"),Ext.MessageBox.ERROR);}});}};CSWMgr={getCapabilities:function(url){var data='<?xml version="1.0" encoding="UTF-8"?>'
+'<GetCapabilities service="CSW"></GetCapabilities>';var request=OpenLayers.Request.POST({url:url,data:data,async:false});return request.responseText;},getRecordsSummaryXML:function(url,search_string,category,provider,bbox){var data='<?xml version="1.0" encoding="UTF-8"?>'
+'<csw:GetRecords service="CSW" version="2.0.2" xmlns="http://www.opengis.net/cat/csw"'
+' xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:ogc="http://www.opengis.net/ogc"'
+' xmlns:gml="http://www.opengis.net/gml" outputSchema="csw:Record" resultType="results"  startPosition="1" maxRecords="100">'
+'<csw:Query typeNames="csw:Record" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml">'
+'<ElementSetName>summary</ElementSetName>'
+'<csw:Constraint version="1.1.0">'
var bbox_aux='';if(bbox){bbox_aux='<ogc:BBOX>'
+'<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>'
+'<gml:Envelope>'
+'<gml:lowerCorner>'+bbox.left+' '+bbox.bottom+'</gml:lowerCorner>'
+'<gml:upperCorner>'+bbox.right+' '+bbox.top+'</gml:upperCorner>'
+'</gml:Envelope>'
+'</ogc:BBOX>';}
data+='<ogc:Filter><ogc:And>';if(search_string){data+='<ogc:Or>'
+'<ogc:Or>'
+'<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="\">'
+'<ogc:PropertyName>description</ogc:PropertyName>'
+'<ogc:Literal>*'+search_string+'*</ogc:Literal>'
+'</ogc:PropertyIsLike>'
+'<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="\">'
+'<ogc:PropertyName>subject</ogc:PropertyName>'
+'<ogc:Literal>*'+search_string+'*</ogc:Literal>'
+'</ogc:PropertyIsLike>'
+'</ogc:Or>'
+'<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="\">'
+'<ogc:PropertyName>title</ogc:PropertyName>'
+'<ogc:Literal>*'+search_string+'*</ogc:Literal>'
+'</ogc:PropertyIsLike>'
+'</ogc:Or>'}
if(category){data+='<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="\">'
+'<ogc:PropertyName>topicCat</ogc:PropertyName>'
+'<ogc:Literal>*'+category+'*</ogc:Literal>'
+'</ogc:PropertyIsLike>'}
if(provider){data+='<ogc:PropertyIsLike wildCard="*" singleChar="?" escape="\">'
+'<ogc:PropertyName>orgName</ogc:PropertyName>'
+'<ogc:Literal>*'+provider+'*</ogc:Literal>'
+'</ogc:PropertyIsLike>'}
data+=bbox_aux
+'</ogc:And></ogc:Filter>'
+'</csw:Constraint>'
+'</csw:Query>'
+'</csw:GetRecords>';var request=OpenLayers.Request.POST({url:url,data:data,async:false,failure:function(req){throw(req.status);}});return request.responseXML;},search:function(url,string_search){var data='<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" service="CSW" version="2.0.2" resultType="results" outputSchema="csw:IsoRecord">';data+='<csw:Query><csw:ElementSetName>full</csw:ElementSetName><csw:Constraint version="1.1.0">';data+='<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml">';data+='<PropertyIsLike wildCard="*" singleChar="?" escape="!"><PropertyName>any</PropertyName><Literal>'+search_string+'</Literal></PropertyIsLike>';data+='</Filter></csw:Constraint></csw:Query></csw:GetRecords>';var request=OpenLayers.Request.POST({url:url,data:data,async:false});return request.responseXML;},getRecordsSummary:function(url,title,category,provider,bbox){var xml=null;try{xml=this.getRecordsSummaryXML(url,title,category,provider,bbox).documentElement;}catch(e){throw("Conexión al servidor fallida, código:"+e);return;}
var result=new Array();var records=xml.getElementsByTagName("csw:SummaryRecord");for(var i=0;i<records.length;i++){try{var aux=[];var id=records[i].getElementsByTagName("dc:identifier");aux.push(id[0].textContent);var title=records[i].getElementsByTagName("dc:title");aux.push(title[0].textContent);var description=records[i].getElementsByTagName("dct:abstract");aux.push(description[0].textContent);result.push(aux);}catch(e){throw("Error parseando summary: "+e);}}
return result;},getRecordsById:function(url,uuid){var data='<?xml version="1.0" encoding="UTF-8"?>'
+'<csw:GetRecordById xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" outputSchema="http://www.isotc211.org/2005/gmd" service="CSW" version="2.0.2">'
+'<csw:Id>'+uuid+'</csw:Id>'
+'</csw:GetRecordById>';var request=OpenLayers.Request.POST({url:url,data:data,async:false,failure:function(req){throw(req.status);}});return request.responseXML;},getResources:function(url,uuid){var xml=this.getRecordsById(url,uuid);var resources=xml.getElementsByTagName('gmd:CI_OnlineResource');var res=[];for(var i=0;i<resources.length;i++){var node=resources[i];var aux={};aux.url=this.getNodeValue(resources[i],'gmd:URL');aux.protocol=this.getNodeValue(resources[i].getElementsByTagName('gmd:protocol')[0],'gco:CharacterString');aux.name=this.getNodeValue(resources[i].getElementsByTagName('gmd:name')[0],'gco:CharacterString');res.push(aux);}
return res;},getNodeValue:function(node_name,value){var aux=node_name.getElementsByTagName(value);return(aux[0].textContent);}};InfoCallejeroWindow=function(){this.url=Config.ProxyHost+'http://ideacv.iver.es:8080/wsCallejero/service';this.xmlReader=new Ext.data.XmlReader({record:'via',id:'codigo',totalRecords:'@total'},['nombre','tipo','codigo']);this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:OpenLayers.ProxyHost}),reader:this.xmlReader});this.locateXML=function(codVia,numVia){var xml="<request>";xml+="<tipo>2</tipo>";xml+="<via>";xml+="<codigo>"+codVia+"</codigo>";xml+="<nombre></nombre>";if(numVia.trim()!=""){xml+="<numero>"+numVia+"</numero>";}
else{xml+="<numero>0</numero>";}
xml+="</via>";xml+="<municipio>";xml+="<codigo></codigo>";xml+="<nombre></nombre>";xml+="</municipio>";xml+="</request>";return xml;};this.grid=new Ext.grid.GridPanel({store:this.store,loadMask:true,height:150,autoScroll:true,frame:true,columns:[{header:Locale.getText("txt_tipo"),width:50,dataIndex:'tipo',sortable:true},{header:Locale.getText("txt_via"),autoWidth:'auto',dataIndex:'nombre',sortable:true}],viewConfig:{forceFit:true},sm:new Ext.grid.RowSelectionModel({singleSelect:true})});this.grid.on('rowdblclick',function(){this.doLocate();},this);this.numberTextField=new Ext.form.TextField({width:50,fieldLabel:Locale.getText("txt_numero_via"),id:'numvia',name:'numeroVia',maxLength:4,maxLengthText:Locale.getText("txt_longitud_maxima"),allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.locateForm=new Ext.FormPanel({labelWidth:180,frame:true,bodyStyle:'padding:0px 20px 0px 0px',collapsible:true,defaultType:'textfield',items:[this.numberTextField]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_informacion_vias"),id:'infoCallejeroWin',titleCollapse:true,width:300,autoHeight:true,maximizable:true,constrain:true,resizable:false,draggable:true,collapsible:true,closeAction:'hide',plain:true,items:[this.grid,this.locateForm],buttons:[{text:Locale.getText("txt_localizar"),scope:this,handler:function(){this.doLocate();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();this.locateForm.getForm().reset();}}]});this.prepareGML=function(gmlFeatures){var gml="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"<gml:FeatureCollection xmlns:topp=\"http://www.openplans.org/topp\" xmlns:gml=\"http://www.opengis.net/gml\">";gml+=gmlFeatures;gml+="</gml:FeatureCollection>";return gml;};this.doLocate=function(){var selectionModel=this.grid.getSelectionModel();var record=selectionModel.getSelected();if(selectionModel.getCount()!=0){var codigoVia=record.get("codigo");var numeroVia=this.locateForm.getForm().getValues().numeroVia;if(this.locateForm.getForm().isValid()){var request=OpenLayers.Request.GET({url:this.url+"?xml="+this.locateXML(codigoVia,numeroVia),scope:this,async:false});if(request!=null&&request.responseXML!=null){var formatXML=new OpenLayers.Format.XML();var documentElement=request.responseXML.documentElement;var numSearchElement=formatXML.getElementsByTagNameNS(documentElement,'*','numSearch')[0];var numSearch=formatXML.getChildValue(numSearchElement);var numeroElement=formatXML.getElementsByTagNameNS(documentElement,'*','numero')[0];var numFind=formatXML.getChildValue(numeroElement);var gmlFeatures="";var numChildNodes=formatXML.getElementsByTagNameNS(documentElement,'*','gml')[0].childNodes.length;for(var i=0;i<numChildNodes;i++){gmlFeatures+=formatXML.getElementsByTagNameNS(documentElement,'*','gml')[0].childNodes[i].data;}
var gml=this.prepareGML(gmlFeatures);var format=new OpenLayers.Format.GML({extractAttributes:true});var features=format.read(gml);if(numSearch!=numFind){Ext.MessageBox.show({title:Locale.getText("txt_informacion_vias"),msg:Locale.getText("txt_numero_portal")+numSearch+
Locale.getText("txt_no_pertenece")+record.get("nombre").toUpperCase()+
Locale.getText("msg_localizacion_portal_cercano")+numFind,icon:Ext.MessageBox.INFO,buttons:Ext.MessageBox.OK,fn:IDEOL.layersMgr.drawObjects(features,'EPSG:32628',true,true),scope:this});}
if(features.length>0)
IDEOL.layersMgr.drawObjects(features,'EPSG:32628',true,true);}else
this.showMessageEmptyFeatures();}}else
UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_seleccionar_via"),Ext.MessageBox.WARNING);};this.numberTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.keyEventHandler=function(object,event){if(event.getCharCode()==event.ENTER)
this.doLocate();};this.showMessageEmptyFeatures=function(){UtilsUI.showMessageWindow(Locale.getText("txt_informacion_vias"),Locale.getText("msg_features_vacio"),Ext.MessageBox.INFO);};this.show=function(xml){if(xml.trim()!=''){this.grid.store.removeAll();this.grid.store.proxy.conn.url=this.url+"?xml="+xml;this.grid.store.reload();this.win.show();this.win.expand();}};}
ToponimosWindow=function(){this.layer=null;this.store=new Ext.data.Store({reader:new Ext.data.JsonReader({},['data.id','data.toponimo','geometry'])});this.grid=new Ext.grid.GridPanel({title:Locale.getText("msg_resultados_busqueda"),store:this.store,columns:[{header:Locale.getText("txt_toponimo"),dataIndex:'data.toponimo',sortable:true}],view:new Ext.grid.GridView({forceFit:true}),sm:new Ext.grid.RowSelectionModel({singleSelect:false}),stripeRows:true,autoScroll:true,frame:true,height:200});this.gridLoadMask=null;this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("msg_busqueda_toponimos"),constrainHeader:true,width:350,minWidth:350,height:350,maximizable:false,resizable:false,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.grid],buttons:[{text:Locale.getText("txt_localizar"),scope:this,handler:function(){this.locateFeature();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.show=function(layer,features){this.layer=layer;this.win.show();this.win.expand();this.gridLoadMask=new Ext.LoadMask(this.grid.body);this.grid.store.removeAll();this.gridLoadMask.show();if(features&&features.length>0){this.grid.store.loadData(features);}
else{}
this.gridLoadMask.hide();};this.locateFeature=function(){var selectionModel=this.grid.getSelectionModel();var record=selectionModel.getSelected();if(record){var geometryWKT=record.get("geometry");var WKTFormat=new OpenLayers.Format.WKT();var feature=WKTFormat.read(geometryWKT);var bounds=feature.geometry.getBounds();var lonlat=bounds.getCenterLonLat();IDEOL.layersMgr.drawMarker(lonlat,this.layer.projection,true,true);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elemento_localizar"),Ext.MessageBox.WARNING);}};};StreetViewWindow=function(){this.streetView=null;this.streetViewError=function(errorCode){if(errorCode==603){UtilsUI.showMessageWindow(Locale.getText("txt_error"),"Error: Flash doesn’t appear to be supported by your browser",Ext.MessageBox.WARNING);return;}
if(errorCode==600){UtilsUI.showMessageWindow(Locale.getText("txt_error"),"Street View Not Available For This Location",Ext.MessageBox.WARNING);return;}};this.streetViewInitialized=function(){this.focus();};this.panel=new Ext.Panel({id:'streetViewPanel',layout:'fit'});this.panel.on("resize",function(panel,adjWidth,adjHeight,rawWidth,rawHeight){if(this.streetView)
this.streetView.checkResize();},this);this.panel.on("render",function(panel){if(!this.streetView){this.streetView=new GStreetviewPanorama(panel.getEl().dom,{zoom:0});GEvent.addListener(this.streetView,"error",this.streetViewError);GEvent.addListener(this.streetView,"initialized",this.streetViewInitialized);}},this);this.win=new Ext.Window({layout:'fit',modal:false,title:'StreetView',constrain:true,width:450,minWidth:400,autoHeight:true,maximizable:true,resizable:true,draggable:true,collapsible:false,closeAction:"hide",plain:true,border:false,items:[this.panel],buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.moveTo=function(longlat){if(longlat){longlat.transform(IDEOL.mapMgr.map.getProjectionObject(),new OpenLayers.Projection('EPSG:4326'));var theloc=new GLatLng(longlat.lat,longlat.lon);this.streetView.setLocationAndPOV(theloc);}};this.show=function(lonlat){this.lonlat=lonlat;this.win.show();this.win.expand();this.moveTo(this.lonlat);};};InfoMetadataWindow=function(){this.textArea=new Ext.form.TextArea();this.metadatosPanel=new Ext.Panel({layout:'fit',height:'100%',padding:'2px 2px 2px 2px',closable:true,autoScroll:true});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px',modal:false,title:Locale.getText("txt_informacion_metadato"),id:'infoMetadataWin',constrainHeader:true,width:575,minWidth:575,height:500,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.metadatosPanel],buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.show=function(xmlDocument,xslString){var html=XSLMgr.transformXML(xmlDocument,xslString);this.win.show();this.metadatosPanel.html=html;this.metadatosPanel.body.update(html);};};InfoLinksWindow=function(){this.map=null;this.features=null;this.URL_IMAGES='http://213.172.37.189/DatosCabildo/1956/';this.initialize=function(map){this.map=map;};this.store=new Ext.data.Store({reader:new Ext.data.JsonReader({},['enlace','name'])});this.tpl2=new Ext.XTemplate('<tpl for=".">','<div class="thumb-wrap" id="{name}">','<div class="thumb"><img src="{enlace}" title="{name}"></div>','<span class="x-editable">{name}</span></div>','</tpl>','<div class="x-clear"></div>');this.tpl=new Ext.XTemplate('<h2>Listado de imágenes</h2>','<tpl for=".">','<div class="link-wrap" style="padding: 2px 2px 2px 2px"><a href="{enlace}">{name}</a></div>','</tpl>');this.dataView=new Ext.DataView({store:this.store,tpl:this.tpl,autoHeight:true,singleSelect:true,multiSelect:false,overClass:'x-view-over',itemSelector:'div.link-wrap',emptyText:'Sin enlaces'});this.linksPanel=new Ext.Panel({id:'linksPanel',bodyStyle:'padding: 4px',frame:true,height:200,autoScroll:true,layout:'fit',items:[this.dataView]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px',modal:false,title:Locale.getText("txt_informacion_wms"),id:'infoImagesWin',constrainHeader:true,width:275,minWidth:275,autoHeight:true,maximizable:false,resizable:false,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.linksPanel],buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.prepareFeatures=function(features){var arrayFeatures=[];for(var i=0;i<features.length;i++){var feature={};feature.enlace=this.URL_IMAGES+features[i].data.enlace;feature.name=features[i].data.enlace;arrayFeatures.push(feature);}
return arrayFeatures;};this.loadDataView=function(title){if(this.features&&this.features.length>0){var features=this.prepareFeatures(this.features);this.store.removeAll();this.store.loadData(features);this.win.setTitle(Locale.getText("txt_informacion_wms")+"  -  "+title);this.win.show();this.win.expand();return true;}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_informacion"),Ext.MessageBox.INFO);}
return false;};this.show=function(features,title){this.features=features;this.loadDataView(title);};};InfoImagesWindow=function(){this.map=null;this.features=null;this.URL_IMAGES='http://213.172.37.189/DatosCabildo/1956/';this.initialize=function(map){this.map=map;};this.store=new Ext.data.Store({reader:new Ext.data.JsonReader({},['enlace','name'])});this.tpl=new Ext.XTemplate('<tpl for=".">','<div class="thumb-wrap" id="{name}">','<div class="thumb"><img src="{enlace}" title="{name}"></div>','<span class="x-editable">{name}</span></div>','</tpl>','<div class="x-clear"></div>');this.dataView=new Ext.DataView({store:this.store,tpl:this.tpl,autoHeight:true,singleSelect:true,multiSelect:false,overClass:'x-view-over',itemSelector:'div.thumb-wrap',emptyText:'No images to display'});this.Imagespanel=new Ext.Panel({id:'images-view',frame:true,width:535,height:300,layout:'fit',items:[this.dataView]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_informacion_wms"),id:'infoImagesWin',constrainHeader:true,width:535,minWidth:535,autoHeight:true,maximizable:false,resizable:false,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.Imagespanel],buttons:[{text:Locale.getText("txt_ampliar"),scope:this,handler:function(){var nodes=this.dataView.getSelectedNodes();if(nodes.length==1){var node=nodes[0];var value=node.attributes[0].nodeValue;var url=this.URL_IMAGES+value;window.open(url);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_imagen_ampliar"),Ext.MessageBox.WARNING);}}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.prepareFeatures=function(features){var arrayFeatures=[];for(var i=0;i<features.length;i++){var feature={};feature.enlace=this.URL_IMAGES+features[i].data.enlace;feature.name=features[i].data.enlace;arrayFeatures.push(feature);}
return arrayFeatures;};this.loadDataView=function(title){if(this.features&&this.features.length>0){var features=this.prepareFeatures(this.features);this.store.removeAll();this.store.loadData(features);this.win.setTitle(Locale.getText("txt_informacion_wms")+"  -  "+title);this.win.show();this.win.expand();return true;}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_informacion"),Ext.MessageBox.INFO);}
return false;};this.show=function(features,title){this.features=features;this.loadDataView(title);};};InfoWMSWindow=function(){this.map=null;this.features=null;this.initialize=function(map){this.map=map;};this.grid=new Ext.grid.GridPanel({layout:'fit',store:new Ext.data.Store({reader:new Ext.data.JsonReader({},[])}),columns:[],view:new Ext.grid.GridView({forceFit:true}),sm:new Ext.grid.RowSelectionModel({singleSelect:false}),stripeRows:true,autoScroll:true,frame:true,iconCls:'icon-grid',height:250,autoExpanColumn:'geometry'});this.grid.on('afteredit',function(){this.getSaveButton().enable();},this);this.grid.on('rowclick',function(index){},this);this.getLastColumnId=function(){return this.grid.getColumnModel().getColumnId(this.grid.getColumnModel().getColumnCount()-1);};this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_informacion_wms"),id:'infoWMSWin',constrainHeader:true,width:650,minWidth:650,autoHeight:true,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.grid],buttons:[{text:Locale.getText("txt_localizar"),disabled:true,scope:this,handler:function(){this.locateFeature();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.getFeatureByFid=function(fid){var features=this.layer.features;for(i=0;i<features.length;i++){if(features[i].fid==fid)
return features[i];}};this.locateFeature=function(){var selectionModel=this.grid.getSelectionModel();var records=selectionModel.getSelections();if(records.length==0){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elemento_localizar"),Ext.MessageBox.WARNING);}
else if(records.length>1){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_unico_elemento_localizar"),Ext.MessageBox.WARNING);}
else if(records.length==1){var record=records[0];var geometryWKT=record.get("geometry");var WKTFormat=new OpenLayers.Format.WKT();var feature=WKTFormat.read(geometryWKT);var bounds=feature.geometry.getBounds();bounds.transform(this.featuresProjection,this.map.getProjectionObject());var size=new OpenLayers.Size(20,34);var offset=new OpenLayers.Pixel(-(size.w/2),-size.h);var icon=new OpenLayers.Icon('ide/images/yellowMarker.png',size,offset);var lonlat=bounds.getCenterLonLat();var marker=new OpenLayers.Marker(lonlat,icon);this.marker=marker;IDEOL.layersMgr.addMarker(marker);var zoom=this.map.getNumZoomLevels();this.map.setCenter(lonlat,zoom-3);}};this.getFeatureFromRecord=function(record){var feature=new OpenLayers.Feature();feature.fid=record.data.fid;feature.geometry=record.data.geometry;for(key in record.data){if(key!='fid'&&key!='geometry'){validKey=key.split(".");feature.data[validKey[1]]=record.data[key]}}
return feature;};this.getDescribeFeatureData=function(feature){var data=[];data.push('fid');for(key in feature.data){if(key!="the_geom")
data.push('data.'+key);}
data.push('geometry');return data;};this.getStore=function(describeFeatureData){var jsonReader=new Ext.data.JsonReader({},describeFeatureData);var store=new Ext.data.Store({reader:jsonReader});return store;};this.getColumnModel=function(describeFeatureData){var columns=[];for(var i=0;i<describeFeatureData.length;i++){var dataHeaderTitle=describeFeatureData[i].split(".")[1];if(describeFeatureData[i]=='fid')
columns.push({header:'Fid',dataIndex:describeFeatureData[i],sortable:true,hidden:true});else if(describeFeatureData[i]=='geometry')
columns.push({header:'Geometry',dataIndex:describeFeatureData[i],sortable:true,width:300,hidden:true});else
columns.push({header:dataHeaderTitle,dataIndex:describeFeatureData[i],sortable:true,editor:new Ext.form.TextField()});}
var columnModel=new Ext.grid.ColumnModel({columns:columns});return columnModel;};this.reloadGrid=function(){this.grid.store.loadData(this.features);};this.loadGrid=function(title){if(this.features&&this.features.length>0){var feature=this.features[0];var describeFeatureData=this.getDescribeFeatureData(feature);var store=this.getStore(describeFeatureData);var columnModel=this.getColumnModel(describeFeatureData);store.loadData(this.features);this.grid.store.removeAll();this.win.setTitle(Locale.getText("txt_informacion_wms")+"  -  "+title);this.win.show();this.win.expand();this.grid.reconfigure(store,columnModel);return true;}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_informacion"),Ext.MessageBox.INFO);this.grid.store.removeAll();}
return false;};this.show=function(features,title){this.features=features;this.loadGrid(title);};};InfoXSLWMSWindow=function(){this.textArea=new Ext.form.TextArea();this.wmsPanel=new Ext.Panel({layout:'fit',height:'100%',padding:'2px 2px 2px 2px',closable:true,autoScroll:true});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px',modal:false,title:Locale.getText("txt_informacion_wms"),constrainHeader:true,width:575,minWidth:575,height:500,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.wmsPanel],buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.show=function(xmlString,xslString){var html=XSLMgr.transformString(xmlString,xslString);this.win.show();this.wmsPanel.html=html;this.wmsPanel.body.update(html);};};InfoWFSWindow=function(){this.map=null;this.layer=null;this.bounds=null;this.initialize=function(map){this.map=map;};this.grid=new Ext.grid.EditorGridPanel({layout:'fit',store:new Ext.data.Store({reader:new Ext.data.JsonReader({},[])}),columns:[],view:new Ext.grid.GridView({forceFit:true}),sm:new Ext.grid.RowSelectionModel({singleSelect:false}),stripeRows:true,autoScroll:true,frame:true,iconCls:'icon-grid',height:200,clicksToEdit:2,autoExpanColumn:'geometry'});this.grid.on('afteredit',function(){this.getSaveButton().enable();},this);this.grid.on('rowclick',function(index){},this);this.getLastColumnId=function(){return this.grid.getColumnModel().getColumnId(this.grid.getColumnModel().getColumnCount()-1);};this.getSaveButton=function(){return Ext.getCmp('saveFeaturesDataButton');};this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_informacion_wfs"),id:'infoWFSWin',constrainHeader:true,width:550,minWidth:550,autoHeight:true,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.grid],buttons:[{text:Locale.getText("txt_localizar"),scope:this,handler:function(){this.locateFeature();}},{id:'saveFeaturesDataButton',text:Locale.getText("txt_guardar"),disabled:true,scope:this,handler:function(){this.saveChanges();}},{text:Locale.getText("txt_eliminar"),scope:this,handler:function(){this.deleteFeature();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.getFeatureByFid=function(fid){var features=this.layer.features;for(i=0;i<features.length;i++){if(features[i].fid==fid)
return features[i];}},this.saveChanges=function(){var features=this.getModifiedFeatures();if(features.length>0){IDEOL.editionMgr.saveDataFeatures(features);this.getSaveButton().disable();this.grid.store.commitChanges();this.reloadGrid();}};this.deleteFeature=function(){var selectionModel=this.grid.getSelectionModel();var records=selectionModel.getSelections();if(records.length>0){Ext.MessageBox.confirm(Locale.getText("txt_confirmacion"),Locale.getText("msg_eliminar_geometrias_seleccionadas?"),function(button){var confirm=false;if(button=="yes")
confirm=true;if(confirm){var features=[];for(var i=0;i<records.length;i++){if(records[i]){var fid=records[i].get("fid");var feature=this.getFeatureByFid(fid);features.push(feature);}}
IDEOL.editionMgr.deleteFeatures(features);this.reloadGrid();}},this);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elementos_eliminar"),Ext.MessageBox.WARNING);}};this.locateFeature=function(){var selectionModel=this.grid.getSelectionModel();var records=selectionModel.getSelections();if(records.length==0){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elemento_localizar"),Ext.MessageBox.WARNING);}
else if(records.length>1){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_unico_elemento_localizar"),Ext.MessageBox.WARNING);}
else if(records.length==1){var record=records[0];var geometryWKT=record.get("geometry");var WKTFormat=new OpenLayers.Format.WKT();var feature=WKTFormat.read(geometryWKT);var bounds=feature.geometry.getBounds();var lonlat=bounds.getCenterLonLat();IDEOL.layersMgr.drawMarker(lonlat,this.layer.projection.getCode(),true,true);}};this.getFeatureFromRecord=function(record){var feature=new OpenLayers.Feature();feature.fid=record.data.fid;feature.geometry=record.data.geometry;for(key in record.data){if(key!='fid'&&key!='geometry'){validKey=key.split(".");feature.data[validKey[1]]=record.data[key]}}
return feature;};this.getModifiedFeatures=function(){var records=this.grid.getStore().getModifiedRecords();var features=[];for(var i=0;i<records.length;i++){features.push(this.getFeatureFromRecord(records[i]));}
return features;};this.getDescribeFeatureData=function(describeFeature){var data=[];data.push('fid');for(var i=0;i<describeFeature.length;i++){if(describeFeature[i].name!="the_geom")
data.push('data.'+describeFeature[i].name);}
data.push('geometry');return data;};this.getStore=function(describeFeatureData){var jsonReader=new Ext.data.JsonReader({},describeFeatureData);var store=new Ext.data.Store({reader:jsonReader});return store;};this.getColumnModel=function(describeFeatureData){var columns=[];for(var i=0;i<describeFeatureData.length;i++){var dataHeaderTitle=describeFeatureData[i].split(".")[1];if(describeFeatureData[i]=='fid')
columns.push({header:'Fid',dataIndex:describeFeatureData[i],sortable:true,hidden:true});else if(describeFeatureData[i]=='geometry')
columns.push({header:'Geometry',dataIndex:describeFeatureData[i],sortable:true,hidden:true,width:300});else
columns.push({header:dataHeaderTitle,dataIndex:describeFeatureData[i],sortable:true,editor:new Ext.form.TextField()});}
var columnModel=new Ext.grid.ColumnModel({columns:columns});return columnModel;};this.reloadGrid=function(){var features=WFSMgr.getFeaturesByBBOX(this.layer,this.bounds);this.grid.store.loadData(features);};this.loadGrid=function(){var features=WFSMgr.getFeaturesByBBOX(this.layer,this.bounds);if(features&&features.length>0){var describeFeature=WFSMgr.getDescribeFeature(this.layer);var describeFeatureData=this.getDescribeFeatureData(describeFeature);var store=this.getStore(describeFeatureData);var columnModel=this.getColumnModel(describeFeatureData);store.loadData(features);this.grid.store.removeAll();this.grid.reconfigure(store,columnModel);return true;}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_features_bbox_seleccionado"),Ext.MessageBox.WARNING);}
return false;};this.show=function(layer,bounds){if(layer&&bounds){this.layer=layer;this.bounds=bounds;if(this.loadGrid()){this.win.setTitle(Locale.getText("txt_informacion_wfs")+"  -  "+this.layer.name);this.win.show();this.win.expand();}}};};UploadFileWindow=function(){this.url=Config.ProxyHost+Config.FILEUPLOAD_URL;this.fileUploadField=new Ext.form.FileUploadField({id:'uploadFileField',emptyText:Locale.getText("msg_seleccionar_fichero"),fieldLabel:Locale.getText("txt_fichero"),width:350,name:'path',buttonCfg:{text:'',iconCls:'upload-icon'}});this.form=new Ext.FormPanel({fileUpload:true,width:300,frame:true,autoHeight:true,bodyStyle:'padding: 10px 10px 0 10px;',labelWidth:50,defaults:{anchor:'92%',allowBlank:false,msgTarget:'side'},items:[this.fileUploadField]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:true,title:Locale.getText("txt_cargar_mapa"),id:'uploadFileWin',constrainHeader:true,width:300,autoHeight:true,maximizable:false,resizable:false,draggable:true,closeAction:"hide",plain:true,border:false,items:[this.form],buttons:[{text:Locale.getText("txt_enviar"),scope:this,handler:function(){if(this.form.getForm().isValid()){this.form.getForm().submit({url:this.url,scope:this,success:function(form,action){var fileName=form.items.items[0].value;this.win.hide();IDEOL.initialize(action.result,fileName);},failure:function(fomr,transport){this.win.hide();UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_error_obtener_fichero"),Ext.MessageBox.ERROR);}});}}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.show=function(){this.win.show();this.win.expand();};};SaveFileWindow=function(){this.map;this.initialize=function(mapOL){this.map=mapOL;};this.infoPanel=new Ext.Panel({id:'infoExportMapPanel',html:Locale.getText('msg_exportar_wmc')});this.nameTextField=new Ext.form.TextField({xtype:'textfield',fieldLabel:Locale.getText("txt_nombre"),id:'name',name:'name',allowBlank:false,blankText:Locale.getText("msg_introducir_nombre"),enableKeyEvents:true,anchor:'95%'});this.nameTextField.on('keypress',function(object,event){if(event.getCharCode()==event.ENTER)
this.saveFile();},this);this.form=new Ext.FormPanel({width:350,frame:true,autoHeight:true,bodyStyle:'padding: 10px 10px 0 10px;',labelWidth:50,defaults:{anchor:'92%',allowBlank:false,msgTarget:'side'},items:[this.infoPanel,this.nameTextField]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:true,title:Locale.getText("txt_guardar_mapa"),id:'saveFileWin',constrainHeader:true,width:350,autoHeight:true,maximizable:false,resizable:false,draggable:true,closeAction:"hide",plain:true,border:false,items:[this.form],buttons:[{text:Locale.getText("txt_guardar"),scope:this,handler:function(){if(this.form.getForm().isValid()){this.saveFile();}}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.saveFile=function(){var wmcString=WMCMgr.getWMCStringMap(this.map);var values=this.form.getForm().getValues();FileMgr.saveFile(wmcString,values.name+".cml");this.win.hide();};this.show=function(){this.form.getForm().reset();this.win.show();this.win.expand();this.nameTextField.focus('',10);};};HelpWindow=function(){this.textArea=new Ext.form.TextArea();this.helpPanel=new Ext.Panel({layout:'fit',height:'100%',padding:'2px 2px 2px 2px',closable:true,autoScroll:true});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px',modal:false,title:Locale.getText("txt_ayuda"),constrainHeader:true,width:715,minWidth:715,height:500,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.helpPanel],buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.getHelp=function(){var helpFile="ide/help/"+Locale.lang+"/index.html";var request=OpenLayers.Request.GET({url:helpFile,async:false});return request.responseText;};this.show=function(){this.win.show();var html=this.getHelp();this.helpPanel.body.update(html);};};MoveToLonLatPanel=Ext.extend(Ext.Panel,{title:Locale.getText("msg_centrado_coordenadas"),border:false,collapsed:true,iconCls:'moveToLonLatPanel',autoScroll:true,storeProjections:new Ext.data.SimpleStore({fields:['desc','projection'],data:[['EPSG:32628 (UTM28N)','EPSG:32628'],['EPSG:4326 (Lat-Long)','EPSG:4326']]}),comboProjections:new Ext.form.ComboBox({width:125,displayField:'desc',valueField:'projection',fieldLabel:Locale.getText("txt_proyeccion"),name:'nombre',mode:'local',typeAhead:false,triggerAction:'all',allowBlank:false,selectOnFocus:true,editable:false,anchor:'95%'}),longitudTextField:new Ext.form.NumberField({fieldLabel:Locale.getText("txt_longitud"),name:'longitud',allowBlank:false,allowDecimals:true,allowNegative:true,enableKeyEvents:true,anchor:'95%'}),latitudTextField:new Ext.form.NumberField({fieldLabel:Locale.getText("txt_latitud"),name:'latitud',allowBlank:false,allowDecimals:true,allowNegative:true,enableKeyEvents:true,anchor:'95%'}),form:new Ext.FormPanel({frame:true,labelWidth:70,autoHeight:true,bodyStyle:'padding: 2px 2px 0 2px;',labelWidth:70}),moveToLonLat:function(){if(this.form.getForm().isValid()){var longitud=this.longitudTextField.getValue();var latitud=this.latitudTextField.getValue();var srs=this.comboProjections.getRawValue();var lonlat=new OpenLayers.LonLat(longitud,latitud);IDEOL.layersMgr.drawMarker(lonlat,srs,true,true);}},initComponent:function(){MoveToLonLatPanel.superclass.initComponent.call(this);this.comboProjections.store=this.storeProjections;this.comboProjections.on('expand',function(comboBox){this.comboProjections.list.setWidth('auto');this.comboProjections.innerList.setWidth('auto');},this,{single:true});this.comboProjections.on('beforeselect',function(combo,record,index){combo.setRawValue(record.data[combo.valueField]);combo.collapse();return false;},this);this.latitudTextField.on('keypress',function(object,event){if(event.getCharCode()==event.ENTER)
this.moveToLonLat();},this);this.form.add(this.comboProjections);this.form.add(this.longitudTextField);this.form.add(this.latitudTextField);this.form.addButton({text:Locale.getText("txt_centrar")},function(button,event){this.moveToLonLat();},this);this.add(this.form);}});ToponimosPanel=Ext.extend(Ext.Panel,{title:Locale.getText("msg_busqueda_toponimos"),border:false,collapsed:true,iconCls:'toponimosPanel',autoScroll:true,autoHeight:true,mask:null,toponimosWindow:new ToponimosWindow(),layer:new OpenLayers.Layer.WFS("Toponimos","http://www.mapasdelapalma.es/geoserver/wfs",{typename:'cabildo:toponimos'},{typename:"toponimos",featureNS:"http://cabildo.iver.es",projection:"EPSG:32628",extractAttributes:true,isBaseLayer:false,visibility:false,displayInLayerSwitcher:false}),initComponent:function(){ToponimosPanel.superclass.initComponent.call(this);this.on('render',function(form){this.mask=new Ext.LoadMask(this.body,{msg:Locale.getText("msg_obteniendo_datos")+" ..."});},this);this.toponimoTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.form.add(this.toponimoTextField);this.form.addButton({text:Locale.getText("txt_buscar")},function(button,event){this.doSearch();},this);this.add(this.form);},keyEventHandler:function(object,event){if(event.getCharCode()==event.ENTER)
this.doSearch();},toponimoTextField:new Ext.form.TextField({fieldLabel:Locale.getText("txt_toponimo"),name:'toponimo',allowBlank:false,enableKeyEvents:true,anchor:'95%'}),searchButton:new Ext.Button({text:Locale.getText("txt_buscar"),scope:this,handler:function(){this.doSearch();}}),form:new Ext.FormPanel({frame:true,bodyStyle:'padding:5px 5px 0',autoHeight:true,labelWidth:70,defaultButton:0}),doSearch:function(){if(this.form.getForm().isValid()){this.mask.show();var toponimo=this.toponimoTextField.getValue().toUpperCase();var attr=[];attr.push({name:'toponimo',header:'Tema',value:"*"+toponimo+"*",operator:WFSMgr.queryOperators.IGUAL});var features=WFSMgr.getFeaturesQuery(this.layer,attr,null,'GML2');this.toponimosWindow.show(this.layer,features);this.mask.hide();}}});CatastroClient=Ext.extend(Ext.Panel,{url:'http://www.mapasdelapalma.es/wsCatastro/wsCatastro?key=495d5f3988d11213827b325f4504a30f',provincia:'S.C. TENERIFE',title:Locale.getText("msg_busqueda_parcelas"),border:false,iconCls:'catastroClient',autoHeight:true,selectedMunicipioRecord:null,mask:null,storeProvincias:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:OpenLayers.ProxyHost}),reader:new Ext.data.XmlReader({record:'prov',id:'cpine',totalRecords:'@total'},['cpine','np'])}),storeMunicipios:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:OpenLayers.ProxyHost}),reader:new Ext.data.XmlReader({record:'muni',totalRecords:'@total'},['locat.cd','nm'])}),comboProvincias:new Ext.form.ComboBox({displayField:'np',fieldLabel:Locale.getText("txt_provincia"),name:'np',typeAhead:true,triggerAction:'all',allowBlank:false,selectOnFocus:true,editable:false,anchor:'95%'}),comboMunicipios:new Ext.form.ComboBox({displayField:'nm',fieldLabel:Locale.getText("txt_municipio"),name:'nm',typeAhead:true,triggerAction:'all',allowBlank:false,disabled:true,selectOnFocus:true,editable:false,anchor:'95%'}),keyEventHandler:function(object,event){if(event.getCharCode()==event.ENTER){this.locate();}},parcelaTextField:new Ext.form.NumberField({fieldLabel:Locale.getText("txt_parcela"),name:'parcela',allowBlank:false,allowDecimals:false,allowNegative:false,maxLength:5,enableKeyEvents:true,anchor:'95%'}),rfcTextField:new Ext.form.TextField({fieldLabel:Locale.getText("txt_rfc"),name:'rfc',allowBlank:true,enableKeyEvents:true,anchor:'95%'}),poligonoTextField:new Ext.form.NumberField({fieldLabel:Locale.getText("txt_poligono"),allowBlank:false,allowDecimals:false,allowNegative:false,maxLength:3,enableKeyEvents:true,name:'poligono',enableKeyEvents:true,anchor:'95%'}),form:new Ext.form.FormPanel({labelWidth:60,frame:true,bodyStyle:'padding:5px 5px 0',defaultButton:0}),locate:function(){this.mask.show();var provincia=this.comboProvincias.getValue().trim();var municipio=this.comboMunicipios.getValue().trim();var parcela=this.parcelaTextField.getValue();var poligono=this.poligonoTextField.getValue();var rfc=this.rfcTextField.getValue().trim();municipio=(municipio=="")?"":municipio;parcela=(parcela=="")?"":parcela;poligono=(poligono=="")?"":poligono;rfc=(rfc=="")?"":rfc;var parameters="provincia="+escape(provincia)+"&municipio="+escape(municipio)+"&parcela="+parcela+"&poligono="+poligono+"&rfc="+rfc
OpenLayers.Request.GET({url:this.url+'&'+parameters,failure:this.onLocateFailure,success:this.onLocateSuccess,scope:this});},onLocateFailure:function(response){this.mask.hide();UtilsUI.showMessageWindow(Localle.getText("txt_error"),Locale.getText("msg_error_contactar_servicio_catastro"),Ext.MessageBox.ERROR);},onLocateSuccess:function(response){this.mask.hide();if(response!=null&&response.responseXML!=null){var error=response.responseXML.getElementsByTagName("error");if(error[0]!=null){var errorDesc=error[0].attributes[0].value;UtilsUI.showMessageWindow("Información",errorDesc,Ext.MessageBox.ERROR);}
else{var longitud=response.responseXML.getElementsByTagName("longitud")[0].textContent;var latitud=response.responseXML.getElementsByTagName("latitud")[0].textContent;var lonlat=new OpenLayers.LonLat(longitud,latitud);IDEOL.layersMgr.drawMarker(lonlat,'EPSG:4326',true,true);}}},initialize:function(){this.on('render',function(form){this.mask=new Ext.LoadMask(this.body,{msg:Locale.getText("msg_obteniendo_datos")+" ..."});},this);this.form.add(this.comboProvincias);this.comboProvincias.store=this.storeProvincias;var parameters="getProvincias=";this.comboProvincias.store.proxy.conn.url=Config.ProxyHost+encodeURIComponent(this.url+'&'+parameters);this.comboProvincias.store.on('load',function(store,records,options){},this);this.comboProvincias.on('render',function(combo){},this);this.comboProvincias.on('select',function(combo,record,index){this.comboMunicipios.setDisabled(false);var parameters="getMunicipios="+record.data.cpine;this.comboMunicipios.store.proxy.conn.url=Config.ProxyHost+encodeURIComponent(this.url+'&'+parameters);this.comboMunicipios.clearValue();this.comboMunicipios.store.removeAll();this.comboMunicipios.store.reload();},this);this.form.add(this.comboMunicipios);this.comboMunicipios.store=this.storeMunicipios;this.comboMunicipios.store.on('load',function(comboBox){if(this.comboMunicipios.list){this.comboMunicipios.list.setWidth('auto');this.comboMunicipios.innerList.setWidth('auto');}},this);this.comboMunicipios.on('select',function(comboBox,record,index){this.selectedMunicipioRecord=this.comboMunicipios.store.getAt(index);},this);this.form.add(this.poligonoTextField);this.poligonoTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.form.add(this.parcelaTextField);this.parcelaTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.form.add(this.rfcTextField);this.rfcTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.form.addButton({text:'Localizar'},function(button,event){this.locate();},this);this.add(this.form)},initComponent:function(){CatastroClient.superclass.initComponent.call(this);this.initialize();}});CallejeroClient=Ext.extend(Ext.Panel,{title:Locale.getText("msg_busqueda_callejero"),border:false,autoHeight:true,iconCls:'callejeroClient',url:Config.ProxyHost+'http://www.mapasdelapalma.es/wsCallejero/service',codMun:null,infoWin:new InfoCallejeroWindow(),xmlVia:null,xmlReader:new Ext.data.XmlReader({record:'municipio',id:'codigo',totalRecords:'@total'},['codigo','nombre']),store:new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:OpenLayers.ProxyHost})}),createXML:function(){var xml="<request>";xml+="<tipo>0</tipo>";xml+="<via>";xml+="<codigo></codigo>";xml+="<nombre></nombre>";xml+="<numero></numero>";xml+="</via>";xml+="<municipio>";xml+="<codigo></codigo>";xml+="<nombre></nombre>";xml+="</municipio>";xml+="</request>";return xml;},searchXML:function(nombreVia,codMun){var xml="<request>";xml+="<tipo>1</tipo>";xml+="<via>";xml+="<codigo></codigo>";xml+="<nombre>"+nombreVia+"</nombre>";xml+="<numero></numero>";xml+="</via>";xml+="<municipio>";xml+="<codigo>"+codMun+"</codigo>";xml+="<nombre></nombre>";xml+="</municipio>";xml+="</request>";return xml;},cbox:new Ext.form.ComboBox({id:'munCbox',labelWidth:60,anchor:'95%',name:'municipio',fieldLabel:Locale.getText("txt_municipio"),displayField:'nombre',typeAhead:true,forceSelection:true,triggerAction:'all',blankText:Locale.getText("txt_campo_obligatorio"),selectOnFocus:true,allowBlank:false,editable:false,handler:function(){}}),form:new Ext.FormPanel({labelWidth:60,frame:true,bodyStyle:'padding: 5px 5px 0',defaultType:'textfield',items:[new Ext.form.TextField({anchor:'95%',fieldLabel:Locale.getText("txt_via"),id:'nomVia',name:'nomVia',allowBlank:false,blankText:Locale.getText("txt_campo_obligatorio"),enableKeyEvents:true})]}),doSearch:function(){var xmlVia;if(this.form.getForm().isValid()){var nombreVia=this.form.getForm().getValues().nomVia;xmlVia=this.searchXML(nombreVia,this.codMun);}
else{xmlVia="";}
return xmlVia;},keyEventHandler:function(object,event){if(event.getCharCode()==event.ENTER)
this.infoWin.show(this.doSearch());},prepareCombo:function(){this.store.on('load',function(comboBox){this.cbox.list.setWidth('auto');this.cbox.innerList.setWidth('auto');},this,{single:true});this.cbox.store=this.store;this.cbox.store.reader=this.xmlReader;this.cbox.store.proxy.conn.url=this.url+"?xml="+this.createXML();},initComponent:function(){CallejeroClient.superclass.initComponent.call(this);this.prepareCombo();this.form.addButton({text:Locale.getText("txt_buscar")},function(button,event){this.infoWin.show(this.doSearch());},this);this.form.getComponent('nomVia').on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.on('render',function(panel){this.form.add(this.cbox);this.add(this.form);});this.cbox.on('select',function(){if(this.cbox.selectedIndex!=null){this.codMun=this.cbox.store.getAt(this.cbox.selectedIndex).get('codigo');}},this);}});function CSWClient(){this.url=Config.CSW_URL;this.xslMetadataURL='ide/xsl/catalog.xsl';this.xslMetadataString=null;this.store=new Ext.data.SimpleStore({fields:[{name:'id'},{name:'title'},{name:'description'}]});this.resultTpl=new Ext.XTemplate('<tpl for=".">','<div class="search-item">','<h3><span><a href="javascript: IDEOL.cswClient.addLayer(\'{id}\');">'+Locale.getText("txt_anyadir_capa")+'</a><br /><a href="javascript: IDEOL.cswClient.getMetadata(\'{id}\');">'+Locale.getText("txt_mostrar_metadato")+'</a></span>','<h2 style="color: Black; font-weight: bold;">{title}</h2></h3>','<p>{description}</p>','</div></tpl>',{showId:function(id){alert(id);}});this.dataView=new Ext.DataView({tpl:this.resultTpl,loadingText:Locale.getText("msg_obteniendo_resultados"),store:this.store,itemSelector:'div.search-item'}),this.keyEventHandler=function(object,event){if(event.getCharCode()==event.ENTER)
this.doSearch();};this.searchField=new Ext.form.TextField({width:200,fieldLabel:Locale.getText("txt_busqueda"),name:'titulo',allowBlank:false,blankText:Locale.getText("msg_introducir_texto_comodines"),enableKeyEvents:true,anchor:'95%'});this.searchField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.categoriaField=new Ext.form.TextField({fieldLabel:Locale.getText("txt_categoria"),id:'categoria',name:'categoria',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.categoriaField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.proveedorField=new Ext.form.TextField({fieldLabel:Locale.getText("txt_proveedor"),id:'proveedor',name:'proveedor',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.proveedorField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.lonMinField=new Ext.form.TextField({fieldLabel:'LonMin',id:'lonmin',name:'lonmin',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.lonMaxField=new Ext.form.TextField({fieldLabel:'LonMax',id:'lonmax',name:'lonmax',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.latMinField=new Ext.form.TextField({fieldLabel:'LatMin',id:'latmin',name:'latmin',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.latMaxField=new Ext.form.TextField({fieldLabel:'LatMax',id:'latmax',name:'latmax',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.latMaxField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.searchPanel=new Ext.FormPanel({columnWidth:.4,layout:'fit',labelAlign:'top',frame:true,bodyStyle:'padding:5px 5px 0',height:250,defaultButton:0,items:[{layout:'column',border:false,items:[{columnWidth:.6,layout:'form',items:[this.searchField,this.categoriaField,this.proveedorField]},{columnWidth:.4,layout:'form',items:[this.lonMinField,this.lonMaxField,this.latMinField,this.latMaxField]}]}],buttons:[{text:Locale.getText("txt_buscar"),pressed:true,scope:this,handler:function(){this.doSearch();}}]});this.dataViewPanel=new Ext.Panel({title:Locale.getText("msg_resultados_busqueda"),columnWidth:.6,height:250,autoScroll:true,items:[this.searchPanel,this.dataView]});this.containerPanel=new Ext.Panel({autoHeight:true,autoScroll:true,layout:'column',items:[this.searchPanel,this.dataViewPanel]});this.window=new Ext.Window({constrainHeader:true,collapsible:true,resizable:true,maximizable:true,id:'metadata',layout:'fit',title:Locale.getText("txt_catalogo"),titleCollapse:true,width:575,autoHeight:true,closeAction:'hide',plain:true,buttons:[{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.window.hide();}}],items:[this.containerPanel]});this.show=function(){this.window.show();this.window.expand();this.searchField.focus('',10);};this.doSearch=function(){var what_search=this.searchField.getValue().trim();var category=this.categoriaField.getValue().trim();var provider=this.proveedorField.getValue().trim();var lonMin=this.lonMinField.getValue().trim();var lonMax=this.lonMaxField.getValue().trim();var latMin=this.latMinField.getValue().trim();var latMax=this.latMaxField.getValue().trim();if(what_search){var bbox=null;if(lonMin&&lonMax&&latMin&&latMax){bbox=new OpenLayers.Bounds(lonMin,latMax,lonMax,latMin);}
var myMask=new Ext.LoadMask(this.containerPanel.body,{msg:Locale.getText("msg_obteniendo_metadatos")+" ..."});var summary=null;try{myMask.show();summary=CSWMgr.getRecordsSummary(this.url,what_search,category,provider,bbox);myMask.hide();}catch(e){UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_error_obtener_sumario_metadatos")+".",Ext.MessageBox.ERROR);return;}
this.store.loadData(summary);}else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_introducir_expresion_busqueda")+".",Ext.MessageBox.ERROR);}};this.getMetadata=function(uuid){var myMask=new Ext.LoadMask(this.containerPanel.body,{msg:Locale.getText("msg_obteniendo_metadato")+" ..."});var metadata=null;try{myMask.show();metadata=CSWMgr.getRecordsById(this.url,uuid);myMask.hide();}
catch(e){this.metadataPanel.collapse();UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_error_obtener_metadato")+" "+e,Ext.MessageBox.ERROR);myMask.hide();return;}
this.showXSLMetadata(metadata);};this.showXSLMetadata=function(metadata){if(!this.xslMetadataString){this.xslMetadataString=this.getXSLString(this.xslMetadataURL);}
IDEOL.infoMetadataWindow.show(metadata,this.xslMetadataString);};this.addLayer=function(uuid){var myMask=new Ext.LoadMask(this.containerPanel.body,{msg:Locale.getText("msg_obteniendo_recursos_wms")+" ..."});var resources=null;try{myMask.show();resources=CSWMgr.getResources(this.url,uuid);myMask.hide();}catch(e){UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_error_obtener_metadato")+" "+e,Ext.MessageBox.ERROR);myMask.hide();return;}
for(var i=0;i<resources.length;i++){if(resources[0].protocol=='OGC:WMS-1.1.1-http-get-map'){var layerid=resources[0].name+'-'+i;var layer=this.createLayerWMS(layerid,resources[0].url,resources[0].name);IDEOL.toc.addLayer(layer);}}};this.createLayerWMS=function(id,url,layername){var layeroptions={buffer:0,isBaseLayer:false,singleTile:true,displayInLayerSwitcher:true};var layer=new OpenLayers.Layer.WMS(id,url,{LAYERS:layername,TRANSPARENT:'TRUE',FORMAT:'image/png'},layeroptions);return layer;};this.getXSLString=function(url){var request=OpenLayers.Request.GET({url:url,async:false});return request.responseText;};}
ContextCollectionPanel=Ext.extend(Ext.Panel,{title:Locale.getText("txt_mapas"),border:false,collapsed:true,iconCls:'contextCollectionPanel',autoScroll:true,autoHeight:false,wmccText:null,vcreferences:null,selectedNode:null,urlCollection:Config.WMC_COLLECTION_URL,tree:new Ext.tree.TreePanel({id:'treeContextCollectionPanel',autoHeight:true,border:false,collapsible:true,collapsed:false,rootVisible:false,autoScroll:true,bodyStyle:'padding:5px 0 5px 0',root:{text:'Mapas',draggable:false,leaf:false},buttonAlign:'center'}),loadTree:function(references){var root=new Ext.tree.TreeNode({text:Locale.getText("txt_mapas"),allowDrag:false,expanded:true,expandChildNodes:true,allowDrop:false,allowChildren:true,leaf:false,qtip:Locale.getText("txt_mapas")});this.tree.getRootNode().destroy();this.tree.setRootNode(root);for(var i=0;i<references.length;i++){var reference=new Ext.tree.TreeNode({text:references[i].title,url:references[i].url,allowDrag:false,expanded:false,expandChildNodes:false,allowDrop:false,allowChildren:false,leaf:true,iconCls:'mapNode',qtip:references[i].title});root.appendChild(reference);}},loadMap:function(){var selmodel=this.tree.getSelectionModel();var selectedNode=selmodel.getSelectedNode();if(selectedNode){IDEOL.initialize(selectedNode.attributes.url,selectedNode.text);}
else
UtilsUI.showMessageWindow(Locale.getText("txt_error"),Locale.getText("msg_seleccionar_mapa_cargar"),Ext.MessageBox.ERROR);},initComponent:function(){ContextCollectionPanel.superclass.initComponent.call(this);var wmccText=this.getWMCCString(this.urlCollection);var format=new OpenLayers.Format.WMCC();this.vcreferences=format.read(wmccText);this.on('render',function(panel){this.loadTree(this.vcreferences.references);this.add(this.tree);},this);this.tree.on('click',function(node,event){if(this.selectedNode!=node){this.selectedNode=node;IDEOL.initialize(node.attributes.url,node.text);}},this);},getWMCCString:function(contextURL){var request=OpenLayers.Request.GET({url:contextURL,success:function(transport){wmccText=transport.responseText;},failure:function(transport){wmccText=null;},async:false});return wmccText;}});WFSService=function(){this.selectedFeatureIndex;this.map=null;this.layer=null;this.projection=null;this.gridResult=null;this.gridResultLoadMask=null;this.initialize=function(map){this.map=map;};this.comboLayers=new Ext.form.ComboBox({id:'layersCombo',store:new Ext.data.SimpleStore({fields:['layerName'],data:[]}),displayField:'layerName',fieldLabel:Locale.getText("txt_capa"),name:'layersCombo',typeAhead:false,mode:'local',triggerAction:'all',allowBlank:false,emptyText:Locale.getText("msg_seleccionar_capa")+" ...",selectOnFocus:true,editable:false,anchor:'95%',listeners:{render:function(){}}});this.comboLayers.on('beforeselect',function(combo,record,index){if(combo.getValue()!=record.data.layerName){var layerName=record.data.layerName;this.layer=this.getWFSLayerByName(layerName);this.projection=this.layer.projection;this.loadComboAttributes();this.gridQuery.store.removeAll();this.prepareGridResult();}},this);this.comboAttributes=new Ext.form.ComboBox({id:'atributosCombo',store:new Ext.data.SimpleStore({fields:['name'],data:[]}),displayField:'name',fieldLabel:Locale.getText("txt_atributo"),name:'attribute',typeAhead:false,mode:'local',triggerAction:'all',allowBlank:false,selectOnFocus:true,editable:false,anchor:'95%',listeners:{select:function(record){},render:function(){}}});this.comboOperators=new Ext.form.ComboBox({id:'comboOperators',store:new Ext.data.SimpleStore({fields:['operator'],data:[[WFSMgr.queryOperators.IGUAL],[WFSMgr.queryOperators.DISTINTO],[WFSMgr.queryOperators.MAYOR],[WFSMgr.queryOperators.MAYOR_IGUAL],[WFSMgr.queryOperators.MENOR],[WFSMgr.queryOperators.MENOR_IGUAL],[WFSMgr.queryOperators.NULO]]}),displayField:'operator',fieldLabel:Locale.getText("txt_operador"),name:'operator',typeAhead:false,mode:'local',triggerAction:'all',allowBlank:false,selectOnFocus:true,editable:false,anchor:'95%',listeners:{select:function(record){},render:function(){}}});this.comboOperators.on('select',function(combo,record,index){var operator=record.data.operator;if(operator==WFSMgr.queryOperators.NULO)
this.valueTextField.disable();else
this.valueTextField.enable();},this);this.valueTextField=new Ext.form.TextField({xtype:'textfield',fieldLabel:Locale.getText("txt_valor"),id:'value',name:'value',allowBlank:false,enableKeyEvents:true,anchor:'95%'});this.valueTextField.on('keypress',function(object,event){if(event.getCharCode()==event.ENTER)
this.addAttr();},this);this.buttonDelAttr=new Ext.Button({text:'<<',scope:this,handler:function(){this.delAttr();}});this.buttonAddAttr=new Ext.Button({text:'>>',scope:this,handler:function(){this.addAttr();}});this.leftFormPanel=new Ext.Panel({layout:'form',columnWidth:.5,autoHeight:true,border:false,items:[this.comboLayers,this.comboOperators]});this.rightFormPanel=new Ext.Panel({layout:'form',columnWidth:.5,autoHeight:true,border:false,items:[this.comboAttributes,this.valueTextField]});this.containerFormPanel=new Ext.Panel({layout:'column',autoHeight:true,border:false,items:[this.leftFormPanel,this.rightFormPanel]});this.form=new Ext.FormPanel({layout:'fit',columnWidth:.5,frame:true,bodyStyle:'padding:5px 5px 0',height:150,labelAlign:'top',defaultButton:0,items:[this.containerFormPanel],buttons:[this.buttonDelAttr,this.buttonAddAttr]});this.jsonReaderGridQuery=new Ext.data.JsonReader({},['attribute','operator','value']);this.storeGridQuery=new Ext.data.Store({reader:this.jsonReaderGridQuery});this.gridQuery=new Ext.grid.EditorGridPanel({columnWidth:.5,store:this.storeGridQuery,loadMask:true,autoScroll:true,height:150,frame:true,iconCls:'icon-grid',clicksToEdit:2,columns:[{header:Locale.getText("txt_atributo"),width:100,dataIndex:'attribute',sortable:false},{header:Locale.getText("txt_operador"),width:100,dataIndex:'operator',sortable:false},{header:Locale.getText("txt_valor"),width:140,dataIndex:'value',sortable:true,editor:new Ext.form.TextField()}],viewConfig:{forceFit:true},sm:new Ext.grid.RowSelectionModel({singleSelect:true})});this.queryPanel=new Ext.Panel({layout:'column',autoHeight:true,border:false,items:[this.form,this.gridQuery]});this.pagingBar=new Ext.PagingToolbar({pageSize:25,store:new Ext.data.Store({reader:new Ext.data.JsonReader({},[])}),displayInfo:true,displayMsg:'Displaying topics {0} - {1} of {2}',emptyMsg:"No topics to display",items:['-',{pressed:true,enableToggle:true,text:'Show Preview',cls:'x-btn-text-icon details',toggleHandler:function(btn,pressed){var view=this.gridResult.getView();view.showPreview=pressed;view.refresh();}}]});this.gridResult=new Ext.grid.EditorGridPanel({store:new Ext.data.Store({reader:new Ext.data.JsonReader({},[])}),columns:[],view:new Ext.grid.GridView({forceFit:true}),sm:new Ext.grid.RowSelectionModel({singleSelect:false}),autoScroll:true,frame:true,iconCls:'icon-grid',height:175,clicksToEdit:2,bbar:this.paginBar,listeners:{rowclick:function(grid,index,event){this.selectedFeatureIndex=index;},rowdblclick:function(grid,index,event){}}});this.gridResult.on('afteredit',function(){this.getSaveButton().enable();},this);this.resultPanel=new Ext.Panel({layout:'fit',tittle:Locale.getText("txt_resultados"),border:false,items:[this.gridResult]});this.containerPanel=new Ext.Panel({layout:'fit',autoHeight:true,items:[this.queryPanel,this.resultPanel]});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_servicio_wfs"),id:'wfssearchWin',constrainHeader:true,width:675,minWidth:675,autoHeight:true,maximizable:true,resizable:true,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.containerPanel],buttons:[{text:Locale.getText("txt_buscar"),scope:this,handler:function(){this.doQuery();}},{text:Locale.getText("txt_localizar"),scope:this,handler:function(){this.locateFeature();}},{id:'saveFeaturesDataButton2',text:Locale.getText("txt_guardar"),disabled:true,scope:this,handler:function(){this.saveChanges();}},{text:Locale.getText("txt_eliminar"),scope:this,handler:function(){this.deleteFeatures();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.win.on('maximize',function(window){this.resultPanel.setWidth(this.queryPanel.getSize().width);},this);this.win.on('restore',function(window){this.resultPanel.setWidth(this.queryPanel.getSize().width);},this);this.loadComboLayers=function(){this.comboLayers.store.removeAll();var layerNames=this.getWFSLayersName();if(layerNames.length>0){this.comboLayers.store.loadData(layerNames);return true;}
return false;};this.loadComboAttributes=function(){this.comboAttributes.store.removeAll();this.comboAttributes.reset();var attr=WFSMgr.getFeatureAttributes(this.layer);var attributes=[];if(attr.length>0){for(var i=0;i<attr.length;i++){if(attr[i]!='the_geom'){attributes.push([attr[i]])}}
this.comboAttributes.store.loadData(attributes);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_atributos_capa"),Ext.MessageBox.ERROR);}};this.getWFSLayersName=function(){var layers=this.map.layers;var layerNames=[];for(var i=0;i<layers.length;i++){if(layers[i]instanceof OpenLayers.Layer.WFS)
layerNames.push([layers[i].name]);}
return layerNames;};this.getWFSLayerByName=function(layerName){var layers=this.map.layers;for(var i=0;i<layers.length;i++){if(layers[i]instanceof OpenLayers.Layer.WFS&&layers[i].name==layerName)
return layers[i];}
return null;};this.addAttr=function(){if(this.form.getForm().isValid()){values=this.form.getForm().getValues();var data=new Object();data.attribute=values.attribute;data.operator=values.operator;if(data.operator!=WFSMgr.queryOperators.NULO)
data.value=values.value;else
data.value="-";this.gridQuery.store.loadData([data],true);}};this.delAttr=function(){var selectionModel=this.gridQuery.getSelectionModel();var record=selectionModel.getSelected();if(record)
this.gridQuery.store.remove(record);};this.getAttributesQuery=function(){var store=this.gridQuery.store;var records=store.getRange(0,store.getTotalCount());var attr=[];for(var i=0;i<records.length;i++){attr.push({name:records[i].data.attribute,header:'Tema',value:"*"+records[i].data.value+"*",operator:records[i].data.operator});}
return attr;};this.locateFeature=function(){var selectionModel=this.gridResult.getSelectionModel();var record=selectionModel.getSelected();if(record){var geometryWKT=record.get("geometry");var WKTFormat=new OpenLayers.Format.WKT();var feature=WKTFormat.read(geometryWKT);var bounds=feature.geometry.getBounds();var lonlat=bounds.getCenterLonLat();IDEOL.layersMgr.drawMarker(lonlat,this.projection.getCode(),true,true);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elemento_localizar"),Ext.MessageBox.WARNING);}};this.doQuery=function(){var attr=this.getAttributesQuery();if(attr.length>0){this.gridResult.store.removeAll();this.gridResultLoadMask.show();var features=WFSMgr.getFeaturesQuery(this.layer,attr,null,'GML2');if(features.length>0){this.gridResult.store.loadData(features);}
else{}
this.gridResultLoadMask.hide();}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_anyadir_atributo_filtro"),Ext.MessageBox.WARNING);}};this.getSaveButton=function(){return Ext.getCmp('saveFeaturesDataButton2');};this.getDescribeFeatureData=function(describeFeature){var data=[];data.push('fid');for(var i=0;i<describeFeature.length;i++){if(describeFeature[i].name!="the_geom"&&describeFeature[i].name!="geometry")
data.push('data.'+describeFeature[i].name);}
data.push('geometry');return data;};this.prepareGridResult=function(){this.gridResultLoadMask.show();var describeFeature=WFSMgr.getDescribeFeature(this.layer);var describeFeatureData=this.getDescribeFeatureData(describeFeature);var store=this.getStoreResult(describeFeatureData);var columnModel=this.getColumnModelResult(describeFeatureData);this.gridResult.store.removeAll();this.gridResult.reconfigure(store,columnModel);this.gridResultLoadMask.hide();};this.resetGridResult=function(){var store=new Ext.data.Store({reader:new Ext.data.JsonReader({},[])});var columnModel=new Ext.grid.ColumnModel({columns:[]});this.gridResult.store.removeAll();this.gridResult.reconfigure(store,columnModel);};this.getStoreResult=function(describeFeatureData){var jsonReader=new Ext.data.JsonReader({},describeFeatureData);var store=new Ext.data.Store({reader:jsonReader});return store;};this.getColumnModelResult=function(describeFeatureData){var columns=[];for(var i=0;i<describeFeatureData.length;i++){var dataHeaderTitle=describeFeatureData[i].split(".")[1];if(describeFeatureData[i]=='fid')
columns.push({header:'Fid',dataIndex:describeFeatureData[i],sortable:true,hidden:true});else if(describeFeatureData[i]=='geometry')
columns.push({header:'Geometry',dataIndex:describeFeatureData[i],sortable:true,hidden:true});else
columns.push({header:dataHeaderTitle,dataIndex:describeFeatureData[i],sortable:true,editor:new Ext.form.TextField()});}
var columnModel=new Ext.grid.ColumnModel({columns:columns});return columnModel;};this.getFeatureFromRecord=function(record){var feature=new OpenLayers.Feature();feature.fid=record.data.fid;feature.geometry=record.data.geometry;feature.attributes=new Object();for(key in record.data){if(key!='fid'&&key!='geometry'){validKey=key.split(".");feature.data[validKey[1]]=record.data[key];feature.attributes[validKey[1]]=record.data[key];}}
return feature;};this.getModifiedFeatures=function(){var records=this.gridResult.getStore().getModifiedRecords();var features=[];for(var i=0;i<records.length;i++){var feature=this.getFeatureFromRecord(records[i]);feature.state=OpenLayers.State.UPDATE;features.push(feature);}
return features;};this.saveChanges=function(){var features=this.getModifiedFeatures();if(features.length>0){WFSMgr.updateFeatures(this.layer,features);this.getSaveButton().disable();this.gridResult.store.commitChanges();}};this.resetUI=function(){this.form.getForm().reset();this.gridQuery.store.removeAll();this.resetGridResult();};this.deleteFeatures=function(){var selectionModel=this.gridResult.getSelectionModel();var records=selectionModel.getSelections();if(records.length>0){Ext.MessageBox.confirm(Locale.getText("txt_confirmacion"),Locale.getText("msg_eliminar_geometrias_seleccionadas?"),function(button){var confirm=false;if(button=="yes")
confirm=true;if(confirm){var features=[];for(var i=0;i<records.length;i++){if(records[i]){var fid=records[i].get("fid");var feature=new OpenLayers.Feature.Vector();feature.fid=fid;feature.state=OpenLayers.State.DELETE;features.push(feature);}}
WFSMgr.updateFeatures(this.layer,features);this.doQuery();}},this);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_elementos_eliminar"),Ext.MessageBox.WARNING);}};this.show=function(){if(!this.win.isVisible()){this.resetUI();if(this.loadComboLayers()){this.win.show();this.gridResultLoadMask=new Ext.LoadMask(this.gridResult.body);this.valueTextField.focus('',10);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_sin_capas_wfs_mapa"),Ext.MessageBox.WARNING);}}
else{this.win.expand(true);}};};WMSService=function(){this.map;this.capabilities=null;this.servers=[['Catastro','http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx'],['IDEE','http://www.idee.es/wms/IDEE-Base/IDEE-Base'],['PNOA','http://www.idee.es/wms/PNOA/PNOA'],['IDE Canarias - OrtoExpress','http://idecan1.grafcan.es/ServicioWMS/OrtoExpress'],['IDE Canarias - OrtoExpress Urbana','http://idecan1.grafcan.es/ServicioWMS/OrtoUrb'],['IDE Canarias - Red Geodésica','http://idecan2.grafcan.es/ServicioWMS/RedGeodesica'],['IDE Canarias - Fototeca','http://idecan2.grafcan.es/ServicioWMS/Fototeca'],['IDE Canarias - Mapa Topográfico 1:5.000','http://idecan2.grafcan.es/ServicioWMS/carto5'],['IDE Canarias - Callejero','http://idecan2.grafcan.es/ServicioWMS/Callejero'],['IDE Canarias - Modelo de Sombras','http://idecan1.grafcan.es/ServicioWMS/MDSombras'],['IDE Canarias - Planeamiento Urbanístico','http://idecan2.grafcan.es/ServicioWMS/Planeamiento'],['IDE Canarias - Mapa de Ocupación de Suelo','http://idecan2.grafcan.es/ServicioWMS/MOS'],['IDE Canarias - Mapa de Vegetación','http://idecan2.grafcan.es/ServicioWMS/Vegetacion'],['IDE Canarias - Mapa de Cultivos','http://idecan2.grafcan.es/ServicioWMS/Cultivos'],['IDE Canarias - Mapa Geológico','http://idecan2.grafcan.es/ServicioWMS/Geologico'],['IDE Canarias - Espacios Naturales Protegidos','http://idecan2.grafcan.es/ServicioWMS/EspNat'],['IDE Canarias - Lugares de Importancia Comunitaria','http://idecan2.grafcan.es/ServicioWMS/LIC'],['IDE Canarias - Zonas de Especial Protección para las Aves','http://idecan2.grafcan.es/ServicioWMS/ZEPA'],['IDE Canarias - Ortofoto 1:5.000 Año 2004 - 2006','http://idecan1.grafcan.es/ServicioWMS/OrtoProd'],['IDE Canarias - OrtoExpress Año 1990','http://idecan1.grafcan.es/ServicioWMS/Historico/Ortofotos/OrtoExpress_1990'],['IDE Canarias - Distribuidor de Ortofoto Urbana Año 2007','http://idecan1.grafcan.es/ServicioWMS/DistOrto2000'],['IDE Canarias - Distribuidor de OrtoExpress Urbana','http://idecan1.grafcan.es/ServicioWMS/DistOrtoUrb'],['IDE Canarias - Fincas Registrales','http://idecan.grafcan.com/ServicioWMS/FincasRegEsp']];this.initialize=function(mapOL){this.map=mapOL;};this.store=new Ext.data.SimpleStore({fields:['abbr','url'],data:this.servers});this.comboWMSServers=new Ext.form.ComboBox({store:this.store,id:'comboWMSServers',vtype:'url',width:290,fieldLabel:Locale.getText("txt_servidor"),displayField:'abbr',valueField:'url',typeAhead:true,mode:'local',triggerAction:'all',allowBlank:false,emptyText:Locale.getText("msg_seleccionar_servicio"),selectOnFocus:true,enableKeyEvents:true,listeners:{}});this.comboWMSServers.on('expand',function(comboBox){this.comboWMSServers.list.setWidth('auto');this.comboWMSServers.innerList.setWidth('auto');},this);this.comboWMSServers.on('beforeselect',function(combo,record,index){combo.setRawValue(record.data[combo.valueField]);combo.collapse();this.connect();return false;},this);this.comboWMSServers.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.keyEventHandler=function(object,event){if(event.getCharCode()==event.ENTER)
this.connect();};this.form=new Ext.FormPanel({labelWidth:55,frame:true,bodyStyle:'padding:10px 5px 0',autoHeight:true,items:[this.comboWMSServers],buttons:[{text:Locale.getText("txt_conectar"),id:'connectButtonWMSService',scope:this,handler:function(){this.connect();}}]});this.mask=null;this.tree=new Ext.tree.TreePanel({id:'treeWMSService',animate:true,height:220,hidden:false,border:false,collapsible:true,collapsed:false,rootVisible:true,autoScroll:true,selModel:new Ext.tree.MultiSelectionModel(),root:{text:Locale.getText("txt_servicios"),draggable:false,leaf:true}});this.win=new Ext.Window({layout:'fit',bodyStyle:'padding: 2px 2px 2px',modal:false,title:Locale.getText("txt_servicios_wms"),titleCollapse:true,id:'wmsServiceWin',constrainHeader:true,width:400,autoHeight:true,resizable:false,draggable:true,collapsible:true,closeAction:"hide",plain:true,border:false,items:[this.form,this.tree],buttons:[{text:Locale.getText("txt_anyadir"),scope:this,handler:function(){this.addLayers();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}]});this.getConnectButton=function(){return Ext.getCmp('connectButtonWMSService');};this.show=function(){if(!this.win.isVisible()){this.win.show();this.mask=new Ext.LoadMask(this.tree.body,{msg:Locale.getText("msg_obteniendo_datos")+" ..."});}
else{this.win.expand(true);}};this.connect=function(){if(this.form.getForm().isValid()){var url=this.comboWMSServers.getRawValue().trim();if(url){this.getConnectButton().disable();this.mask.show();this.loadCapabilitiesWMSTree(url);this.mask.hide();this.getConnectButton().enable();}}};this.addLayers=function(){var selmodel=this.tree.getSelectionModel();var selected_nodes=selmodel.getSelectedNodes();if(selected_nodes.length>0){var rootNode=this.tree.getRootNode();var rootNodeLayerinfo=rootNode.attributes.layerinfo;var rootValid=WMSMgr.isValidSRS(rootNodeLayerinfo,this.map.projection.projCode);for(var i=0;i<selected_nodes.length;i++){var layerinfo=selected_nodes[i].attributes.layerinfo;var layerValid=WMSMgr.isValidSRS(layerinfo,this.map.projection.projCode);if(rootValid||layerValid){layerinfo.capabilities=this.capabilities;var layer=this.createLayer(layerinfo,this.map.displayProjection.projCode)
if(layer){IDEOL.toc.addLayer(layer);}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_servidor_wms_no_soporta_proyeccion_mapa")+" '"+layerinfo.title+"'",Ext.MessageBox.ERROR);}}
this.tree.getSelectionModel().clearSelections();}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_seleccionar_capas_anyadir"),Ext.MessageBox.WARNING);}};this.createLayer=function(layerInfo,srs){var wmsFormat=new OpenLayers.Format.WMS();var newlayer=wmsFormat.createLayer(layerInfo);if(newlayer){newlayer.projection=new OpenLayers.Projection(srs);newlayer.visibility=true;return newlayer;}
return null;};this.loadCapabilitiesWMSTree=function(url){this.capabilities=WMSMgr.getCapabilities(url);if(this.capabilities){this.mask.hide();this.getConnectButton().enable();var nodes=this.createNodes(this.capabilities);this.loadTree(nodes);this.tree.setVisible(true);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_obtener_documento_capabilities"),Ext.MessageBox.ERROR);}};this.loadTree=function(nodes){var rootNode=this.tree.getRootNode();rootNode.destroy();this.tree.setRootNode(nodes);this.tree.getRootNode().render();this.tree.render();};this.createNodes=function(capabilities){var layersRootNode=capabilities.layers[0];var rootname=layersRootNode.title;var root=new Ext.tree.TreeNode({text:rootname,layerinfo:layersRootNode,allowDrag:false,expanded:true,expandChildNodes:true,allowDrop:false,allowChildren:true,leaf:false,qtip:layersRootNode.description?layersRootNode.description:capabilities.description});var layersNode=layersRootNode.layers;if(layersNode){for(var i=0;i<layersNode.length;i++){if(layersNode[i].layers){var layerNodeDescription='';if(capabilities.description)
layerNodeDescription=capabilities.description;else if(layersRootNode.description)
layerNodeDescription=layersRootNode.description
var newnode=new Ext.tree.TreeNode({text:layersNode[i].title,layerinfo:layersNode[i],expandChildNodes:true,allowChildren:true,leaf:false,iconCls:'groupNode',qtip:layersNode[i].description?layersNode[i].description:layersNode[i].title});for(var j=0;j<layersNode[i].layers.length;j++){auxnode=new Ext.tree.TreeNode({text:layersNode[i].layers[j].title,layerinfo:layersNode[i].layers[j],leaf:true,iconCls:'layerNode',qtip:layersNode[i].layers[j].description?layersNode[i].layers[j].description:layersNode[i].layers[j].title});newnode.appendChild(auxnode);}
root.appendChild(newnode);}else{var attributes={text:layersNode[i].title,layerinfo:layersNode[i],leaf:true,iconCls:'layerNode',qtip:layersNode[i].description?layersNode[i].description:layersNode[i].title};var node=new Ext.tree.TreeNode(attributes);root.appendChild(node);}}}
return root;};this.deleteAllTreeNodes=function(){var rootnode=this.tree.getRootNode();while(rootnode.firstChild){var c=rootnode.firstChild;rootnode.removeChild(c);c.destroy();}};};Incidencias=function(){this.layer=new OpenLayers.Layer.WFS("Incidencias","http://www.mapasdelapalma.es/geoserver/wfs",{typename:'cabildo:incidencias'},{typename:"incidencias",featureNS:"http://cabildo.iver.es",projection:"EPSG:32628",extractAttributes:true,isBaseLayer:false,visibility:false,displayInLayerSwitcher:false,scope:this,commitSuccess:function(response){this.scope.onCommitSuccess(response);},commitFailure:function(response){this.scope.onCommitFailure(response);}});this.lonlat=null;this.storeCategorias=new Ext.data.SimpleStore({fields:['codigo','categoria'],data:[['1','Barreras Arquitectónicas'],['2','Aceras o carreteras'],['3','Contenedores y papeleras'],['4','Señalización horizontal y vertical'],['5','Jardines'],['6','Coches abandonados'],['7','Solares sin limpiar'],['8','Planeamiento'],['9','Ambiental'],['10','Otras']]}),this.comboCategorias=new Ext.form.ComboBox({store:this.storeCategorias,displayField:'categoria',fieldLabel:Locale.getText("txt_categoria"),name:'categoria',typeAhead:true,triggerAction:'all',allowBlank:false,disabled:false,mode:'local',selectOnFocus:true,editable:false,anchor:'95%'});this.comboCategorias.on('select',function(comboBox,record,index){var record=comboBox.store.getAt(index);this.selectedIdCategoria=record.data.codigo;},this);this.keyEventHandler=function(object,event){if(event.getCharCode()==event.ENTER){this.enviarIncidencia();}};this.fechaDateField=new Ext.form.DateField({fieldLabel:Locale.getText("txt_fecha"),value:new Date().dateFormat('d/m/Y'),format:'d/m/Y',name:'fecha',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.fechaDateField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.descripcionField=new Ext.form.TextArea({fieldLabel:Locale.getText("txt_descripcion"),name:'descripcion',grow:true,allowBlank:false,enableKeyEvents:true,anchor:'95%'});this.descripcionField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.nombreTextField=new Ext.form.TextField({fieldLabel:Locale.getText("txt_nombre"),name:'nombre',allowBlank:false,enableKeyEvents:true,anchor:'95%'});this.nombreTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.telefonoTextField=new Ext.form.NumberField({fieldLabel:Locale.getText("txt_telefono"),name:'telefono',allowBlank:true,allowDecimals:false,allowNegative:false,maxLength:12,enableKeyEvents:true,anchor:'95%'});this.telefonoTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.emailTextField=new Ext.form.TextField({fieldLabel:Locale.getText("txt_email"),name:'email',allowBlank:true,enableKeyEvents:true,anchor:'95%'});this.emailTextField.on('keypress',function(object,event){this.keyEventHandler(object,event);},this);this.form=new Ext.form.FormPanel({labelWidth:80,frame:true,autoHeight:true,bodyStyle:'padding:5px 5px 0',defaultButton:0,items:[this.comboCategorias,this.descripcionField,this.fechaDateField,this.nombreTextField,this.telefonoTextField,this.emailTextField]});this.win=new Ext.Window({constrainHeader:true,collapsible:true,resizable:true,maximizable:false,layout:'fit',title:Locale.getText("txt_incidencias"),titleCollapse:true,width:350,minWidth:350,maxWidth:400,autoHeight:true,closeAction:'hide',plain:true,buttons:[{text:Locale.getText("txt_enviar"),scope:this,handler:function(){this.enviarIncidencia();}},{text:Locale.getText("txt_cerrar"),scope:this,handler:function(){this.win.hide();}}],items:[this.form]});this.show=function(lonlat){this.lonlat=lonlat;this.form.getForm().reset();this.win.show();this.win.expand();};this.enviarIncidencia=function(){if(this.form.getForm().isValid()){var descripcion=this.descripcionField.getValue();var myDate=Date.parseDate(this.fechaDateField.value,'d/m/Y');var day=(myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();var monthInt=parseInt(myDate.getMonth(),10)+1;var month=(monthInt<10)?"0"+monthInt:monthInt;var year=myDate.getFullYear();var finalDate=year+'-'+month+'-'+day;var nombre=this.nombreTextField.getValue();var telefono=this.telefonoTextField.getValue();var email=this.emailTextField.getValue();var point=new OpenLayers.Geometry.Point(this.lonlat.lon,this.lonlat.lat);var feature=new OpenLayers.Feature.Vector(point);feature.attributes.fecha_deteccion=finalDate;feature.attributes.nombre=nombre;feature.attributes.descripcion=descripcion;feature.attributes.telefono=telefono;feature.attributes.email=email;feature.attributes.categoria=this.selectedIdCategoria;feature.attributes.estado=1;feature.state=OpenLayers.State.INSERT;this.layer.addFeatures([feature]);this.layer.commit();}};this.onCommitSuccess=function(response){if(response.responseText.indexOf('ServiceException')>=0||response.responseText.indexOf('wfs:FAILED')>=0){UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_realizar_transaccion_incidencia"),Ext.MessageBox.ERROR);}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_transaccion_incidencia_ok"),Ext.MessageBox.INFO);}
this.layer.destroyFeatures();this.win.hide();};this.onCommitFailure=function(response){this.layer.destroyFeatures();UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_realizar_transaccion_incidencia"),Ext.MessageBox.ERROR);};};Styles=OpenLayers.Class({defaultStyleMap:new OpenLayers.StyleMap({"default":new OpenLayers.Style({pointRadius:5,fillColor:"#006fec",fillOpacity:0.3,strokeColor:"#006fec",strokeWidth:2}),"select":new OpenLayers.Style({fillColor:"#66ccff",strokeColor:"red"})}),drawSymbolizers:{"Point":{pointRadius:4,graphicName:"square",fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"#006fec",fillOpacity:0.6},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"#006fec"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#006fec",fillColor:"#006fec",fillOpacity:0.2}},drawStyle:null,drawStyleMap:null,measureSymbolizers:{"Point":{pointRadius:4,graphicName:"square",fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"#fbfe25"},"Line":{strokeWidth:2,strokeOpacity:1,strokeColor:"#fbfe25"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#fbfe25",fillColor:"#fbfe25",fillOpacity:0.4}},measureStyle:null,measureStyleMap:null,vectorDefaultSymbolizers:{"Point":{pointRadius:6,fillColor:"white",fillOpacity:0.6,strokeWidth:2,strokeColor:"#006fec"},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"#006fec"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#006fec",fillColor:"#006fec",fillOpacity:0.6}},vectorSelectSymbolizers:{"Point":{pointRadius:6,fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"yellow"},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"yellow"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"yellow",fillColor:"yellow",fillOpacity:0.6}},vectorDeleteSymbolizers:{"Point":{pointRadius:6,fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"red",fillOpacity:0.6},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"red"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"red",fillColor:"red",fillOpacity:0.6}},vectorInsertSymbolizers:{"Point":{pointRadius:6,fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"#32ec06",fillOpacity:0.6},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"#32ec06"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#32ec06",fillColor:"green",fillOpacity:0.6}},vectorUpdateSymbolizers:{"Point":{pointRadius:6,fillColor:"white",fillOpacity:0.8,strokeWidth:2,strokeColor:"yellow",fillOpacity:0.6},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"yellow"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"yellow",fillColor:"yellow",fillOpacity:0.6}},vectorStyleMap:null,initialize:function(){this.initializeDrawStyle();this.initializeMeasureStyle();this.initializeVectorStyle();},initializeDrawStyle:function(){this.drawStyle=new OpenLayers.Style();this.drawStyle.addRules([new OpenLayers.Rule({symbolizer:this.drawSymbolizers})]);this.drawStyleMap=new OpenLayers.StyleMap({"default":this.drawStyle});},initializeMeasureStyle:function(){this.measureStyle=new OpenLayers.Style();this.measureStyle.addRules([new OpenLayers.Rule({symbolizer:this.measureSymbolizers})]);this.measureStyleMap=new OpenLayers.StyleMap({"default":this.measureStyle});},initializeVectorStyle:function(){var vectorDefaultStyle=new OpenLayers.Style();vectorDefaultStyle.addRules([new OpenLayers.Rule({symbolizer:this.vectorDefaultSymbolizers})]);var vectorSelectStyle=new OpenLayers.Style();vectorSelectStyle.addRules([new OpenLayers.Rule({symbolizer:this.vectorSelectSymbolizers})]);var vectorDeleteStyle=new OpenLayers.Style();vectorDeleteStyle.addRules([new OpenLayers.Rule({symbolizer:this.vectorDeleteSymbolizers})]);var vectorInsertStyle=new OpenLayers.Style();vectorInsertStyle.addRules([new OpenLayers.Rule({symbolizer:this.vectorInsertSymbolizers})]);var vectorUpdateStyle=new OpenLayers.Style();vectorUpdateStyle.addRules([new OpenLayers.Rule({symbolizer:this.vectorUpdateSymbolizers})]);this.vectorStyleMap=new OpenLayers.StyleMap({"default":vectorDefaultStyle,"select":vectorSelectStyle,"delete":vectorDeleteStyle,"insert":vectorInsertStyle,"update":vectorUpdateStyle});},CLASS_NAME:"Styles"});Tools={callejeroClient:new CallejeroClient(),catastroClient:new CatastroClient(),toponimosClient:new ToponimosPanel(),moveToLonLatPanel:new MoveToLonLatPanel()};IDEOL={mapMgr:new MapMgr(),layersMgr:null,controlsMgr:null,editionMgr:null,styles:new Styles(),toc:new Toc(),cswClient:new CSWClient(),wfsService:new WFSService(),infoWMSWindow:new InfoWMSWindow(),infoXSLWMSWindow:new InfoXSLWMSWindow(),infoWFSWindow:new InfoWFSWindow(),infoLinksWindow:new InfoLinksWindow(),infoImagesWindow:new InfoImagesWindow(),uploadFileWindow:new UploadFileWindow(),saveFileWindow:new SaveFileWindow(),wmsService:new WMSService(),infoMetadataWindow:new InfoMetadataWindow(),streetViewWindow:new StreetViewWindow(),incidencias:new Incidencias(),helpWindow:new HelpWindow(),initialize:function(contextURL,title,projCode){Layout.statusBar.showBusy(Locale.getText("msg_inicializando_mapa")+" ...");OpenLayers.ProxyHost=Config.ProxyHost;if(contextURL==null)
contextURL=Config.WMC_URL;if(title==null)
title=Locale.getText("txt_capas");if(WMCMgr.isValidWMC(contextURL)){this.mapMgr.map=WMCMgr.createWMCMap(this.mapMgr.map,contextURL,'mapOL',projCode);this.controlsMgr=new ControlsMgr(this.mapMgr.map,this.styles);WFSLayers.initialize();this.layersMgr=new LayersMgr(this.mapMgr.map,this.styles);this.editionMgr=new EditionMgr(this.mapMgr.map,this.layersMgr.defaultVector,this.styles.vectorStyleMap);this.toc.initialize('tocOL',this.mapMgr.map,title);this.infoWFSWindow.initialize(this.mapMgr.map);this.infoWMSWindow.initialize(this.mapMgr.map);this.saveFileWindow.initialize(this.mapMgr.map);this.wfsService.initialize(this.mapMgr.map);this.wmsService.initialize(this.mapMgr.map);Login.initialize();Layout.workLayerCombo.loadLayers(this.mapMgr.map);if(Layout.workLayerCombo.view)
Layout.workLayerCombo.setValue(this.layersMgr.defaultVector.name);if(this.mapMgr.map.getProjection()=='EPSG:900913'){Layout.projectionCombo.setDisabled(true);}
else{Layout.projectionCombo.setDisabled(false);Layout.projectionCombo.setRawValue(this.mapMgr.map.getProjection());}}
else{UtilsUI.showMessageWindow(Locale.getText("txt_informacion"),Locale.getText("msg_error_iniciar_mapa_contexto")+" '"+title+"'",Ext.MessageBox.ERROR);}
Layout.statusBar.clearStatus({useDefaults:true});}};Layout={workLayerCombo:null,projectionCombo:null,toolBar:new ToolBar(),toolBarPanel:null,menuBar:new MenuBar(),statusBar:new StatusBar(),viewport:null,northPanel:new Ext.Panel({region:'north',border:false,contentEl:'header'}),footerPanel:new Ext.Panel({region:'south',border:false,height:35,frame:true}),overViewMapPanel:new Ext.Panel({title:Locale.getText("txt_localizador"),autoHeight:true,border:false,collapsible:true,collapsed:true,contentEl:'overViewMapPanel'}),westPanel:new Ext.Panel({region:'west',title:Locale.getText("Capas"),id:'westPanel',split:true,autoScroll:true,layout:'fit',collapsible:false,frame:true,border:false,width:230,minSize:230,maxSize:300,listeners:{collapse:{fn:function(){setTimeout("IDEOL.mapMgr.map.updateSize();",100)}},expand:{fn:function(){setTimeout("IDEOL.mapMgr.map.updateSize();",100)}}}}),westPanelBasic:new Ext.Panel({region:'west',id:'westPanel',title:'West',split:true,width:200,minSize:175,maxSize:400,collapsible:true,margins:'0 0 0 5',layout:'accordion',layoutConfig:{animate:true},items:[{title:'Navigation',border:false,iconCls:'nav'},{title:'Settings',html:'<p>Some settings in here.</p>',border:false,iconCls:'settings'}]}),eastPanel:new Ext.Panel({id:'eastPanel',region:'east',boder:false,width:250,minWidth:225,maxWidth:300,layout:'fit',split:true,collapsible:true,collapseMode:'mini',collapsed:false,frame:true,border:false,plain:true,layout:'accordion',layoutConfig:{animate:true},listeners:{collapse:{fn:function(){setTimeout("IDEOL.mapMgr.map.updateSize();",100)}},expand:{fn:function(){setTimeout("IDEOL.mapMgr.map.updateSize();",100)}}}}),tabPanel:null,mapPanel:null,mapPanelMask:null,containerEastPanel:null,containerMapPanel:null,postInitialize:function(){IDEOL.initialize();this.eastPanel.add(this.overViewMapPanel);this.eastPanel.add(IDEOL.toc.tree);this.eastPanel.add(new ContextCollectionPanel());var tools=Tools;for(key in tools){this.eastPanel.add(tools[key]);}
this.eastPanel.doLayout();IDEOL.mapMgr.refreshMap();},showAdminFrame:function(){var frame=Ext.getCmp('adminFrame');this.tabPanel.add({title:Locale.getText("txt_administracion"),id:'adminFrame',defaultSrc:Config.ADMIN_URL,loadMask:{hideOnReady:true,msg:'Loading Site...'},closable:false,border:false,autoScroll:true,hidden:true,listeners:{documentloaded:function(){}}});},hideAdminFrame:function(){var frame=Ext.getCmp('adminFrame');this.tabPanel.remove(frame);},initialize:function(){Ext.QuickTips.init();Ext.BLANK_IMAGE_URL='ide/images/blank.gif';this.overViewMapPanel.on('resize',function(){var ovmapControl=IDEOL.controlsMgr.controls.overViewMap;if(ovmapControl!=null&&ovmapControl.ovmap!=null)
ovmapControl.ovmap.updateSize();},this);this.mapPanel=new Ext.Panel({region:'center',contentEl:'mapOL',border:false,bbar:this.statusBar});this.toolBarPanel=new Ext.Panel({region:'north',tbar:this.toolBar});this.containerMapPanel=new Ext.Panel({title:Locale.getText("txt_mapa"),layout:'border',id:'containerMapPanel',border:false,closable:false,items:[this.toolBarPanel,this.mapPanel,this.eastPanel]});this.tabPanel=new Ext.TabPanel({id:'centerTabPanel',deferredRender:false,region:'center',activeTab:0,border:false,defaultType:"iframepanel",items:[this.containerMapPanel]});this.viewport=new Ext.Viewport({layout:'border',autoHeight:true,autoScroll:true,loadMask:'Loading',bufferResize:300,items:[this.northPanel,this.tabPanel,this.footerPanel]});this.mapPanelMask=new Ext.LoadMask(this.mapPanel.body,{msg:"Loading ..."});this.workLayerCombo=Ext.getCmp('workLayerCombo');this.projectionCombo=Ext.getCmp('projectionCombo');setTimeout("Layout.postInitialize();",1500);}};

