/**
 * Camigolo
 *  
 * @category   Javascript
 * @package    script
 * @copyright  Copyright (c) 2008 OnlineShop Consulting AG (http://www.oscag.de)
 * @author     Andreas Eckersperger (andreas.eckersperger@oscag.de)
 * 
 * @version    $Id: core.js 688 2008-06-18 07:12:46Z andreas.eckersperger $
 */

/*
 * jQuery 1.2.3 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $
 * $Rev: 4663 $
 */
(function(){if(window.jQuery)var _jQuery=window.jQuery;var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$)var _$=window.$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem)if(elem.id!=match[3])return jQuery().find(selector);else{this[0]=elem;this.length=1;return this;}else
selector=[];}}else
return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.3",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem)ret=i;});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],name)||undefined;else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return!selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length)data=jQuery.data(this[0],key);return data==null&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==1){target=this;i=0;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){if(target===options[name])continue;if(deep&&options[name]&&typeof options[name]=="object"&&target[name]&&!options[name].nodeType)target[name]=jQuery.extend(target[name],options[name]);else if(options[name]!=undefined)target[name]=options[name];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,windowData={};var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.appendChild(script);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){if(args){if(object.length==undefined){for(var name in object)if(callback.apply(object[name],args)===false)break;}else
for(var i=0,length=object.length;i<length;i++)if(callback.apply(object[i],args)===false)break;}else{if(object.length==undefined){for(var name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var i=0,length=object.length,value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&elem.style&&elem.style[name])ret=elem.style[name];else if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem))ret=getComputedStyle.getPropertyValue(name);else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(getComputedStyle&&getComputedStyle.getPropertyValue(name))||"";for(var i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left,runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem=elem.toString();if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(typeof array!="array")for(var i=0,length=array.length;i<length;i++)ret.push(array[i]);else
ret=array.slice(0);return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]==elem)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else
for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv&&callback(elems[i],i)||inv&&!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!==null&&value!=undefined){if(value.constructor!=Array)value=[value];ret=ret.concat(value);}}return ret;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength",selectedIndex:"selectedIndex",defaultValue:"defaultValue",tagName:"tagName",nodeName:"nodeName"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval!=undefined)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event)data.unshift(this.fix({type:type,target:elem}));data[0].type=type;if(exclusive)data[0].exclusive=true;if(jQuery.isFunction(jQuery.data(elem,"handle")))val=jQuery.data(elem,"handle").apply(elem,data);if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xml;},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(!elem)return undefined;type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=(new Date()).getTime();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&jQuery.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};})();
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);
/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: jquery.lazyload.js 262 2007-10-19 13:56:45Z tuupola $
 *
 */
(function($){$.fn.lazyload=function(options){var settings={threshold:0,failurelimit:0};if(options){$.extend(settings,options);};var elements=this;if(!settings.event){$(window).bind("scroll",function(event){var counter=0;elements.each(function(){if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings)){$(this).attr("src",$(this).attr("original"));this.loaded=true;}else{if(counter++>settings.failurelimit){return false;};}});var temp=$.grep(elements,function(element){return!element.loaded;});elements=$(temp);});};return this.each(function(){var self=this;$(self).attr("original",$(self).attr("src"));if(settings.event||$.belowthefold(self,settings)||$.rightoffold(self,settings)){if(settings.placeholder){$(self).attr("src",settings.placeholder);}else{$(self).removeAttr("src");}
self.loaded=false;}else{self.loaded=true;}
if(settings.event){$(self)[settings.event](function(event){if(!self.loaded){$(self).attr("src",$(self).attr("original"));self.loaded=true;};});};});};$.belowthefold=function(element,settings){var fold=$(window).height()+$(window).scrollTop();return fold<=$(element).offset().top-settings.threshold;}
$.rightoffold=function(element,settings){var fold=$(window).width()+$(window).scrollLeft();return fold<=$(element).offset().left-settings.threshold;}
$.extend($.expr[':'],{belowthefold:"$.belowthefold(a, {threshold : 0})",abovethefold:"!$.belowthefold(a, {threshold : 0})",rightoffold:"$.rightoffold(a, {threshold : 0})",leftoffold:"!$.rightoffold(a, {threshold : 0})"});})(jQuery);
/*
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 1.2
 * Last Modified: 11/21/2007
 * 
 * Copyright 2007 Trent Richardson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
jQuery.extend({ 
    ImpromptuDefaults: { prefix:'jqi', buttons:{ Ok:true }, loaded:function(){}, submit:function(){return true;}, callback:function(){}, container:'body', opacity:0.6, overlayspeed:'slow', promptspeed:'fast', show:'show'},
    SetImpromptuDefaults: function(o){ 
        jQuery.ImpromptuDefaults = jQuery.extend({},jQuery.ImpromptuDefaults,o);
    },
    prompt: function(m,o){
        o = jQuery.extend({},jQuery.ImpromptuDefaults,o);
        
        var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);  
        var b = (ie6)? jQuery(document.body):jQuery(o.container);   
        var fade = '<div class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></div>';
        if((jQuery.browser.msie && jQuery('object, applet').length > 0) || ie6)
            fade = '<iframe src="" class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></iframe>';
        var msgbox = '<div class="'+ o.prefix +'" id="'+ o.prefix +'"><div class="'+ o.prefix +'container"><div class="'+ o.prefix +'message">'+ m +'<div class="'+ o.prefix +'buttons" id="'+ o.prefix +'buttons">';
        jQuery.each(o.buttons,function(k,v){ msgbox += '<button name="'+ o.prefix +'button'+ k +'" id="'+ o.prefix +'button'+ k +'" value="'+ v +'">'+ k +'</button>'}) ;
        msgbox += '</div></div></div></div>';
        
        var jqi = b.prepend(msgbox).children('#'+ o.prefix);
        var jqif = b.prepend(fade).children('#'+ o.prefix +'fade');
        
        //ie6 calculation functions
        var getfoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + 'px'; };
        var getjoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + Math.round(15 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'; };
        var ie6scroll = function(){ jqif.css({ top: getfoffset() }); jqi.css({ top: getjoffset() }); };

        jqif.css({ position: "fixed", height: (ie6)? "100%":$('#background').height(), width: "100%", top: (ie6)? getfoffset():0, left: 0, right: 0, bottom: 0, zIndex: 998, display: "none", opacity: o.opacity });
        jqi.css({ position: (ie6)? "absolute" : "fixed", top: (ie6)? getjoffset():"10%", left: "50%", display: "none", zIndex: 999, marginLeft: ((((jqi.css("paddingLeft").split("px")[0]*1) + jqi.width())/2)*-1) });
            
        jQuery('#'+ o.prefix +'buttons').children('button').click(function(){ 
            var msg = jqi.children('.'+ o.prefix +'container').children('.'+ o.prefix +'message');
            var clicked = o.buttons[jQuery(this).text()];   
            if(o.submit(clicked,msg)){      
                jqi.remove(); 
                if(ie6)jQuery(window).unbind('scroll',ie6scroll);//ie6, remove the scroll event
                jqif.fadeOut(o.overlayspeed,function(){
                    jqif.remove();
                    o.callback(clicked,msg);
                });
            }
        });
                
        if(ie6) jQuery(window).scroll(ie6scroll);//ie6, add a scroll event to fix position:fixed
        jqif.fadeIn(o.overlayspeed);
        jqi[o.show](o.promptspeed,o.loaded);
        return jqi;
    }   
});



/**
 * Camigolo
 * 
 * @category   javascript
 * @package    plugins
 * @copyright  Copyright (c) 2008 OnlineShop Consulting AG (http://www.oscag.de)
 * @author     Andreas Eckersperger (andreas.eckersperger@oscag.de)
 * 
 * @version    $Id$
 */

(function($) {
    $.fn.editable = function(target, options)
    {
        var settings = 
        {
            target     : target,
            name       : 'value',
            id         : 'id',
            type       : 'text',
            width      : '100%',
            height     : '100px',
            event      : 'click',
            onblur     : 'ignore',
            loadtype   : 'POST',
            loadtext   : '...',
            placeholder: 'Zum editieren klicken',
            loaddata   : {},
            submitdata : {}
        };
        
        if (options)
        {
            $.extend(settings, options);
        }
    
        var plugin   = $.editable.types[settings.type].plugin || function() {};
        var submit   = $.editable.types[settings.type].submit || function() {};
        var buttons  = $.editable.types[settings.type].buttons 
                    || $.editable.types['defaults'].buttons;
        var content  = $.editable.types[settings.type].content 
                    || $.editable.types['defaults'].content;
        var element  = $.editable.types[settings.type].element 
                    || $.editable.types['defaults'].element;
        var callback = settings.callback || function() {};
        
        if  (!$.isFunction($(this)[settings.event]))
        {
            $.fn[settings.event] = function(fn)
            {
                return fn ? this.bind(settings.event, fn) : this.trigger(settings.event);
            }
        }
          
        $(this).attr('title', settings.tooltip);
        
        //settings.autowidth  = 'auto' == settings.width;
        //settings.autoheight = 'auto' == settings.height;

        return this.each(function()
        {
            if (!$.trim($(this).html()))
            {
                $(this).html(settings.placeholder);
            }
            
            $(this)[settings.event](function(e)
            {
                var self = this;

                if (self.editing)
                {
                    return;
                }

                if ($(this).html().toLowerCase().replace(/;/, '') == settings.placeholder.toLowerCase().replace(/;/, ''))
                {
                        $(this).html('');
                }
                                
                self.editing    = true;
                self.revert     = $(self).html();
                $(self).html('');

                var form = $('<form/>');

                $(self).append(form);
                
                if (settings.cssclass)
                {
                    if ('inherit' == settings.cssclass)
                    {
                        form.attr('class', $(self).attr('class'));
                    } else
                    {
                        form.attr('class', settings.cssclass);
                    }
                }
        
                if (settings.style)
                {
                    if ('inherit' == settings.style)
                    {
                        form.attr('style', $(self).attr('style'));
                        form.css('display', $(self).css('display'));                
                    } else
                    {
                        form.attr('style', settings.style);
                    }
                }
        
                var input = element.apply(form, [settings, self]);

                var input_content;
                
                if (settings.loadurl)
                {
                    var t = setTimeout(function()
                    {
                        input.disabled = true;
                        content.apply(form, [settings.loadtext, settings, self]);
                    }, 100);

                    var splitlid = self.id.split("_");                        
                    var loaddata = {};
                    loaddata['key']   = splitlid[1];
                    loaddata['group'] = splitlid[2] + '_' + splitlid[0];
                    
                    $(self).parent("a").click(function()
                    {
                        $(this).find('form').submit();
                        return false;
                    });
                    
                    if ($.isFunction(settings.loaddata))
                    {
                        $.extend(loaddata, settings.loaddata.apply(self, [self.revert, settings]));
                    } else
                    {
                        $.extend(loaddata, settings.loaddata);
                    }
                    $.ajax(
                    {
                       type : settings.loadtype,
                       url  : settings.loadurl,
                       data : loaddata,
                       async : false,
                       success: function(result)
                       {
                          window.clearTimeout(t);
                          input_content = result;
                          input.disabled = false;
                       }
                    });
                } else if (settings.data)
                {
                    input_content = settings.data;
                    if ($.isFunction(settings.data))
                    {
                        input_content = settings.data.apply(self, [self.revert, settings]);
                    }
                } else
                {
                    input_content = self.revert; 
                }
                content.apply(form, [input_content, settings, self]);

                input.attr('name', settings.name);
        
                buttons.apply(form, [settings, self]);

                if (settings.select)
                {
                    input.select();
                }

                plugin.apply(form, [settings, self]);

                $(':input:visible:enabled:first', form).focus();
        
                input.keydown(function(e)
                {
                    if (e.keyCode == 27)
                    {
                        e.preventDefault();
                        reset();
                    }
                });

                var t;
                if ('cancel' == settings.onblur)
                {
                    input.blur(function(e) {
                        t = setTimeout(reset, 500);
                    });
                    input.mouseout(function(e) {
                        t = setTimeout(reset, 0);
                    });
                } else if ('submit' == settings.onblur)
                {
                    input.blur(function(e)
                    {
                        form.submit();
                    });
                } else if ($.isFunction(settings.onblur))
                {
                    input.blur(function(e)
                    {
                        settings.onblur.apply(self, [input.val(), settings]);
                    });
                } else
                {
                    input.blur(function(e) {});
                }

                form.submit(function(e)
                {
                    if (t)
                    { 
                        clearTimeout(t);
                    }

                    e.preventDefault(); 
            
                    submit.apply(form, [settings, self]);

                    if ($.isFunction(settings.target))
                    {
                        var str = settings.target.apply(self, [input.val(), settings]);
                        $(self).html(str);
                        self.editing = false;
                        callback.apply(self, [self.innerHTML, settings]);                           
                        if (!$.trim($(self).html()))
                        {
                            $(self).html(settings.placeholder);
                        }
                    } else
                    {
                        var splitid = self.id.split("_");                        
                        var submitdata = {};
                        submitdata['value'] = input.val();
                        submitdata['key']   = splitid[1];
                        submitdata['group'] = splitid[2] + '_' + splitid[0];

                        if ($.isFunction(settings.submitdata))
                        {
                            $.extend(submitdata, settings.submitdata.apply(self, [self.revert, settings]));
                        } else
                        {
                            $.extend(submitdata, settings.submitdata);
                        }          

                        $(self).html(settings.indicator);
                        $.post(settings.target, submitdata, function(str)
                        {
                            $(self).html(str);
                            self.editing = false;
                            callback.apply(self, [self.innerHTML, settings]);
                              
                            if (!$.trim($(self).html()))
                            {
                                $(self).html(settings.placeholder);
                            }
                        });
                    }
                     
                    return false;
                });

                function reset()
                {
                    $(self).html(self.revert);
                    self.editing   = false;
                    if (!$.trim($(self).html()))
                    {
                        $(self).html(settings.placeholder);
                    }
                }
                
                return false;

            });
        });

    };


    $.editable =
    {
        types:
        {
            defaults:
            {
                element : function(settings, original)
                {
                    var input = $('<input type="hidden">');                
                    $(this).append(input);
                    return(input);
                },
                content : function(string, settings, original)
                {
                    $(':input:first', this).val(string);
                },
                buttons : function(settings, original)
                {
                    if (settings.submit)
                    {
                        var submit = $('<input type="submit">');
                        submit.val(settings.submit);
                        $(this).append(submit);
                    }
                    if (settings.cancel)
                    {
                        var cancel = $('<input type="button">');
                        cancel.val(settings.cancel);
                        $(this).append(cancel);

                        $(cancel).click(function()
                        {
                            $(original).html(original.revert);
                            original.editing = false;
                        });
                    }
                }
            },
            text:
            {
                element : function(settings, original)
                {
                    var input = $('<input>');
                    //if (settings.width  != 'none') { input.width(settings.width);  }
                    //if (settings.height != 'none') { input.height(settings.height); }
                    
                    input.attr('class', 'editable');
                    
                    input.attr('autocomplete','off');
                    $(this).append(input);
                    return(input);
                }
            },
            textarea: {
                element : function(settings, original)
                {
                    var textarea = $('<textarea>');
                    if (settings.rows)
                    {
                        textarea.attr('rows', settings.rows);
                    } else
                    {
                        textarea.height(settings.height);
                    }
                    if (settings.cols)
                    {
                        textarea.attr('cols', settings.cols);
                    } else
                    {
                        textarea.width(settings.width);
                    }
                    $(this).append(textarea);
                    return(textarea);
                }
            },
            select:
            {
                element : function(settings, original)
                {
                    var select = $('<select>');
                    $(this).append(select);
                    return(select);
                },
                content : function(string, settings, original)
                {
                    if (String == string.constructor)
                    {      
                        eval ('var json = ' + string);
                        for (var key in json)
                        {
                            if ('selected' == key)
                            {
                                continue;
                            } 
                            var option = $('<option>').val(key).append(json[key]);
                            $('select', this).append(option);    
                        }
                    }
 
                    $('select', this).children().each(function()
                    {
                        if ($(this).val() == json['selected'])
                        {
                            $(this).attr('selected', 'selected');
                        };
                    });
                }
            }
        },

        addInputType: function(name, input)
        {
            $.editable.types[name] = input;
        }
    };

})(jQuery);


jQuery.fn.corner = function(o) {
    function hex2(s) {
        var s = parseInt(s).toString(16);
        return ( s.length < 2 ) ? '0'+s : s;
    };
    function gpc(node) {
        for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode  ) {
            var v = jQuery.css(node,'backgroundColor');
            if ( v.indexOf('rgb') >= 0 ) { 
                rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            if ( v && v != 'transparent' )
                return v;
        }
        return '#ffffff';
    };
    function getW(i) {
        switch(fx) {
        case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
        case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
        case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
        case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
        case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
        case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
        case 'curl':   return Math.round(width*(Math.atan(i)));
        case 'tear':   return Math.round(width*(Math.cos(i)));
        case 'wicked': return Math.round(width*(Math.tan(i)));
        case 'long':   return Math.round(width*(Math.sqrt(i)));
        case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
        case 'dog':    return (i&1) ? (i+1) : width;
        case 'dog2':   return (i&2) ? (i+1) : width;
        case 'dog3':   return (i&3) ? (i+1) : width;
        case 'fray':   return (i%2)*width;
        case 'notch':  return width; 
        case 'bevel':  return i+1;
        }
    };
    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt(jQuery.css(this,'paddingTop'))||0,     R: parseInt(jQuery.css(this,'paddingRight'))||0,
            B: parseInt(jQuery.css(this,'paddingBottom'))||0,  L: parseInt(jQuery.css(this,'paddingLeft'))||0
        };

        if (jQuery.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = jQuery.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
            var d = document.createElement('div');
            var ds = d.style;

            bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

            if (bot && cssHeight != 'auto') {
                if (jQuery.css(this,'position') == 'static')
                    this.style.position = 'relative';
                ds.position = 'absolute';
                ds.bottom = ds.left = ds.padding = ds.margin = '0';
                if (jQuery.browser.msie)
                    ds.setExpression('width', 'this.parentNode.offsetWidth');
                else
                    ds.width = '100%';
            }
            else {
                ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                    (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
            }

            for (var i=0; i < width; i++) {
                var w = Math.max(0,getW(i));
                var e = strip.cloneNode(false);
                e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
            }
        }
    });
};






jQuery.fn.truncate = function( max, settings ) {
    settings = jQuery.extend( {
        chars: /\s/,
        trail: [ "...", "" ]
    }, settings );
    var myResults = {};
    var ie = $.browser.msie;
    function fixIE( o ) {
        if ( ie ) {
            o.style.removeAttribute( "filter" );
        }
    }
    return this.each( function() {
        var $this = jQuery(this);
        var myStrOrig = $this.html().replace( /\r\n/gim, "" );
        var myStr = myStrOrig;
        var myRegEx = /<\/?[^<>]*\/?>/gim;
        var myRegExArray;
        var myRegExHash = {};
        var myResultsKey = $("*").index( this );
        while ( ( myRegExArray = myRegEx.exec( myStr ) ) != null ) {
            myRegExHash[ myRegExArray.index ] = myRegExArray[ 0 ];
        }
        myStr = jQuery.trim( myStr.split( myRegEx ).join( "" ) );
        if ( myStr.length > max ) {
            var c;
            while ( max < myStr.length ) {
                c = myStr.charAt( max );
                if ( c.match( settings.chars ) ) {
                    myStr = myStr.substring( 0, max );
                    break;
                }
                max--;
            }
            if ( myStrOrig.search( myRegEx ) != -1 ) {
                var endCap = 0;
                for ( eachEl in myRegExHash ) {
                    myStr = [ myStr.substring( 0, eachEl ), myRegExHash[ eachEl ], myStr.substring( eachEl, myStr.length ) ].join( "" );
                    if ( eachEl < myStr.length ) {
                        endCap = myStr.length;
                    }
                }
                $this.html( [ myStr.substring( 0, endCap ), myStr.substring( endCap, myStr.length ).replace( /<(\w+)[^>]*>.*<\/\1>/gim, "" ).replace( /<(br|hr|img|input)[^<>]*\/?>/gim, "" ) ].join( "" ) );
            } else {
                $this.html( myStr );
            }
            myResults[ myResultsKey ] = myStrOrig;
            $this.html( [ "<p class='truncate_less'>", $this.html(), settings.trail[ 0 ], "</p>" ].join( "" ) )
            .find(".truncate_show",this).click( function() {
                if ( $this.find( ".truncate_more" ).length == 0 ) {
                    $this.append( [ "<p class='truncate_more' style='display: none;'>", myResults[ myResultsKey ], settings.trail[ 1 ], "</p>" ].join( "" ) )
                    .find( ".truncate_hide" ).click( function() {
                        $this.find( ".truncate_more" ).fadeOut( "normal", function() {
                            $this.find( ".truncate_less" ).fadeIn( "normal", function() {
                                fixIE( this );
                                $(this).css( "background", "none" );
                            });
                            fixIE( this );
                        });
                        return false;
                    });
                }
                $this.find( ".truncate_less" ).fadeOut( "normal", function() {
                    $this.find( ".truncate_more" ).fadeIn( "normal", function() {
                        fixIE( this );
                    });
                    fixIE( this );
                });
                jQuery(".truncate_show",$this).click( function() {
                    $this.find( ".truncate_less" ).fadeOut( "normal", function() {
                        $this.find( ".truncate_more" ).fadeIn( "normal", function() {
                            fixIE( this );
                            $(this).css( "background", "none" );
                        });
                        fixIE( this );
                    });
                    return false;
                });
                return false;
            });
        }
    });
};

/******************************************************************************************************************************

 * @ Original idea by by Binny V A, Original version: 2.00.A 
 * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * @ Original License : BSD
 
 * @ jQuery Plugin by Tzury Bar Yochay 
        mail: tzury.by@gmail.com
        blog: evalinux.wordpress.com
        face: facebook.com/profile.php?id=513676303
        
        (c) Copyrights 2007
        
 * @ jQuery Plugin version Beta (0.0.2)
 * @ License: jQuery-License.
 
TODO:
    add queue support (as in gmail) e.g. 'x' then 'y', etc.
    add mouse + mouse wheel events.

USAGE:
    $.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');});
    $.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});>
    $.hotkeys.remove('Ctrl+c'); 
    $.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'}); 
    
******************************************************************************************************************************/
(function (jQuery){
    this.version = '(beta)(0.0.3)';
	this.all = {};
    this.special_keys = {
        27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock', 
        144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup', 
        34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3', 
        115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'};
        
    this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", 
        "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", 
        ".":">",  "/":"?",  "\\":"|" };
        
    this.add = function(combi, options, callback) {
        if (jQuery.isFunction(options)){
            callback = options;
            options = {};
        }
        var opt = {},
            defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0], checkParent: true},
            that = this;
        opt = jQuery.extend( opt , defaults, options || {} );
        combi = combi.toLowerCase();        
        
        // inspect if keystroke matches
        var inspector = function(event) {
            event = jQuery.event.fix(event); // jQuery event normalization.
            var element = event.target;
            // @ TextNode -> nodeType == 3
            element = (element.nodeType==3) ? element.parentNode : element;
            
            if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields
                var target = jQuery(element);
                if( target.is("input") || target.is("textarea")){
                    return;
                }
            }
            var code = event.which,
                type = event.type,
                character = String.fromCharCode(code).toLowerCase(),
                special = that.special_keys[code],
                shift = event.shiftKey,
                ctrl = event.ctrlKey,
                alt= event.altKey,
                propagate = true, // default behaivour
                mapPoint = null;
            
            // in opera + safari, the event.target is unpredictable.
            // for example: 'keydown' might be associated with HtmlBodyElement 
            // or the element where you last clicked with your mouse.
            if (jQuery.browser.opera || jQuery.browser.safari || opt.checkParent){
                while (!that.all[element] && element.parentNode){
                    element = element.parentNode;
                }
            }
            
            var cbMap = that.all[element].events[type].callbackMap;
            if(!shift && !ctrl && !alt) { // No Modifiers
                mapPoint = cbMap[special] ||  cbMap[character]
			}
            // deals with combinaitons (alt|ctrl|shift+anything)
            else{
                var modif = '';
                if(alt) modif +='alt+';
                if(ctrl) modif+= 'ctrl+';
                if(shift) modif += 'shift+';
                // modifiers + special keys or modifiers + characters or modifiers + shift characters
                mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]]
            }
            if (mapPoint){
                mapPoint.cb(event);
                if(!mapPoint.propagate) {
                    event.stopPropagation();
                    event.preventDefault();
                    return false;
                }
            }
		};        
        // first hook for this element
        if (!this.all[opt.target]){
            this.all[opt.target] = {events:{}};
        }
        if (!this.all[opt.target].events[opt.type]){
            this.all[opt.target].events[opt.type] = {callbackMap: {}}
            jQuery.event.add(opt.target, opt.type, inspector);
        }        
        this.all[opt.target].events[opt.type].callbackMap[combi] =  {cb: callback, propagate:opt.propagate};                
        return jQuery;
	};    
    this.remove = function(exp, opt) {
        opt = opt || {};
        target = opt.target || jQuery('html')[0];
        type = opt.type || 'keydown';
		exp = exp.toLowerCase();        
        delete this.all[target].events[type].callbackMap[exp]        
        return jQuery;
	};
    jQuery.hotkeys = this;
    return jQuery;    
})(jQuery);
/*
 * jQuery Form Plugin
 * version: 2.07 (03/04/2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
 (function($) {
/**
 * ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.
 *
 * ajaxSubmit accepts a single argument which can be either a success callback function
 * or an options Object.  If a function is provided it will be invoked upon successful
 * completion of the submit and will be passed the response from the server.
 * If an options Object is provided, the following attributes are supported:
 *
 *  target:   Identifies the element(s) in the page to be updated with the server response.
 *            This value may be specified as a jQuery selection string, a jQuery object,
 *            or a DOM element.
 *            default value: null
 *
 *  url:      URL to which the form data will be submitted.
 *            default value: value of form's 'action' attribute
 *
 *  type:     The method in which the form data should be submitted, 'GET' or 'POST'.
 *            default value: value of form's 'method' attribute (or 'GET' if none found)
 *
 *  data:     Additional data to add to the request, specified as key/value pairs (see $.ajax).
 *
 *  beforeSubmit:  Callback method to be invoked before the form is submitted.
 *            default value: null
 *
 *  success:  Callback method to be invoked after the form has been successfully submitted
 *            and the response has been returned from the server
 *            default value: null
 *
 *  dataType: Expected dataType of the response.  One of: null, 'xml', 'script', or 'json'
 *            default value: null
 *
 *  semantic: Boolean flag indicating whether data must be submitted in semantic order (slower).
 *            default value: false
 *
 *  resetForm: Boolean flag indicating whether the form should be reset if the submit is successful
 *
 *  clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful
 *
 *
 * The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for
 * validating the form data.  If the 'beforeSubmit' callback returns false then the form will
 * not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data
 * in array format, the jQuery object, and the options object passed into ajaxSubmit.
 * The form data array takes the following form:
 *
 *     [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * If a 'success' callback method is provided it is invoked after the response has been returned
 * from the server.  It is passed the responseText or responseXML value (depending on dataType).
 * See jQuery.ajax for further details.
 *
 *
 * The dataType option provides a means for specifying how the server response should be handled.
 * This maps directly to the jQuery.httpData method.  The following values are supported:
 *
 *      'xml':    if dataType == 'xml' the server response is treated as XML and the 'success'
 *                   callback method, if specified, will be passed the responseXML value
 *      'json':   if dataType == 'json' the server response will be evaluted and passed to
 *                   the 'success' callback, if specified
 *      'script': if dataType == 'script' the server response is evaluated in the global context
 *
 *
 * Note that it does not make sense to use both the 'target' and 'dataType' options.  If both
 * are provided the target will be ignored.
 *
 * The semantic argument can be used to force form serialization in semantic order.
 * This is normally true anyway, unless the form contains input elements of type='image'.
 * If your form must be submitted with name/value pairs in semantic order and your form
 * contains an input of type='image" then pass true for this arg, otherwise pass false
 * (or nothing) to avoid the overhead for this logic.
 *
 *
 * When used on its own, ajaxSubmit() is typically bound to a form's submit event like this:
 *
 * $("#form-id").submit(function() {
 *     $(this).ajaxSubmit(options);
 *     return false; // cancel conventional submit
 * });
 *
 * When using ajaxForm(), however, this is done for you.
 *
 * @example
 * $('#myForm').ajaxSubmit(function(data) {
 *     alert('Form submit succeeded! Server returned: ' + data);
 * });
 * @desc Submit form and alert server response
 *
 *
 * @example
 * var options = {
 *     target: '#myTargetDiv'
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc Submit form and update page element with server response
 *
 *
 * @example
 * var options = {
 *     success: function(responseText) {
 *         alert(responseText);
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc Submit form and alert the server response
 *
 *
 * @example
 * var options = {
 *     beforeSubmit: function(formArray, jqForm) {
 *         if (formArray.length == 0) {
 *             alert('Please enter data.');
 *             return false;
 *         }
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc Pre-submit validation which aborts the submit operation if form data is empty
 *
 *
 * @example
 * var options = {
 *     url: myJsonUrl.php,
 *     dataType: 'json',
 *     success: function(data) {
 *        // 'data' is an object representing the the evaluated json data
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc json data returned and evaluated
 *
 *
 * @example
 * var options = {
 *     url: myXmlUrl.php,
 *     dataType: 'xml',
 *     success: function(responseXML) {
 *        // responseXML is XML document object
 *        var data = $('myElement', responseXML).text();
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc XML data returned from server
 *
 *
 * @example
 * var options = {
 *     resetForm: true
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc submit form and reset it if successful
 *
 * @example
 * $('#myForm).submit(function() {
 *    $(this).ajaxSubmit();
 *    return false;
 * });
 * @desc Bind form's submit event to use ajaxSubmit
 *
 *
 * @name ajaxSubmit
 * @type jQuery
 * @param options  object literal containing options which control the form submission process
 * @cat Plugins/Form
 * @return jQuery
 */
$.fn.ajaxSubmit = function(options) {
    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) return this;

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this;

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) return this;

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i](data, status, $form);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        var opts = $.extend({}, $.ajaxSettings, options);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];
        var op8 = $.browser.opera && window.opera.version() < 9;
        if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

        var cbInvoked = 0;
        var timedOut = 0;

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;
                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * Note that for accurate x/y coordinates of image submit elements in all browsers
 * you need to also use the "dimensions" plugin (this method will auto-detect its presence).
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.  See ajaxSubmit for a full description of the options argument.
 *
 *
 * @example
 * var options = {
 *     target: '#myTargetDiv'
 * };
 * $('#myForm').ajaxSForm(options);
 * @desc Bind form's submit event so that 'myTargetDiv' is updated with the server response
 *       when the form is submitted.
 *
 *
 * @example
 * var options = {
 *     success: function(responseText) {
 *         alert(responseText);
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc Bind form's submit event so that server response is alerted after the form is submitted.
 *
 *
 * @example
 * var options = {
 *     beforeSubmit: function(formArray, jqForm) {
 *         if (formArray.length == 0) {
 *             alert('Please enter data.');
 *             return false;
 *         }
 *     }
 * };
 * $('#myForm').ajaxSubmit(options);
 * @desc Bind form's submit event so that pre-submit callback is invoked before the form
 *       is submitted.
 *
 *
 * @name   ajaxForm
 * @param  options  object literal containing options which control the form submission process
 * @return jQuery
 * @cat    Plugins/Form
 * @type   jQuery
 */
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var $form = this.form;
            $form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    $form.clk_x = e.offsetX;
                    $form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    $form.clk_x = e.pageX - offset.left;
                    $form.clk_y = e.pageY - offset.top;
                } else {
                    $form.clk_x = e.pageX - this.offsetLeft;
                    $form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
        });
    });
};


/**
 * ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
 *
 * @name   ajaxFormUnbind
 * @return jQuery
 * @cat    Plugins/Form
 * @type   jQuery
 */
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 *
 * The semantic argument can be used to force form serialization in semantic order.
 * This is normally true anyway, unless the form contains input elements of type='image'.
 * If your form must be submitted with name/value pairs in semantic order and your form
 * contains an input of type='image" then pass true for this arg, otherwise pass false
 * (or nothing) to avoid the overhead for this logic.
 *
 * @example var data = $("#myForm").formToArray();
 * $.post( "myscript.cgi", data );
 * @desc Collect all the data from a form and submit it to the server.
 *
 * @name formToArray
 * @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
 * @type Array<Object>
 * @cat Plugins/Form
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};


/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 *
 * The semantic argument can be used to force form serialization in semantic order.
 * If your form must be submitted with name/value pairs in semantic order then pass
 * true for this arg, otherwise pass false (or nothing) to avoid the overhead for
 * this logic (which can be significant for very large forms).
 *
 * @example var data = $("#myForm").formSerialize();
 * $.ajax('POST', "myscript.cgi", data);
 * @desc Collect all the data from a form into a single string
 *
 * @name formSerialize
 * @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
 * @type String
 * @cat Plugins/Form
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};


/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 *
 * The successful argument controls whether or not serialization is limited to
 * 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.
 *
 * @example var data = $("input").fieldSerialize();
 * @desc Collect the data from all successful input elements into a query string
 *
 * @example var data = $(":radio").fieldSerialize();
 * @desc Collect the data from all successful radio input elements into a query string
 *
 * @example var data = $("#myForm :checkbox").fieldSerialize();
 * @desc Collect the data from all successful checkbox input elements in myForm into a query string
 *
 * @example var data = $("#myForm :checkbox").fieldSerialize(false);
 * @desc Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string
 *
 * @example var data = $(":input").fieldSerialize();
 * @desc Collect the data from all successful input, select, textarea and button elements into a query string
 *
 * @name fieldSerialize
 * @param successful true if only successful controls should be serialized (default is true)
 * @type String
 * @cat Plugins/Form
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};


/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 *
 * @example var data = $("#myPasswordElement").fieldValue();
 * alert(data[0]);
 * @desc Alerts the current value of the myPasswordElement element
 *
 * @example var data = $("#myForm :input").fieldValue();
 * @desc Get the value(s) of the form elements in myForm
 *
 * @example var data = $("#myForm :checkbox").fieldValue();
 * @desc Get the value(s) for the successful checkbox element(s) in the jQuery object.
 *
 * @example var data = $("#mySingleSelect").fieldValue();
 * @desc Get the value(s) of the select control
 *
 * @example var data = $(':text').fieldValue();
 * @desc Get the value(s) of the text input or textarea elements
 *
 * @example var data = $("#myMultiSelect").fieldValue();
 * @desc Get the values for the select-multiple control
 *
 * @name fieldValue
 * @param Boolean successful true if only the values for successful controls should be returned (default is true)
 * @type Array<String>
 * @cat Plugins/Form
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If the given element is not
 * successful and the successful arg is not false then the returned value will be null.
 *
 * Note: If the successful flag is true (default) but the element is not successful, the return will be null
 * Note: The value returned for a successful select-multiple element will always be an array.
 * Note: If the element has no value the return value will be undefined.
 *
 * @example var data = jQuery.fieldValue($("#myPasswordElement")[0]);
 * @desc Gets the current value of the myPasswordElement element
 *
 * @name fieldValue
 * @param Element el The DOM element for which the value will be returned
 * @param Boolean successful true if value returned must be for a successful controls (default is true)
 * @type String or Array<String> or null or undefined
 * @cat Plugins/Form
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};


/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 *
 * @example $('form').clearForm();
 * @desc Clears all forms on the page.
 *
 * @name clearForm
 * @type jQuery
 * @cat Plugins/Form
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.  Takes the following actions on the matched elements:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 *
 * @example $('.myInputs').clearFields();
 * @desc Clears all inputs with class myInputs
 *
 * @name clearFields
 * @type jQuery
 * @cat Plugins/Form
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};


/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 *
 * @example $('form').resetForm();
 * @desc Resets all forms on the page.
 *
 * @name resetForm
 * @type jQuery
 * @cat Plugins/Form
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};


/**
 * Enables or disables any matching elements.
 *
 * @example $(':radio').enabled(false);
 * @desc Disables all radio buttons
 *
 * @name select
 * @type jQuery
 * @cat Plugins/Form
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 *
 * @example $(':checkbox').select();
 * @desc Checks all checkboxes
 *
 * @name select
 * @type jQuery
 * @cat Plugins/Form
 */
$.fn.select = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').select(false);
            }
            this.selected = select;
        }
    });
};

})(jQuery);

﻿/*
 * jQuery blockUI plugin
 * Version 2.08 (06/11/2008)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
    return;
}

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// plugin method for blocking element content
$.fn.block = function(opts) {
    return this.each(function() {
        if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
        if ($.browser.msie) 
            this.style.zoom = 1; // force 'hasLayout'
        install(this, opts);
    });
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
    return this.each(function() {
        remove(this, opts);
    });
};

$.blockUI.version = 2.08; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
    // message displayed when blocking (use null for no message)
    message:  '<h1>Please wait...</h1>',
    
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: { 
        padding:        0,
        margin:         0,
        width:          '30%', 
        top:            '40%', 
        left:           '35%', 
        textAlign:      'center', 
        color:          '#000', 
        border:         '3px solid #aaa',
        backgroundColor:'#fff',
        cursor:         'wait'
    },
    
    // styles for the overlay
    overlayCSS:  { 
        backgroundColor:'#000', 
        opacity:        '0.6' 
    },
    
    // z-index for the blocking overlay
    baseZ: 1000,
    
    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,
    
    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,
    
    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,
    
    // fadeOut time in millis; set to 0 to disable fadeout on unblock
    fadeOut:  400,
    
    // if true, focus will be placed in the first available input field when
    // page blocking
    focusInput: true,
    
    // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
    applyPlatformOpacityRules: true,
    
    // callback method invoked when unblocking has completed; the callback is
    // passed the element that has been unblocked (which is the window object for page
    // blocks) and the options that were passed to the unblock call:
    //     onUnblock(element, options)
    onUnblock: null
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
    var full = (el == window);
    var msg = opts && opts.message !== undefined ? opts.message : undefined;
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
    var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
    msg = msg === undefined ? opts.message : msg;

    // remove the current block (if there is one)
    if (full && pageBlock) 
        remove(window, {fadeOut:0}); 
    
    // if an existing element is being used as the blocking content then we capture
    // its current place in the DOM (and current display style) so we can restore
    // it when we unblock
    if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
        var node = msg.jquery ? msg[0] : msg;
        var data = {};
        $(el).data('blockUI.history', data);
        data.el = node;
        data.parent = node.parentNode;
        data.display = node.style.display;
        data.position = node.style.position;
        data.parent.removeChild(node);
    }
    
    var z = opts.baseZ;
    
    // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
    // layer1 is the iframe layer which is used to supress bleed through of underlying content
    // layer2 is the overlay layer which has opacity and a wait cursor
    // layer3 is the message content that is displayed while blocking
    
    var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:'+ z++ +';border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
    var lyr2 = $('<div class="blockUI" style="z-index:'+ z++ +';cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
    var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');

    // if we have a message, style it
    if (msg) 
        lyr3.css(css);

    // style the overlay
    if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))) 
        lyr2.css(opts.overlayCSS);
    lyr2.css('position', full ? 'fixed' : 'absolute');
    
    // make iframe layer transparent in IE
    if ($.browser.msie) 
        lyr1.css('opacity','0.0');

    $([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
    
    // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
    var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
    if (ie6 || expr) {
        // give body 100% height
        if (full && opts.allowBodyStretch && $.boxModel)
            $('html,body').css('height','100%');

        // fix ie6 issue when blocked element has a border width
        if ((ie6 || !$.boxModel) && !full) {
            var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
            var fixT = t ? '(0 - '+t+')' : 0;
            var fixL = l ? '(0 - '+l+')' : 0;
        }

        // simulate fixed position
        $.each([lyr1,lyr2,lyr3], function(i,o) {
            var s = o[0].style;
            s.position = 'absolute';
            if (i < 2) {
                full ? s.setExpression('height','document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"')
                     : s.setExpression('height','this.parentNode.offsetHeight + "px"');
                full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                if (fixL) s.setExpression('left', fixL);
                if (fixT) s.setExpression('top', fixT);
            }
            else if (opts.centerY) {
                if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                s.marginTop = 0;
            }
        });
    }
    
    // show the message
    lyr3.append(msg).show();
    if (msg && (msg.jquery || msg.nodeType))
        $(msg).show();

    // bind key and mouse events
    bind(1, el, opts);
        
    if (full) {
        pageBlock = lyr3[0];
        pageBlockEls = $(':input:enabled:visible',pageBlock);
        if (opts.focusInput)
            setTimeout(focus, 20);
    }
    else
        center(lyr3[0], opts.centerX, opts.centerY);
};

// remove the block
function remove(el, opts) {
    var full = el == window;
    var data = $(el).data('blockUI.history');
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    bind(0, el, opts); // unbind events
    var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);
    
    if (full) 
        pageBlock = pageBlockEls = null;

    if (opts.fadeOut) {
        els.fadeOut(opts.fadeOut);
        setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
    }
    else
        reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
    els.each(function(i,o) {
        // remove via DOM calls so we don't lose event handlers
        if (this.parentNode) 
            this.parentNode.removeChild(this);
    });
    if (data && data.el) {
        data.el.style.display = data.display;
        data.el.style.position = data.position;
        data.parent.appendChild(data.el);
        $(data.el).removeData('blockUI.history');
    }
    if (typeof opts.onUnblock == 'function')
        opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
    var full = el == window, $el = $(el);
    
    // don't bother unbinding if there is nothing to unbind
    if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) 
        return;
    if (!full) 
        $el.data('blockUI.isBlocked', b);
        
    // bind anchors and inputs for mouse and key events
    var events = 'mousedown mouseup keydown keypress click';
    b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//    var $e = $('a,:input');
//    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
    // allow tab navigation (conditionally)
    if (e.keyCode && e.keyCode == 9) {
        if (pageBlock && e.data.constrainTabKey) {
            var els = pageBlockEls;
            var fwd = !e.shiftKey && e.target == els[els.length-1];
            var back = e.shiftKey && e.target == els[0];
            if (fwd || back) {
                setTimeout(function(){focus(back)},10);
                return false;
            }
        }
    }
    // allow events within the message content
    if ($(e.target).parents('div.blockMsg').length > 0)
        return true;
        
    // allow events for content that is not being blocked
    return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
    if (!pageBlockEls) 
        return;
    var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
    if (e) 
        e.focus();
};

function center(el, x, y) {
    var p = el.parentNode, s = el.style;
    var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
    var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
    if (x) s.left = l > 0 ? (l+'px') : '0';
    if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};

})(jQuery);



/*
 * DOM node creation for jQuery.
 *
 * Author  :  Sean Gilbertson
 * Created :  2006-01-04
 *
 */

$.create = function() {
    if (arguments.length == 0) {
        return [];
    }
    
    var first_arg = arguments[0];

    /*
     * In case someone passes in a null object,
     * assume that they want an empty string.
     */
    if (first_arg == null) {
        first_arg = "";
    }

    if (first_arg.constructor == String) {
        if (arguments.length > 1) {
            var second_arg = arguments[1];
            
            if (second_arg.constructor == String) {
                var elt = document.createTextNode(first_arg);
                
                var elts = [];
                
                elts.push(elt);

                var siblings = $.create.apply(null, Array.prototype.slice.call(arguments, 1));

                elts = elts.concat(siblings);
                
                return elts;
            } else {
                var elt = document.createElement(first_arg);
                
                /*
                 * Set element attributes.
                 */
                var attributes = arguments[1];

                for (var attr in attributes) {
                    $(elt).attr(attr, attributes[attr]);
                }
        
                /*
                 * Add children of this element.
                 */
                if (arguments[2] != undefined)
                {
                    var children = arguments[2];
                    
                    children = $.create.apply(null, children);
    
                    $(elt).append(children);
                }
                /*
                 * If there are more siblings, render those too.
                 */
                if (arguments.length > 3) {
                    var siblings = $.create.apply(null, Array.prototype.slice.call(arguments, 3));
                    
                    return [elt].concat(siblings);
                }
        
                return elt;
            }
        } else {
            return document.createTextNode(first_arg);
        }
    }   else {
        var elts = [];
        
        elts.push(first_arg);

        var siblings = $.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
                
        elts = elts.concat(siblings);
        
        return elts;
    }
}

var pageTracker = _gat._getTracker("UA-4060473-1");
pageTracker._initData();
pageTracker._trackPageview();

/**
 * Camigolo
 *  
 * @category   Javascript
 * @package    script
 * @copyright  Copyright (c) 2008 OnlineShop Consulting AG (http://www.oscag.de)
 * @author     Andreas Eckersperger (andreas.eckersperger@oscag.de)
 * 
 * @version    $Id: core-all.js 784 2008-07-02 09:20:04Z andreas.eckersperger $
 */
 
 
var poimarkers = new Array(), poilastm, gis, map;
var application, action;



$(document).ready(function()
{   
    application = new application();
    action = new action();
        
    $("div.info").fadeIn('slow');
});



function application()
{
    var _session;
    
    
    
    this.load = function()
    {
        $.getJSON('/ESB/JSON_RPC.debug_session', function(response)
        {
            _session = response;
        });
        
        $("label.overlabel").overlabel(); 
    
        $('button#actionssubmit_detail_button').click(function()
        {
            $('#fieldset_actionsearchdata').show();
            $('#actionssubmit_detail_button').remove();
        });

        $("p.legend").truncate( 160, {
            chars: /./,
            trail: [ " ... <a href='#' class='truncate_show'>(Mehr Infos?)</a>", " <a href='#' class='truncate_hide'>(Wieder ausblenden?)</a>" ]
        });
        
        $.hotkeys.add('F8', function()
        {
            $('input, button, select, textarea').attr("disabled", true); 
    
            $("label, legend, button, span.label").editable("/ESB/JSON_RPC.i18n_save", {loadurl: "/ESB/JSON_RPC.i18n_load"});
            $("div.contentblock, p.legend").editable("/ESB/JSON_RPC.i18n_save", {loadurl: "/ESB/JSON_RPC.i18n_load", type: "textarea", submit: "Speichern"});
        });
        
        $('button#gpxupload').click(function()
        {
            action.loadGPX();
            return false;
        });
                
    }
    
   /**
    * Funktion für Autocomplete Felder
    */
    this.autocomplete = function()
    {
        $("form input[bluraction]").bind('blur', function()
        {
            $.getJSON('/ESB/JSON_RPC.' + $(this).attr('bluraction') + '?key=' +  $(this).attr('value') + '&target=' + $(this).attr('target'), function(response)
            {
                $("#" + response.target).val(response.value);
            });
        });
    }

    /**
     * Kennzeichnung der Formularfelder bei fehlern
     */
    this.form = function()
    {
        $("form label.required").each(function()
        {
            $(this).html($(this).html() + '<em class="required">*</em>');
            $(this).removeClass('required');
        });
           
        $("form label.error").each(function()
        {
            $(this).find('em').addClass('error');
            $(this).removeClass('error');
        });
        
        this.autocomplete();
    }
       
    /**
     * Das erstellen der TabPanels aus DOM.
     */
    this.tabpanel = function()
    {
		$("div.tabpanel").each(function()
        {
            $(this).find('.tab').hide();
            
			$(this).find("dl a.tabregister").each(function(intIndex)
            {
				$(this).click(function()
                {

                    $(this).parents('div.tabpanel').find('.tab').removeClass('active');
                    $(this).parents('div.tabpanel').find('.tab').hide();
					$(this).parents('dl').find('dt').removeClass('active');
					$(this).parents('div.tabpanel').find('.tab').eq(intIndex).addClass('active');
                    $(this).parents('div.tabpanel').find('.tab').eq(intIndex).show();
					$(this).parents('dt').addClass('active');

                    if(document.location.pathname == '/action/new' || document.location.pathname == '/tour-editieren')
                    {
                        $('div#actionsubmit').show();
                    }
                    
					if ($(this).parents('div.tabpanel').find('.tab').eq(intIndex).find('#mapaction_map, #mapview_map').get(0))
                    {
						if ($(this).attr('rendered') != 'true')
                        {
							$(this).attr('rendered', 'true');

							/**
							 * Laden der Google Map API
							 */
							$('body').append($.create("script",
                            {
								"id" : "gapi",
								"type" : "text/javascript",
                                "src" : "http://maps.google.com/maps?file=api&v=2&async=2&callback=buildMaps&key=" + 'ABQIAAAA2i4FFsBeSGJ6HI3DeoG4QBQsNcaE1s_j-jeCvslIMElyotV6uxQc-7ZYDPBdiPy4ETbKPknr1o4Ixg'
							}, [""]));
						}
					}
                    
                    $('.freeads').hide();
                    if ($(this).parents('div.tabpanel').find('.tab').eq(intIndex).find('.showBox').get(0))
                    {
                        $('.freeads').show();
                    }
                    
                    
                    pageTracker._trackPageview(document.location.href + "/" + $(this).html());

                    return false;
				});
			});
            
			/**
             * Setzt alle Tabs auf die gleiche Höhe.
             */
            if (false)
            {
                var tabhight = 0;
                
    			$(this).find(".tab").each(function(intIndex)
                {
    				if ($(this).height() > tabhight)
                    {
    					tabhight = $(this).height();
    				}
    			});
                
    			$(this).find(".tab").each(function(intIndex)
                {
    				$(this).height(tabhight);
    			});
            }
                        
            $(this).find("button.prevtab").click(function()
            {
                $(this).parents('div.tabpanel').attr('ac', parseInt($(this).parents('div.tabpanel').attr('ac')) - 1);
                $(this).parents('div.tabpanel').find("a.tabregister").eq(parseInt($(this).parents('div.tabpanel').attr('ac'))).click();
                
                if (parseInt($(this).parents('div.tabpanel').attr('ac')) <= 0)
                {
                    $(this).parents('div.tabpanel').find("button.prevtab").attr("disabled", "disabled");
                    $(this).parents('div.tabpanel').find("button.nexttab").removeAttr("disabled");
                } else if (parseInt($(this).parents('div.tabpanel').attr('ac')) >= 5)
                {
                    $(this).parents('div.tabpanel').find("button.prevtab").removeAttr("disabled");
                    $(this).parents('div.tabpanel').find("button.nexttab").attr("disabled", "disabled");
                }
                
                return false;
            });
            
            $(this).find("button.nexttab").click(function()
            {
                $(this).parents('div.tabpanel').attr('ac', parseInt($(this).parents('div.tabpanel').attr('ac')) + 1);
                $(this).parents('div.tabpanel').find("a.tabregister").eq(parseInt($(this).parents('div.tabpanel').attr('ac'))).click();
                return false;
            });
            
            
            $(this).attr('ac', 0);
			$(this).find("a").eq($(this).attr('ac')).click();
            
            $('input.publicflag').click(function()
            {
                $.prompt('<div class="contentblock">Vielen Dank f&uuml;r die Ver&ouml;ffentlichung Ihrer Tour.<br /><br />Ihre Eingaben werden nach dem Speichern von der Camigolo Redaktion &uuml;berpr&uuml;ft und umgehend freigeschalten!</div><button class="" id="publicflag_button" name="Schliessen" type="button">Schliessen</button><br />',              
                { buttons: { 'Schlie&szlig;en':true }, prefix: 'jqi'}).corner();
                $('button#publicflag_button').click(function()
                {
                    $('.jqi').remove();
                    $('.jqifade').remove();
                });
            });

		});
    }
    
    /**
     * Zugriff auf die PHP Session
     */
    this.session = function(key)
    {
        return _session[key];
    }
    
    /**
     * Bilder werden erst geladen, wenn sie im Viewport angezeigt werden.
     */
    this.imgload = function()
    {
        $("img").lazyload();
    }
    
    this.textareaCounter = function()
    {
        $('textarea.max').each(function()
        {
            $(this).removeClass('max');
            $(this).addClass('maxdone');
            
            $(this).prev('label').append($.create("div",
            {
                "class" : "counter"
            }, ["(Maximal " + $(this).attr('max') + " Zeichen)"]));
        });
        
        $('textarea.maxdone').keyup(function()
        {
            if ($(this).val().length > $(this).attr('max'))
            {
                $(this).val($(this).val().substr(0,$(this).attr('max')));
                $(this).prev('label').find('div.counter').html("(" + $(this).attr('max') + " von " + $(this).attr('max') + " Zeichen)");
            } else if ($(this).val().length == 0)
            {
                $(this).prev('label').find('div.counter').html("(Maximal " + $(this).attr('max') + " Zeichen)");
            }
            else
            {
                $(this).prev('label').find('div.counter').html("(" + $(this).val().length + " von " + $(this).attr('max') + " Zeichen)");
            }
        });
    }
    
    /**
     * Form Autosubmit
     */
    this.autosubmit = function()
    {
        $('.autosubmit').each(function()
        {
            clicker = $(this);
            window.setInterval(function()
            {
                if ($(clicker).val())
                {
                    $(clicker).parent('form').ajaxSubmit(
                    { 
                        data: {rpcForm: 'true', rpcResponse: 'status'}
                    });
                }
            }, ($(this).attr('clickinterval') ? parseInt($(this).attr('clickinterval')) * 1000 : 60000));
        });
    }
    
    /**
     * ################## Camigolo ##################
     */
    
    this.actionAddStep = function()
    {        
    }
    
    this.indexMap = function()
    {
        
        $('#mapindex_map').each(function()
        {
            $('body').append($.create("script",
            {
                "id" : "gapi",
                "type" : "text/javascript",
                "src" : "http://maps.google.com/maps?file=api&v=2&async=2&callback=buildMaps&key=" + "ABQIAAAA2i4FFsBeSGJ6HI3DeoG4QBQsNcaE1s_j-jeCvslIMElyotV6uxQc-7ZYDPBdiPy4ETbKPknr1o4Ixg"
            }, [""]));
        });
    }
    
    this.load();
    this.tabpanel();
    //this.imgload();
    this.form();
    this.textareaCounter();
    this.autosubmit();
    this.indexMap();
        
    $('a.vcard').click(function()
    {
	    $.ajax(
	    {
	    	type: "POST",
	    	url: "/ESB/JSON_RPC.advert_getvcard",
	    	data: {title: $(this).attr('href')},
	    	data: {id: $(this).attr('id')},
	    	dataType: 'html',
	    	success: function(response)
	    	{
	    		
	    		$.prompt(response, 	    		
	    		{ buttons: { 'Schlie&szlig;en':true }, prefix: 'jqitab'}).corner();
	    		application.tabpanel();
	    	} 
	    });
	    return false;
    });
    
    $('a.rating').click(function()
    {
	    $.ajax(
	    {
	    	type: "POST",
	    	url: "/ESB/JSON_RPC.actionrating_getrating",
	    	data: {id: $(this).attr('href')},
	    	dataType: 'html',
	    	success: function(response)
	    	{
	    		$.prompt(response, { buttons: { 'Schlie&szlig;en':true } }).corner();
                
                $('button#rating_Schliessen_button').click(function()
                {
                    $('#jqi, #jqifade').remove();

                    return false;
                });

	    	} 
	    });
	    return false;
    });
    
    $('a.fastinput').click(function()
    {        
        $.ajax(
        {
            type: "POST",
            url: "/ESB/JSON_RPC.mapaction_fastinput",
            data: {l: $(this).attr('href')},

            success: function(response)
            {

                $.prompt(response, 
                { 
                    buttons: { 'Schlie&szlig;en':true },
                    submit: function()
                    {
                
                        return true;
                    }
                }).corner();
                
                action.typeAction();
                
                $('button#fastinput_Schliessen_button').click(function()
                {
                    $('#jqi, #jqifade').remove();
                    
                    return false;
                });
                
                $('#fastinputForm').ajaxForm(
                {
                    dataType: 'text',
                    beforeSubmit: function()
                    { 
                        $.blockUI(
                        {
                            message: '<div class="contentblock">Ausflug wird gespeichert!</div><br /><br /><br /><img src="/resources/images/animation/loader.gif" height="250" width="300" alt="lade" /> ',
                            css: { 
                                border: 'none', 
                                backgroundColor: 'transparent'
                            },
                            overlayCSS:  {  
                                backgroundColor:'white',  
                                opacity:        '0.6'  
                            },
                            allowBodyStretch: true, 
                            constrainTabKey: true
                        });
                                    
                        return true;
                    },
                    success: function(response)
                    {
                        $.unblockUI();
                        
                        
                        $('#jqi, #jqifade').remove();
                        if (response == "error")
                        {
                            self.location.href="/action/fastinput?v=false";
                        }   else
                        {
                            self.location.href="/user/myactions?s=1&c="+ Math.floor(Math.random()*101);
                        }
                    }
                });               
            } 
        });
        return false;
    });
    $('a.fastinputregister').click(function()
    {
        $.ajax(
        {
            type: "POST",
            url: "/ESB/JSON_RPC.mapaction_fastinputregister",
            success: function(response)
            {
                $.prompt(response, { buttons: { 'Schlie&szlig;en':true }, prefix: 'jqismall' }).corner();
            } 
        });
        return false;
    });

    
    
    $('div.cat').hover(function()
    {
        $(this).addClass('hover');
        $('div.category_right').find('span.cat' + $(this).attr('cat')).addClass('active');;
    }, function()
    {
        $(this).removeClass('hover');
        $('div.category_right').find('span').removeClass('active');
    });
}








function action()
{    
    var form;
    var stepForm;
    var gpxForm;
    var stepFormPrompt;
    
    this.save = function()
    {
        
    }
    
    this.renderRoudbook = function()
    {
        $("fieldset#fieldset_routebook ol ul li p").truncate( 80, {
            chars: /./,
            trail: [ " ... <a href='#' class='truncate_show'>(Mehr?)</a>", " <a href='#' class='truncate_hide'>(Wieder ausblenden?)</a>" ]
        });
        
        
        $("fieldset#fieldset_routebook ol ul li").mouseover(function()
        {
            $(this).addClass("over");
        });
        
        $("fieldset#fieldset_routebook ol ul li").mouseout(function()
        {
            $(this).removeClass("over");
        });
        
        $("fieldset#fieldset_routebook ol ul").Sortable(
            {
                accept : 'item',
                helperclass : 'sorthelper',
                opacity:    0.5,
                axis: 'vertically',
                tolerance: 'intersect',
                fit :   true,
                floats: true,
                containment: 'fieldset_routebook',
                onStop: function()
                {
                    $(this).css({top: "0"});
                    
                    $.ajax(
                    {
                        type: "POST",
                        url: "/ESB/JSON_RPC.mapaction_orderstep",
                        data: {item: $(this).find('span.steppoint').html(), next: $(this).next().find('span.steppoint').html()},
                        dataType: 'json',
                        success: function(response)
                        {                        

                        }
                    });
                }
            }
        );
        
        $("fieldset#fieldset_routebook ol ul li").each(function()
        {
            var point = $(this).find('.steppoint').html();
            
             $(this).find("a.delete").click(function()
             {
                 $.ajax(
                 {
                     type: "POST",
                     url: "/ESB/JSON_RPC.mapaction_deletestep",
                     data: {point: point},
                     dataType: 'json',
                     success: function(response)
                     {
                        if (map)
                        {
                            gis.removePOI(poimarkers['(' + point + ')']);
                        }
                        
                        if (response.steps)
                        {
                            if ($("fieldset#fieldset_routebook ol ul"))
                            {
                                $("fieldset#fieldset_routebook ol ul").remove();
                            }
                            $("fieldset#fieldset_routebook ol").append(response.steps);
                            action.renderRoudbook();
                        }
                     }
                 });
                 return false;
             });
            
             $(this).find("a.edit").click(function()
             {
                 $.ajax(
                 {
                     type: "POST",
                     url: "/ESB/JSON_RPC.mapaction_editstep",
                     data: {point: point, src: $(this).attr('src')},
                     dataType: 'json',
                     success: function(response)
                     {                        
                        action.stepMessageBox(response.data, 'edit');
                        $('input#fotostep_pictitle2').hide();

                     }
                 });
                 return false;
             });
                $(this).find("a.titleimage").click(function()
                {
                     $.ajax(
                     {
                         type: "POST",
                         url: "/ESB/JSON_RPC.mapaction_titleimage",
                         data: {src: $(this).attr('href'),id: $(this).attr('aid'), point: point},
                         dataType: 'json',
                         success: function(response)
                         {                        

                            $('img#roadbooktitleimage').attr('src', response.title);
                            
                            

                         }
                     });
                    return false;
                }); 
                     
                });
   

    }

    this.loadGPX = function()
    {        
        $.ajax(
        {
            type: "POST",
            url: "/ESB/JSON_RPC.mapaction_loadgpx",
            dataType: 'json',
            success: function(response)
            {                
                $('#jqi, #jqifade').remove();
        
                gpxFormPrompt = $.prompt(response.data,
                {
                    buttons: {},
                    submit: function()
                    {
                        $('#jqi, #jqifade').remove();
                        gpxForm.submit();
                        return true;
                     }
                }).corner();
        
                application.form();
                application.textareaCounter();
                
                $('#gpxloader_cancel_button').click(function()
                {
                    $('#jqi, #jqifade').remove();
                }); 
                
                gpxForm = $('#gpxForm').ajaxForm(
                {
                    dataType: 'text',
                    beforeSubmit: function()
                    { 
                        $.blockUI(
                        {
                            message: '<img src="/resources/images/animation/loader.gif" height="250" width="300" alt="lade" /> ',
                            css: { 
                                border: 'none', 
                                backgroundColor: 'transparent'
                            },
                            overlayCSS:  {  
                                backgroundColor:'white',  
                                opacity:        '0.6'  
                            },
                            allowBodyStretch: true, 
                            constrainTabKey: true
                        });
                                    
                        return true;
                    },
                    success: function(response)
                    { 
                        $.unblockUI();
                        
                        if (response != 'false')
                        {
                            $('#routedata_route_hidden').val(response);
                            $('#jqi, #jqifade').remove(); 
                        } else
                        {
                            $('#jqi, #jqifade').remove(); 
                        }
                    }
                });
            }
        });
    }
    
    
    
    this.addStep = function(point, type)
    {
        poilastm = point;
        
        $.ajax(
        {
            type: "POST",
            url: "/ESB/JSON_RPC.mapaction_addstep",
            data: {point: point, type: type},
            dataType: 'json',
            success: function(response)
            {                
                action.stepMessageBox(response.data);
                $('input#fotostep_pictitle2').hide();
            }
        });
    }
    
    this.stepMessageBox = function(data, mode)
    {
        $('#jqi, #jqifade').remove();
        
        stepFormPrompt = $.prompt(data,
        {
            buttons: {},
            submit: function()
            {
                $('#jqi, #jqifade').remove();
                stepForm.submit();
                return true;
             }
        }).corner();
        
        application.form();
        application.textareaCounter();
        action.addStepForm();
        
        if (mode == 'edit')
        {
            $('#fotostep_cancel_button, #housestep_cancel_button, #infostep_cancel_button').click(function()
            {
                $('#jqi, #jqifade').remove();
            }); 
        } else
        {
            $('#fotostep_cancel_button, #housestep_cancel_button, #infostep_cancel_button').click(function()
            {
                gis.removePOI(poimarkers[poilastm]);
                $('#jqi, #jqifade').remove();
            });
        }
    }
    
    this.addStepForm = function()
    {
        stepForm = $('#stepHouseForm, #stepFotoForm, #stepInfoForm').ajaxForm(
        {
            dataType: 'text',
            beforeSubmit: function()
            { 
                $.blockUI(
                {
                    message: '<img src="/resources/images/animation/loader.gif" height="250" width="300" alt="lade" /> ',
                    css: { 
                        border: 'none', 
                        backgroundColor: 'transparent'
                    },
                    overlayCSS:  {  
                        backgroundColor:'white',  
                        opacity:        '0.6'  
                    },
                    allowBodyStretch: true, 
                    constrainTabKey: true
                });
                            
                return true;
            },
            success: function(response)
            {       
                eval('var response='+response);
                if (response.title != undefined)
                {                 
                    $('img#roadbooktitleimage').attr('src', "/temp/images/tourtitlepics/" + response.title)
                }

                $.unblockUI();
                if (response.status != 'true')
                {
                    action.stepMessageBox(Base64.decode(response.data));
                } else
                {
                    switch (response.data.type)
                    {
                        case 'house':
                            var template = '<h1>' + response.data.headline + '</h1>';
                        break;
                        
                        case 'foto':
                            //var template = '<h1>' + response.data.headline + '</h1><p><img src="' + response.data.img + '" width="100" />' + response.data.text + '</p>';
                            var template = '<img src="' + response.data.img + '" width="100" />';
                        break;
                        
                        case 'info':
                            var template = '<h1>' + response.data.headline + '</h1><p>' + response.data.text + '</p>';
                        break;
                    }

                    if (response.info == true)
                    {
                        gis.openInfoWindow(poimarkers[poilastm], template, true);
                    }
                    
                    $('#jqi, #jqifade').remove(); 

                    if (response.steps)
                    {
                        if ($("fieldset#fieldset_routebook ol ul"))
                        {
                            $("fieldset#fieldset_routebook ol ul").remove();
                        }
                        $("fieldset#fieldset_routebook ol").append(Base64.decode(response.steps));
                        action.renderRoudbook();
                    }
                }
            }
        });
    }
    
    form = $('#actionAdminForm');
    
    form.ajaxForm(
    { 
        data: {rpcForm: 'true', rpcResponse: 'status'},
        success: function()
        {
            var now = new Date();
            if ($('fieldset#fieldset_actionsubmit ol li span.save').length > 0)
            {
                $('fieldset#fieldset_actionsubmit ol li span.save').html("(Zuletzt gespeichert um " + now.getHours() + ":" + now.getMinutes() + " Uhr)");
            } else
            {
                $('fieldset#fieldset_actionsubmit ol li button:eq(0)').before("<span class='save'>(Der Ausflug wurde soeben gespeichert)</span>");
            }
            
            setTimeout('$(\'#actionForm\').submit();', 300000);
        },
        beforeSubmit: function(data)
        { 
            if (!data[0].value)
            {
                $('#jqierrormsg, #jqierrormsgfade').remove();
                
                $.prompt('Bitte geben Sie zuerst den Titel des Ausflugs ein!', {prefix: 'jqierrormsg'}).corner();
                return false;
            }
                        
            return true;
        }
    });
    

    this.renderRoudbook();
    

    this.typeAction = function()
    {
        if ($('select#actionreport_type').length > 0)
        {
            
            $(this).find("select#actionreport_type").ready(function()
            {
                $.ajax(
                {
                    url: ('/ESB/JSON_RPC.type_select4'),
                    data: 'id=' + $(this).val(),
                    type: 'GET',
                    dataType: 'json',
                    
                    success: function(json)
                    {
                        var output = '';   
                                 
                        for (i = 0; i < json.length; i++)
                        {
                            $('select#actionreport_subtype').parent().show();        
                                   
                            output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                        }       
                         
                        if (output == "")
                        {
                            $('select#actionreport_subtype').parent().hide();   
    
                        }    
                           
                        $('select#actionreport_subtype').html(output);
                        
                        if (json == 'false')
                        {
                            $('select#actionreport_subtype').parent().hide();
                        } 
                    }
                })
            });
            
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select2'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {    
                    var output = '';   
                             
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#actionreport_subtype').parent().show();        
                               
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }       
                     
                    if (output == "")
                    {
                        $('select#actionreport_subtype').parent().hide();
                    }    
                       
                    $('select#actionreport_subtype').html(output);    
                }
            })
        }
        
        
        $('select#actionreport_type').change(function()
        {    
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {
                    var output = '';    
                                
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#actionreport_subtype').parent().show();
                        
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }
                    
                    if (output == "")
                    {
                        $('select#actionreport_subtype').parent().hide();
                    }
                    
                    $('select#actionreport_subtype').html(output);
                }
            })
        });
        
        
        if ($('select#fastinput_type').length > 0)
        {
            
            $(this).find("select#fastinput_type").ready(function()
            {
                $.ajax(
                {
                    url: ('/ESB/JSON_RPC.type_select5'),
                    data: 'id=' + $(this).val(),
                    type: 'GET',
                    dataType: 'json',
                    
                    success: function(json)
                    {
                        var output = '';   
                                 
                        for (i = 0; i < json.length; i++)
                        {
                            $('select#fastinput_subtype').parent().show();        
                                   
                            output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                        }       
                         
                        if (output == "")
                        {
                            $('select#fastinput_subtype').parent().hide();   
    
                        }    
                           
                        $('select#fastinput_subtype').html(output);
                        
                        if (json == 'false')
                        {
                            $('select#fastinput_subtype').parent().hide();
                        } 
                    }
                })
            });
            
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select2'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {    
                    var output = '';   
                             
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#fastinput_subtype').parent().show();        
                               
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }       
                     
                    if (output == "")
                    {
                        $('select#fastinput_subtype').parent().hide();
                    }    
                       
                    $('select#fastinput_subtype').html(output);    
                }
            })
        }
        

        
        $('select#fastinput_type').change(function()
        {    
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {
                    var output = '';    
                                
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#fastinput_subtype').parent().show();
                        
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }
                    
                    if (output == "")
                    {
                        $('select#fastinput_subtype').parent().hide();
                    }
                    
                    $('select#fastinput_subtype').html(output);
                }
            })
        });
        
        
        if ($('select#actionsearch_type').length > 0)
        {
            
            $('select#actionsearch_type').ready(function()
            {
                $.ajax(
                {
                    url: ('/ESB/JSON_RPC.type_select3'),
                    data: 'id=' + $(this).val(),
                    type: 'GET',
                    dataType: 'json',
                    
                    success: function(json)
                    {
                        var output = '';   
                                 
                        for (i = 0; i < json.length; i++)
                        {
                            $('select#actionsearch_subtype').parent().show();        
                                   
                            output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                        }       
                         
                        if (output == "")
                        {
                            $('select#actionsearch_subtype').parent().hide();   
    
                        }    
                           
                        $('select#actionsearch_subtype').html(output);
                        
                        if (json == 'false')
                        {
                            $('select#actionsearch_subtype').parent().hide();
                        } 
                    }
                })
            });
            
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select2'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {    
                    var output = '';   
                             
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#actionsearch_subtype').parent().show();        
                               
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }       
                     
                    if (output == "")
                    {
                        $('select#actionsearch_subtype').parent().hide();   

                    }    
                       
                    $('select#actionsearch_subtype').html(output);    
                }
            })
        }
        


        $('select#actionsearch_type').change(function()
        {    
            $.ajax(
            {
                url: ('/ESB/JSON_RPC.type_select'),
                data: 'id=' + $(this).val(),
                type: 'GET',
                dataType: 'json',
                
                success: function(json)
                {
                    var output = '';    
                                
                    for (i = 0; i < json.length; i++)
                    {
                        $('select#actionsearch_subtype').parent().show();
                        
                        output += '<option value=\"' + json[i].subValue + '\">' + json[i].subName + '</option>\n';
                    }
                    
                    if (output == "")
                    {

                        $('select#actionsearch_subtype').parent().hide();
                    }
                    
                    $('select#actionsearch_subtype').html(output);
                }
            })
        });
        
       
}
    
    this.typeAction();
}




function gis(map, dir)
{
    //var map;
    var dir;
    var polyline = [];
    var markers  = [];
    var redo     = [];
    var undoline = [];
    var line     = false;
    var handle;
    var magneticPolyHandle;
    var magneticStartPoint;
    var POIhandle;
    var POItype;
    var linelength = 0;
    var gpunkt;

        
    this.getPolyline = function()
    {
        return polyline;
    }
    
    this.startPOI = function(type)
    {
        POItype = type;
        
        POIhandle = GEvent.addListener(maps, "click", function(overlay, point)
        { 
            gis.addPOI(point);
        });
    }
    
    this.addTooltip = function(marker, html)
    {
        var tooltip = new Tooltip(marker,html,4);

        marker.tooltip = tooltip;

        map.addOverlay(tooltip);
        
        GEvent.addListener(marker,'mouseover',function()
        {
            this.tooltip.show();
        });
        
        GEvent.addListener(marker,'mouseout',function()
        {
            this.tooltip.hide();
        });
    }
    
    this.openInfoWindow = function(ss, data, show)
    {
        GEvent.addListener(ss, "click", function()
        {
            map.openInfoWindowHtml(this.getPoint(), data);
        });
        
        if (show)
        {
            map.openInfoWindowHtml(ss.getPoint(), data);
        }
    }
    
    this.startPoly = function()
    {
        if (handle)
        {
            handle = GEvent.removeListener(handle); 
        }
        
        handle = GEvent.addListener(maps, "click", function(overlay, point)
        { 
            gis.addPoint(point);
        });
    }
    
    this.stopPoly = function()
    {
        if (handle)
        {
            handle = GEvent.removeListener(handle); 
        }
    }

        
    this.addPOI = function(point, dontAddStep)
    {
        startpoint = new GIcon();
        
        switch (POItype)
        {
            case 'house':
                startpoint.image = "/resources/images/icons/silk/house.png";
            break;
            
            case 'foto':
                startpoint.image = "/resources/images/icons/silk/camera.png";
            break;
            
            case 'info':
                startpoint.image = "/resources/images/icons/silk/information.png";
            break;
        }
        
        
        startpoint.iconSize = new GSize(16, 16);
        startpoint.iconAnchor = new GPoint(10, 15);
    
        config = {type: "start", draggable: false, icon: startpoint};
        
        map.addOverlay(marker = this.createWaypoint(point, config)); 
        
        POIhandle = GEvent.removeListener(POIhandle); 
        
        poimarkers[point] = marker;
        
        if (!dontAddStep)
        {
            action.addStep(point, POItype);
        }
    }
    
    this.removePOI = function(marker)
    {
        map.removeOverlay(marker);
    }
    
    this.startMagneticPoly = function()
    {
        if (handle)
        {
            handle = GEvent.removeListener(handle); 
        }
        handle = GEvent.addListener(maps, "click", function(overlay, point)
        { 
            gis.addMagneticPoint(point);
        });
    }
    
    this.stopMagneticPoly = function()
    {
        if (handle)
        {
            handle = GEvent.removeListener(handle); 
        }
    }
    
    this.addMagneticPoint = function(point)
    {
        if (!markers[markers.length - 1])
        {
            gis.addPoint(point);
        } else
        {
            dir.loadFromWaypoints([markers[markers.length - 1].getPoint(), point], {getPolyline: true});
        }
    }
    
    this.onGDirectionsLoad = function()
    {
        var vertexPolyline = dir.getPolyline();
        var vertexCount = vertexPolyline.getVertexCount();

        undoline[undoline.length] = vertexPolyline.getVertex(0);
        
        for (var i = 0; i < vertexCount; i++)
        {
           if (vertexCount - 1 == i)
           {
               gis.addPoint(vertexPolyline.getVertex(i), 'true', true);
           } else
           {
               gis.addPoint(vertexPolyline.getVertex(i), 'false', true);
           }
           
        }
    }
    
    this.addPoint = function(point, redraw, dontundostep)
    {
        if (!dontundostep)
        {
            undoline[undoline.length] = point;
        }
        
        if (markers.length == 0)
        {
            startpoint = new GIcon();
            startpoint.image = "/resources/images/icons/silk/flag_green.png";
            startpoint.iconSize = new GSize(16, 16);
            startpoint.iconAnchor = new GPoint(10, 15);
        
            config = {type: "start", icon: startpoint};
        } else if (markers.length == 1)
        {
            endpoint = new GIcon();
            endpoint.image = "/resources/images/icons/silk/flag_red.png";
            endpoint.iconSize = new GSize(16, 16);
            endpoint.iconAnchor = new GPoint(10, 15);
        
            config = {type: "stop", icon: endpoint};
        } else
        {
            map.removeOverlay(markers[markers.length - 1]);
            
            if (redraw != 'false')
            {
                endpoint = new GIcon();
                endpoint.image = "/resources/images/icons/silk/flag_red.png";
                endpoint.iconSize = new GSize(16, 16);
                endpoint.iconAnchor = new GPoint(10, 15);
                
                config = {type: "stop", icon: endpoint};
            } else
            {
                config = {type: "stop"};
            }
        }

        markers.push(marker = this.createWaypoint(point, config));
        if (markers.length == 1)
        {
            gpunkt = marker
        }

        if (redraw != 'false')
        {
            map.addOverlay(marker); 
            this.renderPolyline();
        }

        $('#routedata_route_hidden').val(polyline);
    }
    
    this.removeLastPoint = function()
    {        
        if (undoline.length > 0)
        {
            map.removeOverlay(markers[markers.length - 1]);

            i = 1;
            r = true;
            while (r)
            {
                if (markers[markers.length - 1].getPoint().x == undoline[undoline.length - 1].x && markers[markers.length - 1].getPoint().y == undoline[undoline.length - 1].y)
                {
                    undoline.remove(undoline.length - 1);
                    r = false;
                }                
                markers.remove(markers.length - 1);
                
                i++;
            }

            point = new GIcon();
            point.iconSize = new GSize(16, 16);
            point.iconAnchor = new GPoint(10, 15);
                
            if (markers.length > 1)
            {
                point.image = "/resources/images/icons/silk/flag_red.png";
            } else
            {
                point.image = "/resources/images/icons/silk/flag_green.png";
            }
                        
            if (markers.length > 0)
            {
                prevPoint = markers[markers.length - 1].getPoint();
                markers[markers.length - 1] = this.createWaypoint(prevPoint, {type: "waypoint", draggable: false, icon: point});
                map.addOverlay(markers[markers.length - 1]);
            }
        } else
        {
             map.removeOverlay(gpunkt);
        }
        
        this.renderPolyline();
        
       
    }
    
    this.redrawRoute = function(route)
    {        
        var center = false;
        var points = route.split ('),');
       
        for (var i = 0; i < points.length; i++)
        {
            var latlng = points[i].split(',');

            if (center == false)
            {                
                if (distance <= 3)
                {
                	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 13);
                } else if (distance <= 10)
                {
	            	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 12);
                } else if (distance <= 18)
                {
                	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 11);
                } else if (distance <= 35)
                {
                	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 10);
                } else if (distance <= 60)
                {
                	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 9);
                } else
                {
                	map.setCenter(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 8);
                }
                center = true;

            }
            this.addPoint(new GLatLng(latlng[0].replace(/\(/g, ""), latlng[1].replace(/\)/g, "")), 'false');
        }
        
        this.renderPolyline();
    }
    
    this.redrawLastPoint = function()
    {
        if (redo.length > 0)
        {
            this.addPoint(redo[redo.length - 1]);
            redo.remove(redo.length - 1);
        }
    }

    this.renderPolyline = function()
    {
        polyline = [];
        var distanceSummary = 0;
        
        for (var i = 0; i < markers.length; i++)
        {
            polyline.push(markers[i].getPoint());
            
            if (i > 0)
            {
                pw_xx = markers[i - 1].getPoint().y;
                pw_yy = markers[i - 1].getPoint().x; 
                sw_xx = markers[i].getPoint().y;
                sw_yy = markers[i].getPoint().x;

                distance  = Math.atan2(Math.sqrt(Math.pow(Math.cos(Math.deg2rad(pw_xx)) * Math.sin(Math.deg2rad(sw_yy - pw_yy)), 2) 
                            + Math.pow(Math.cos(Math.deg2rad(sw_xx)) * Math.sin(Math.deg2rad(pw_xx)) 
                            - Math.sin(Math.deg2rad(sw_xx)) * Math.cos(Math.deg2rad(pw_xx)) * Math.cos(Math.deg2rad(sw_yy - pw_yy)), 2)), (Math.sin(Math.deg2rad(sw_xx)) * Math.sin(Math.deg2rad(pw_xx)) 
                            + Math.cos(Math.deg2rad(sw_xx)) * Math.cos(Math.deg2rad(pw_xx)) * Math.cos(Math.deg2rad(sw_yy - pw_yy)))) * 6372.795;
                
                distanceSummary = distanceSummary + distance;
            }
        }
        
        if (distanceSummary != 0)
        {
        
            if ( $("span#mapaction_distance").length <= 0 )
            {
                $('#fieldset_mapaction').append($.create("span", {"id": "mapaction_distance"}, []));
            }
    
            distanceSummary = (Math.round(distanceSummary * 1000) / 1000)+'';
            distanceSummary = distanceSummary.split('.');
                    
            if (distanceSummary[0] != 0 && distanceSummary[1] != 0)
            {
                $("span#mapaction_distance").html("Die Strecke ist " + distanceSummary[0] + " Kilometer und " + distanceSummary[1] + " Meter lang.");
            } else if (distanceSummary[0] != 0)
            {
                $("span#mapaction_distance").html("Die Strecke ist " + distanceSummary[0] + " Kilometer lang.");
            } else if (distanceSummary[1] != 0)
            {
                $("span#mapaction_distance").html("Die Strecke ist " + distanceSummary[1] + " Meter lang.");
            }
        } else
        {
            $("span#mapaction_distance").html("");
        }
        
        $('#routedata_route_hidden').val(polyline);
        
        map.removeOverlay(line);
        line = new GPolyline(polyline, "#e5007e", 4, 0.6);
        map.addOverlay(line);
    }
    
    this.undo = function()
    {
        this.removeLastPoint();
    }
    
    this.redo = function()
    {
        this.redrawLastPoint();
    }
        
    this.createWaypoint = function(point, config)
    { 
        marker = new GMarker(point, config); 
        return marker;
    }
    
    this.redrawPOIs = function()
    {
        $("fieldset#fieldset_routebook ol ul li, #mapview_routebook li").each(function()
        {
            var steptype = $(this).find('.steptype').html();
            var steppoint = $(this).find('.steppoint').html();
            var steptext = $(this).find('.steptext').html();
            var steptitle = $(this).find('h1').html();
            var stepimage = $(this).find('.foto').attr('src');
            
            startpoint = new GIcon();
            
            switch (steptype)
            {
                case 'house':
                    startpoint.image = "/resources/images/icons/silk/house.png";
                    var template = '<h1>' + steptitle + '</h1>';
                break;
                
                case 'foto':
                    startpoint.image = "/resources/images/icons/silk/camera.png";
                    var template = '<h1>' + steptitle + '</h1><p><img src="' + stepimage + '" width="100" />' + steptext + '</p>';
                break;
                
                case 'info':
                    startpoint.image = "/resources/images/icons/silk/information.png";
                    var template = '<h1>' + steptitle + '</h1><p>' + steptext + '</p>';
                break;
            }

           
            
            startpoint.iconSize = new GSize(16, 16);
            startpoint.iconAnchor = new GPoint(10, 15);

            steppoint = steppoint.split(',');
    
            map.addOverlay(pmarker = new GMarker(point = new GPoint(steppoint[1], steppoint[0]), {type: "poi", draggable: false, icon: startpoint})); 
            poimarkers['(' + point.y + ',' + point.x + ')'] = pmarker;
            
            gis.openInfoWindow(pmarker, template, false);
        })
    }
    
    this.drawIndexPOIs = function()
    {
        da = $('#mapindex_route').html().split(';');

        for (var i = 0; i < da.length; i = i+8)
        {
            switch(1 + parseInt( Math.random() * ( 5-1+1)))
            {
                case 1:
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-1.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-1.png";
                    startpoint.iconSize = new GSize(44.0, 39.0);
                    startpoint.shadowSize = new GSize(64.0, 39.0);
                    startpoint.iconAnchor = new GPoint(22.0, 19.0);
                    startpoint.infoWindowAnchor = new GPoint(22.0, 19.0);
                break;   
    
                case 2:
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-2.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-2.png";
                    startpoint.iconSize = new GSize(40.0, 35.0);
                    startpoint.shadowSize = new GSize(58.0, 35.0);
                    startpoint.iconAnchor = new GPoint(20.0, 17.0);
                    startpoint.infoWindowAnchor = new GPoint(20.0, 17.0);
                break;   
    
                case 3:
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-3.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-3.png";
                    startpoint.iconSize = new GSize(21.0, 52.0);
                    startpoint.shadowSize = new GSize(48.0, 52.0);
                    startpoint.iconAnchor = new GPoint(10.0, 26.0);
                    startpoint.infoWindowAnchor = new GPoint(10.0, 26.0);
                break;   
    
                case 4:
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-4.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-4.png";
                    startpoint.iconSize = new GSize(25.0, 42.0);
                    startpoint.shadowSize = new GSize(47.0, 42.0);
                    startpoint.iconAnchor = new GPoint(12.0, 21.0);
                    startpoint.infoWindowAnchor = new GPoint(12.0, 21.0);
                break;   
    
                case 5:
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-5.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-5.png";
                    startpoint.iconSize = new GSize(22.0, 40.0);
                    startpoint.shadowSize = new GSize(43.0, 40.0);
                    startpoint.iconAnchor = new GPoint(11.0, 20.0);
                    startpoint.infoWindowAnchor = new GPoint(11.0, 20.0);
                break;   
            }

            steppoint = da[i].split(',');
            
            map.addOverlay(pmarker = new GMarker(new GPoint(steppoint[1], steppoint[0]), {type: "tour", draggable: false, icon: startpoint, title: da[i+1]}));
			if (da[i+6] == "dummytour")
			{
           		gis.openInfoWindow(pmarker, '<img src="/resources/images/animation/dummy-tour-1.jpg" width="150" /><br /><a href=/ausflug/'+da[i+2]+' style="color: #DE761F">'+ da[i+1] +'</a><br />Autor: '+ da[i+5] +'<br />Tourtyp: '+ da[i+3] +'<br />Schwierigkeit: '+ da[i+4], false);
			}
			if	(da[i+6] == "upload")
			{
           		gis.openInfoWindow(pmarker, '<img src="/temp/images/tourtitlepics/'+ da[i+2] +'.'+ da[i+7] +'" width="150" /><br /><a href=/ausflug/'+da[i+2]+' style="color: #DE761F">'+ da[i+1] +'</a><br />Autor: '+ da[i+5] +'<br />Tourtyp: '+ da[i+3] +'<br />Schwierigkeit: '+ da[i+4], false);
		
			}
        }
    }

    if ($('#routedata_route_hidden').val() != '' && $('#routedata_route_hidden').val() != undefined)
    {         
        this.redrawRoute($('#routedata_route_hidden').val());
    }
    if ($('#routedata_firstpoint_hidden').val() != '' && $('#routedata_firstpoint_hidden').val() != undefined)
    {
		var point = $('#routedata_firstpoint_hidden').val();
        map.setCenter(new GLatLng(point.substr(1, point.indexOf(', ') -1), point.substring(point.indexOf(', ') +1, point.indexOf(')') )), 12);
        
                    startpoint = new GIcon();
                    startpoint.image = "/resources/images/animation/map-pin-5.png";
                    startpoint.shadow = "/resources/images/animation/shadow-map-pin-5.png";
                    startpoint.iconSize = new GSize(22.0, 40.0);
                    startpoint.shadowSize = new GSize(43.0, 40.0);
                    startpoint.iconAnchor = new GPoint(11.0, 20.0);
                    startpoint.infoWindowAnchor = new GPoint(11.0, 20.0);
        
        map.addOverlay(pmarker = new GMarker(new GLatLng(point.substr(1, point.indexOf(', ') -1), point.substring(point.indexOf(', ') +1, point.indexOf(')') )), {type: "tour", draggable: false, icon: startpoint}));
    }

    
    if ($('#mapview_route').html() != '' && $('#mapview_route').html() != undefined)
    { 
        this.redrawRoute($('#mapview_route').html());
    }
    
    if ($('#mapindex_route').html() != '' && $('#mapindex_route').html() != undefined)
    {   
        setTimeout('gis.drawIndexPOIs();', 500);
    }
    
    setTimeout('gis.redrawPOIs();', 1000);
}



var Tooltip;

function buildMaps()
{

    $("#mapaction_map").parents('li').addClass('nopadding');
    $("#mapaction_map").each(function()
    {
        maps = new GMap2(this, {draggableCursor: 'crosshair'});
        
       	maps.setCenter(new GLatLng(application.session('latitude'), application.session('longitude')), 12);    
               
        Tooltip = function(marker, text, padding)
        {
            this.marker_ = marker;
            this.text_ = text;
            this.padding_ = padding;
        }
        
        Tooltip.prototype = new GOverlay();
        
        Tooltip.prototype.initialize = function(map)
        {
            var div = document.createElement("div");
            div.innerHTML = this.text_;
            div.className = 'tooltip';
            div.style.position = 'absolute';
            div.style.visibility = 'hidden';
            map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
            this.map_ = map;
            this.div_ = div;
        }
        
        Tooltip.prototype.remove = function()
        {
            this.div_.parentNode.removeChild(this.div_);
        }
        
        Tooltip.prototype.copy = function()
        {
            return new Tooltip(this.marker_,this.text_,this.padding_);
        }
        
        Tooltip.prototype.redraw = function(force)
        {
            if (!force) return;
            var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
            var iconAnchor = this.marker_.getIcon().iconAnchor;
            var xPos = Math.round(markerPos.x - this.div_.clientWidth / 2);
            var yPos = markerPos.y - iconAnchor.y - this.div_.clientHeight - this.padding_ - 20;
            this.div_.style.top = yPos + 'px';
            this.div_.style.left = xPos + 'px';
        }
        
        Tooltip.prototype.show = function()
        {
            this.div_.style.visibility = 'visible';
        }
        
        Tooltip.prototype.hide = function()
        {
            this.div_.style.visibility = 'hidden';
        }

        
        function control()
        {
        }
        
        control.prototype = new GControl();
        
        control.prototype.initialize = function(map)
        {
            var container = $.create(
                "div", {style: "-moz-user-select: none; position: absolute; left: 7px; top: 7px; color: black; font-family: Arial,sans-serif; font-size: small; width: 160px; height: 19px;"});
            /*         
            var MoveMapDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 0; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/misc/cursor-hand.png", "title": "Karte verschieben"}, [
                        ""]
            ]]);       
            container.appendChild(MoveMapDiv);
            GEvent.addDomListener(MoveMapDiv, "click", function()
            {
                gis.stopMagneticPoly();
                gis.stopPoly();
            });
            */
            var UndoDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 0; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/arrow_undo.png", "title": "Letzten Punkt löschen"}, [
                        ""]
            ]]);       
            container.appendChild(UndoDiv);
            GEvent.addDomListener(UndoDiv, "click", function()
            {
                gis.undo();
            });
            /*
            var RedoDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 48px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/arrow_redo.png", "title": "Letzten Punkt wiederherstellen"}, [
                        ""]
            ]]);       
            container.appendChild(RedoDiv);
            GEvent.addDomListener(RedoDiv, "click", function()
            {
                gis.redo();
            });
            */
            var DrawPolyDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 30px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/chart_line.png", "title": "Streckenpunkte einzeichnen"}, [
                        ""]
            ]]);       
            container.appendChild(DrawPolyDiv);
            GEvent.addDomListener(DrawPolyDiv, "click", function()
            {
                gis.stopMagneticPoly();
                gis.startPoly();
            });

            var DrawMagneticPolyDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 55px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/vector.png", "title": "Streckenpunkte am Straßenverlauf einzeichnen"}, [
                        ""]
            ]]);       
            container.appendChild(DrawMagneticPolyDiv);
            GEvent.addDomListener(DrawMagneticPolyDiv, "click", function()
            {
                gis.stopPoly();
                gis.startMagneticPoly();
            });
            
            var DrawPointHouseDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 85px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/house.png", "title": "Tipp einzeichnen"}, [
                        ""]
            ]]);       
            container.appendChild(DrawPointHouseDiv);
            GEvent.addDomListener(DrawPointHouseDiv, "click", function()
            {
                gis.stopMagneticPoly();
                gis.stopPoly();
                gis.startPOI('house');
            });
            
            var DrawPointFotoDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 110px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/camera.png", "title": "Fotopunkt einzeichnen"}, [
                        ""]
            ]]);       
            container.appendChild(DrawPointFotoDiv);
            GEvent.addDomListener(DrawPointFotoDiv, "click", function()
            {
                gis.stopMagneticPoly();
                gis.stopPoly();
                gis.startPOI('foto');
            });
            
            var DrawPointInfoDiv = $.create(
                "div", {"style": "border: 1px solid black; position: absolute; background-color: white; text-align: center; width: 20px; left: 135px; cursor: pointer;"}, [
                    "div", {"style": "border-style: solid; border-color: white rgb(176, 176, 176) rgb(176, 176, 176) white; border-width: 1px; font-size: 12px;"}, [
                        "img", {"src": "/resources/images/icons/silk/information.png", "title": "Infopunkt einzeichnen"}, [
                        ""]
            ]]);       
            container.appendChild(DrawPointInfoDiv);
            GEvent.addDomListener(DrawPointInfoDiv, "click", function()
            {
                gis.stopMagneticPoly();
                gis.stopPoly();
                gis.startPOI('info');
            });
            
            map.getContainer().appendChild(container);
            return container;
        }
        
        control.prototype.getDefaultPosition = function()
        {
            return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 7));
        }
        
        maps.removeMapType(G_SATELLITE_MAP);
        maps.addMapType(G_PHYSICAL_MAP);
        maps.setMapType(G_PHYSICAL_MAP);
        maps.enableContinuousZoom();
        maps.enableScrollWheelZoom();
        maps.enableDoubleClickZoom();
        maps.addControl(new GMapTypeControl());
        maps.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,40)));
        maps.addControl(new GOverviewMapControl(new GSize(179,120)));
        maps.addControl(new control());
        
        dirs = new GDirections();
        gis = new gis(maps, dirs);
        
        GEvent.addListener(dirs, "load", gis.onGDirectionsLoad);
        GEvent.addListener(dirs, "error", gis.handleErrors);
        GEvent.addDomListener(maps.getContainer(), "DOMMouseScroll", function(oEvent)
        {
            if (oEvent.preventDefault)
            {
                oEvent.preventDefault();
            }
        }); 
    });
    
    $("#mapview_map").each(function()
    {
        maps = new GMap2(this);
                
        maps.setCenter(new GLatLng(application.session('latitude'), application.session('longitude')), 12);
        
        maps.removeMapType(G_SATELLITE_MAP);
        maps.addMapType(G_PHYSICAL_MAP);
        maps.setMapType(G_PHYSICAL_MAP);
        maps.enableContinuousZoom();
        maps.enableScrollWheelZoom();
        maps.enableDoubleClickZoom();
        maps.addControl(new GMapTypeControl());
        maps.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,40)));
        maps.addControl(new GOverviewMapControl(new GSize(179,120)));

        dirs = new GDirections();
        gis = new gis(maps, dirs);
        
        GEvent.addListener(dirs, "load", gis.onGDirectionsLoad);
        GEvent.addListener(dirs, "error", gis.handleErrors);
        GEvent.addDomListener(maps.getContainer(), "DOMMouseScroll", function(oEvent)
        {
            if (oEvent.preventDefault)
            {
                oEvent.preventDefault();
            }
        }); 
    });
    
    $("#mapindex_map").each(function()
    {
        maps = new GMap2(this);
        
        maps.setCenter(new GLatLng('48.101431', '11.00798'), 8);
        
        maps.removeMapType(G_SATELLITE_MAP);
        maps.addMapType(G_PHYSICAL_MAP);
        maps.setMapType(G_PHYSICAL_MAP);

        dirs = new GDirections();
        gis = new gis(maps, dirs);
    });

}


























var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/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;
    },

    // private method for UTF-8 decoding
    _utf8_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;
    }

}



Array.prototype.remove = function(from, to)
{
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

Math.deg2rad = function ( x ) {
        return x * (Math.PI / 180.0); 
}


jQuery.fn.overlabel = function() {
    this.each(function(index) {
        var label = $(this); var field;
        var id = this.htmlFor || label.attr('for');
        if (id && (field = document.getElementById(id))) {
            var control = $(field);
            label.addClass("overlabel-apply");
            if (field.value !== '') {
                label.css("text-indent", "-1000px");
            }
            control.focus(function () {label.css("text-indent", "-1000px");}).blur(function () {
                if (this.value === '') {
                    label.css("text-indent", "0px");
                }
            });
            label.click(function() {
                var label = $(this); var field;
                var id = this.htmlFor || label.attr('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            });
        }
    });
};










