/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008/05/26 $
 * $Rev: 5685 $
 */
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}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);return jQuery(elem);}selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",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;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);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 this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},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;}if(value.constructor==Number)value+='';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=jQuery.makeArray(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[0]?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===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&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.fn.init.prototype=jQuery.fn;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);}function now(){return+new Date;}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==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};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&&/^[\s[]?function/.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.insertBefore(script,head.firstChild);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){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var 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,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;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":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(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 left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}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+='';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 notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
while(i)ret[--i]=array[i];}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){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
while(elem=second[i++])first[pos++]=elem;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))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)ret[ret.length]=value;}return ret.concat.apply([],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,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});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");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}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,re=quickChild,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=[],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&&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)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});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({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&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,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.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;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},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;event.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;event.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){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,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){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;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.call(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:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._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=now();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:{url:location.href,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){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="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&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){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 xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);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(jQuery.isFunction(a[j])?a[j]():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.apply(this,arguments):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),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(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.call(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){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",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].call(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:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(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.call(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=now();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=now();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)this.options.complete.call(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.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},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),css=jQuery.curCSS,fixed=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&&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(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&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,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'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)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();

/*
 * Extracted from Prototype JS Library, http://prototype.conio.net/ Written by
 * Sam Stephenson, http://conio.net/
 */
function _gel() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string') element = (document.getElementById) ? document.getElementById(element) : eval("document.all."+element) ;
    if (arguments.length == 1) return element;
    elements.push(element);
  }
  return elements;
}
/* Function to remove all child nodes of an element. */
function clean(elm) {
	while(_gel(elm).hasChildNodes()) {
		_gel(elm).removeChild(_gel(elm).childNodes[0]);
	}
	return true;
}


//  This file is part of the jQuery formatCurrency Plugin.
//
//    The jQuery formatCurrency Plugin is free software: you can redistribute it
//    and/or modify it under the terms of the GNU General Public License as published 
//    by the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.

//    The jQuery formatCurrency Plugin is distributed in the hope that it will
//    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty 
//    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along with 
//    the jQuery formatCurrency Plugin.  If not, see <http://www.gnu.org/licenses/>.

(function($) {

	$.formatCurrency = {};

	$.formatCurrency.regions = [];

	// default Region is en
	$.formatCurrency.regions[''] = {
		symbol: '$',
		positiveFormat: '%s%n',
		negativeFormat: '(%s%n)',
		decimalSymbol: '.',
		digitGroupSymbol: ',',
		groupDigits: true
	};

	$.fn.formatCurrency = function(destination, settings) {

		if (arguments.length == 1 && typeof destination !== "string") {
			settings = destination;
			destination = false;
		}

		// initialize defaults
		var defaults = {
			name: "formatCurrency",
			colorize: false,
			region: '',
			global: true,
			roundToDecimalPlace: 2, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ...
			eventOnDecimalsEntered: false
		};
		// initialize default region
		defaults = $.extend(defaults, $.formatCurrency.regions['']);
		// override defaults with settings passed in
		settings = $.extend(defaults, settings);

		// check for region setting
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);

		return this.each(function() {
			$this = $(this);

			// get number
			var num = '0';
			num = $this[$this.is('input, select, textarea') ? 'val' : 'html']();

			//identify '(123)' as a negative number
			if (num.search('\\(') >= 0) {
				num = '-' + num;
			}

			if (num === '') {
				return;
			}

			// if the number is valid use it, otherwise clean it
			if (isNaN(num)) {
				// clean number
				num = num.replace(settings.regex, '');
				
				if (num === '') {
					return;
				}
				
				if (settings.decimalSymbol != '.') {
					num = num.replace(settings.decimalSymbol, '.');  // reset to US decimal for arithmetic
				}
				if (isNaN(num)) {
					num = '0';
				}
			}
			
			// evalutate number input
			var numParts = String(num).split('.');
			var isPositive = (num == Math.abs(num));
			var hasDecimals = (numParts.length > 1);
			var decimals = (hasDecimals ? numParts[1].toString() : '0');
			var originalDecimals = decimals;
			
			// format number
			num = Math.abs(numParts[0]);
			if (settings.roundToDecimalPlace >= 0) {
				decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
				decimals = decimals.toFixed(settings.roundToDecimalPlace); // round
				if (decimals.substring(0, 1) == '2') {
					num = Number(num) + 1;
				}
				decimals = decimals.substring(2); // remove "0."
			}
			num = String(num);

			if (settings.groupDigits) {
				for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
					num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
				}
			}

			if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
				num += settings.decimalSymbol + decimals;
			}

			// format symbol/negative
			var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
			var money = format.replace(/%s/g, settings.symbol);
			money = money.replace(/%n/g, num);

			// setup destination
			var $destination = $([]);
			if (!destination) {
				$destination = $this;
			} else {
				$destination = $(destination);
			}
			// set destination
			$destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money);

			if (hasDecimals && settings.eventOnDecimalsEntered) {
				$destination.trigger('decimalsEntered', originalDecimals);
			}

			// colorize
			if (settings.colorize) {
				$destination.css('color', isPositive ? 'black' : 'red');
			}
		});
	};

	// Remove all non numbers from text
	$.fn.toNumber = function(settings) {
		var defaults = $.extend({
			name: "toNumber",
			region: '',
			global: true
		}, $.formatCurrency.regions['']);

		settings = jQuery.extend(defaults, settings);
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);

		return this.each(function() {
			var method = $(this).is('input, select, textarea') ? 'val' : 'html';
			$(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, ''));
		});
	};

	// returns the value from the first element as a number
	$.fn.asNumber = function(settings) {
		var defaults = $.extend({
			name: "asNumber",
			region: '',
			parse: true,
			parseType: 'Float',
			global: true
		}, $.formatCurrency.regions['']);
		settings = jQuery.extend(defaults, settings);
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);
		settings.parseType = validateParseType(settings.parseType);

		var method = $(this).is('input, select, textarea') ? 'val' : 'html';
		var num = $(this)[method]();
		num = num ? num : "";
		num = num.replace('(', '(-');
		num = num.replace(settings.regex, '');
		if (!settings.parse) {
			return num;
		}

		if (num.length == 0) {
			num = '0';
		}

		if (settings.decimalSymbol != '.') {
			num = num.replace(settings.decimalSymbol, '.');  // reset to US decimal for arthmetic
		}

		return window['parse' + settings.parseType](num);
	};

	function getRegionOrCulture(region) {
		var regionInfo = $.formatCurrency.regions[region];
		if (regionInfo) {
			return regionInfo;
		}
		else {
			if (/(\w+)-(\w+)/g.test(region)) {
				var culture = region.replace(/(\w+)-(\w+)/g, "$1");
				return $.formatCurrency.regions[culture];
			}
		}
		// fallback to extend(null) (i.e. nothing)
		return null;
	}

	function validateParseType(parseType) {
		switch (parseType.toLowerCase()) {
			case 'int':
				return 'Int';
			case 'float':
				return 'Float';
			default:
				throw 'invalid parseType';
		}
	}
	
	function generateRegex(settings) {
		if (settings.symbol === '') {
			return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
		}
		else {
			var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.');		
			return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
		}	
	}

})(jQuery);


/*
 * Function to handle cross-browser HTTPRequest calls. Written by Dan Bogaard,
 * www.rit.edu/~dsbics
 */
function getHTTP() {
	var xmlhttp;
	if(window.XMLHttpRequest) {
		try {
			xmlhttp = new XMLHttpRequest();
			xmlhttp.overrideMimeType("text/xml");
		} catch(e) { xmlhttp = false;	}
	} else if(window.ActiveXObject) {	// if this is IE,
		// try to set the variable to activeX xmlhttp object
		try {	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch(e) {
			try {	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");	}
			catch(e) { xmlhttp = false;	}
		}
	}
	return xmlhttp;
}

/*
 * Function to grab all elements with a specific class name. Original written by
 * Jonathan Snook, http://www.snook.ca/jonathan Add-ons by Robert Nyman,
 * http://www.robertnyman.com Re-written by Zack Gilbert of Seen Creative,
 * http://www.weareseencreative.com
 */
function getElementsByClass(className, elm, tag){
	if(elm == null) elm = document;
	if(tag == null) tag = '*';
	var elems = elm.getElementsByTagName(tag);
	var returnElems = new Array();
	className = className.replace(/\-/g, "\\-");
	var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
	for(var i=0; i<elems.length; i++){
		if(pattern.test(elems[i].className)) returnElems.push(elems[i]);
	}
	return returnElems
}

/*
 * Function to return the class attribute. IE and all other standards compliant
 * browsers have different names for the class attribute object.
 */
function classAttr(){
	if (browser == IE ){
		class_att = 'className';
	}
	else {
		class_att = 'class';
	}

	return class_att;

}
/*
 * Functions to add/remove event listeners to objects Written by John Resig,
 * http://ejohn.org
 */
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) obj.addEventListener( type, fn, false );
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn ) {
	if (obj.removeEventListener) obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent) {
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}
/*
 * Functions to handle cross-browser events. Written by Zack Gilbert of Seen
 * Creative, http://www.weareseencreative.com.
 */
/* get the target of an event object */
function getTarget(e) {
	return (e.target) ? e.target : e.srcElement;
}
/* get the X location of an object */
function getX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x)	curleft += obj.x;
	// alert(curleft);
	return curleft;
}
/* get the Y location of an object */
function getY(obj){
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y)	curtop += obj.y;
	// alert(curtop);
	return curtop;
}
/* get the height of an element */
function getHeight(id){
    var elemHeight = _gel(id).offsetHeight;

    return elemHeight;
}

/* get the width of an element */
function getWidth(id){
    var elemWidth = _gel(id).offsetHeight;

    return elemWidth;
}

function getKey(e) {
	code = false;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code;
}
// this function is used to stop events from acting normally.
// NOTE: Safari supports these functions, but does not work properly!
function killKey(e) {
	(e.preventDefault) ? e.preventDefault() : window.event.returnValue = false;
	(e.stopPropagation) ? e.stopPropagation() : window.event.cancelBubble = true;
	return false;
}

/* Function to get object attribute text */
function getObjectAttribute(obj,attr){
	var attrValue = obj.getAttribute(attr);
	return attrValue;
}

/* Function to get img extension */
function getImgExt(obj){
	var src = obj.getAttribute('src');

	var imgExtPosition = src.lastIndexOf('.') + 1;	// Get the extension. Add 1
													// to get only the
													// extension, not .extension

	var extension;

	if(src.match('clearpixel.gif')){	// If IE and the image is a PNG, return
										// 'png', because the PNG transparency
										// function causes the img src to be
										// clearpixel.gif.
		extension = 'png';
	}

	else {
		var extension = src.slice(imgExtPosition);
	}

	return extension;
}

/* Begin functions dealing with Cookies */
function getCookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = name+"="+escape(value) +
		((expires) ? ";expires="+expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}
/* End functions dealing with Cookies */

/* Begin get URL parameter functions */
function getURLParameters(action) {
	var sURL = window.document.URL.toString();

	if (sURL.indexOf("?") > 0){
		var qsvs;
		// Split the url at the beginning of the query string.
		var arrParams = sURL.split("?");

		// Split the query string into name/value pairs.
		var fullqs = arrParams[1];
		var arrURLParams = fullqs.split("&");

		// Create 2 new arays to hold the parameter name and parameter value.
		var paramNames = new Array();
		var paramValues = new Array();

		for (var j=0;j<arrURLParams.length;j++) {
			// Split the name/value pairs into name and value.
			var sParam =  arrURLParams[j].split("=");

			// Set the value of the parameter name array.
			var arrParamNames = sParam[0];
			// Set the value of the parameter value array.
			var arrParamValues = unescape(sParam[1]);

			// Generate the arrays using the parameter names and parameter
			// values.
			paramNames.push(arrParamNames);
			paramValues.push(arrParamValues);
		}
		qsvs = paramValues[0];
	}

	else {
		qsvs;
	}

	/***************************************************************************
	 * If action equals 'split', we want to return the value of the split query
	 * string. Currently, we are only concerned with the value of the position.
	 * If action does not equal 'split', we want to return the entire query
	 * string as one long string to be passed to a Flash movie. 05/03/06
	 **************************************************************************/
	if (action == 'split'){
		return qsvs;
	}
	else {
		return fullqs;
	}
}
/* End get URL parameter functions */

/* Begin get URL parameter by name function */
function getURLParameterByName(name) {
    var sURL = window.document.URL.toString();

    if (sURL.indexOf("?") > -1){

	    // Split the url at the beginning of the query string.
	    var arrParams = sURL.split("?");

	    // Split the query string into name/value pairs.
	    var fullqs = arrParams[1];
	    var arrURLParams = fullqs.split("&");

	    for (var j=0;j<arrURLParams.length;j++) {

	        if(arrURLParams[j].indexOf(name) > -1){
		        // Split the name/value pairs into name and value.
		        var qsValue =  arrURLParams[j].split("=")[1];
	            return qsValue;
		        break;
		    }
	    }
    }
}
/* End get URL parameter by name function */

/** *** Begin clear value functions **** */

function clearValue(){
    this.value = "";
    removeEvent(this,"click",clearValue);
    removeEvent(this,"focus",clearValue);

    // Remove the class that also sets the style for the input before the value
	// is cleared.
    var classValue = this.getAttribute(classAttribute);
    var newClassValue = classValue.replace('clear-value','','gi');
    this.setAttribute(classAttribute, newClassValue);

}

/** *** End clear value functions **** */

function getCurrentPage() { // Get the page
	var sURL = window.document.URL.toString();

	var arrURL = sURL.split("http://");
	var arrURLParts = arrURL[1].split("/");
	var arrURLPage = arrURLParts.length;
	arrURLPage--;

	switch(arrURLParts[arrURLPage]) {
		case "file name":
			// Do something
			break
		default:
		;
	}
}

var browser = navigator.appName;
var versionInfo = navigator.appVersion;
var versionNum = parseFloat(versionInfo);
var vendor = navigator.vendor;
var IE = "Microsoft Internet Explorer";
var IE6 = "MSIE 6.0";
var IE7 = "MSIE 7.0";
var safari = "Apple Computer, Inc.";
var imagePath = "images/";
var classAttribute = classAttr();   // Get the appropriate class attribute to
									// set. IE and Firefox use different
									// attributes for class in the DOM.

/** *** Begin preload images **** */
var origImg = new Array();	// Array of images for rollovers
origImg[0] = '';

var overImg = new Array();	// Array of images to preload
overImg[0] = '';

var preloadFlag = false;
function preloadImages() {
	for (i=0; i<overImg.length; i++) {
		var images = new Array();
		images[i] = new Image();
		images[i].src = imagePath + overImg[i];
	}
	preloadFlag = true;
}
/** *** End preload images **** */

/** *** Begin image rollover funtion **** */
/* Function to initalize rollover */
function initRollovers(){
	var rollovers = getElementsByClass('rollover',null,null);	// Get elements
																// with a class
																// of "rollover"

	if (rollovers.length > 0){		// If there is at least one element with a
									// class "rollover"
		for(var i=0;i<rollovers.length;i++){	// Loop through all elements
												// with class "rollover"
			var classValue = rollovers[i].getAttribute(classAttribute);

			if((versionInfo.match(IE6) != null) && (classValue.match('tpng') != null) ){ // If
																							// the
																							// browser
																							// is
																							// IE6
																							// and
																							// a
																							// transparent
																							// png
				addEvent(rollovers[i],'mouseover',rolloverPNG);	// Attach
																// mouseover
																// event
				addEvent(rollovers[i],'mouseout',rolloverPNG);	// Attach
																// mouseout
																// event
			}
			else {
				addEvent(rollovers[i],'mouseover',rollover);	// Attach
																// mouseover
																// event
				addEvent(rollovers[i],'mouseout',rollover);	// Attach mouseout
															// event
			}
		}
	}
}

// This function grabs the src attribute and replaces "off" with "on" (for
// mouseover) or "on" with "off (for mouseout) in the attribute string. KM
function rollover(event) {
	var etype = event.type;
	var imgSrc = getObjectAttribute(this,"src");
	var newImgSrc;

	if (etype == 'mouseover'){
	    newImgSrc = imgSrc.replace('off.','on.','gi');
		this.setAttribute('src',newImgSrc);
	}

	else if (etype == 'mouseout') {
	    newImgSrc = imgSrc.replace('on.','off.','gi');
		this.setAttribute('src',newImgSrc);
	}
}

// IE 6 transparent PNG rollover function. KM
function rolloverPNG(event) {
	var etype = event.type;
	var imgSrc = getObjectAttribute(this,"name");
	var newImgSrc;

	if (etype == 'mouseover'){
	    newImgSrc = imgSrc.replace('off.','on.','gi');
		this.setAttribute('src',newImgSrc);
	}

	else if (etype == 'mouseout') {
	    newImgSrc = imgSrc.replace('on.','off.','gi');
		this.setAttribute('src',newImgSrc);
	}
}
/** *** End image rollover function **** */

/** *** Begin pop up functions **** */
function popWindow(href,title,sb,width,height) {
	window.open(href,title,'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+ sb +',resizable=0,width='+ width +',height='+ height +',top=150,left=150');
}
/** *** End pop up functions **** */

/** *** Begin expandable nav function **** */
/* Function to initialize the expandable navigation */
function initNavExpand(){
	var c = classAttr();

	if($('nav_tertiary')){
		var link_items = $('nav_tertiary').getElementsByTagName('ul')[0].getElementsByTagName('li');	// Get
																										// li
																										// items
																										// withing
																										// the
																										// tertiary
																										// nav
																										// section.
		var j = 1;

		for(var i=0;i<link_items.length;i++){	// Loop through all the li items

			if((link_items[i].parentNode.getAttribute(c) != 'sublinks') && (link_items[i].getElementsByTagName('ul')[0])){  // Check
																															// to
																															// make
																															// sure
																															// that
																															// the
																															// li
																															// is
																															// not
																															// within
																															// the
																															// sub
																															// links
																															// ul
				addEvent(link_items[i].getElementsByTagName('span')[0],'mouseover',navBGSwap);	// Attach
																								// mouseover
																								// event
				addEvent(link_items[i].getElementsByTagName('span')[0],'mouseout',navBGSwap);	// Attach
																								// mouseout
																								// event
				addEvent(link_items[i].getElementsByTagName('span')[0],'click',navExpand);		// Attach
																								// click
																								// event
				link_items[i].getElementsByTagName('span')[0].setAttribute('id', 'li' + j++);	// Ad
																								// an
																								// id
																								// to
																								// the
																								// span
																								// tag
				link_items[i].getElementsByTagName('span')[0].setAttribute(c, 'off');			// Set
																								// a
																								// class
																								// attribute
			}
		}

	}
}
/* Function to swap background images */
function navBGSwap(event) {
	var id = getTarget(event).id;	// Get the id of the target of the mouse
									// event
	var etype = event.type;			// Get the type of event, i.e. mouseover or
									// mouseout
	var c = classAttr();			// Get which class attribute to set

	if (etype == 'mouseover'){													// If
																				// the
																				// event
																				// was
																				// a
																				// mousover
		if($(id).getAttribute(c) == "current_off"){								// If
																				// the
																				// class
																				// is
																				// "current_off"
																				// ("current_off"
																				// will
																				// be
																				// the
																				// class
																				// of
																				// the
																				// currently
																				// expanded
																				// navigation)
			$(id).setAttribute(c,'current_on');									// Set
																				// the
																				// class
																				// to
																				// "current_on"
		}
		else if(($(id).getAttribute(c) == "off") || (!$(id).getAttribute(c))){	// If
																				// the
																				// class
																				// is
																				// "off"
																				// ("off"
																				// will
																				// be
																				// the
																				// class
																				// of
																				// non-expanded
																				// navigation;
																				// second
																				// conditional
																				// is
																				// to
																				// fix
																				// IE
																				// bugginess)
			$(id).setAttribute(c,'on');											// Set
																				// the
																				// class
																				// to
																				// "on"
		}
	}

	else if (etype == 'mouseout') {												// If
																				// the
																				// event
																				// was
																				// a
																				// mousout
		if($(id).getAttribute(c) == "current_on"){								// If
																				// the
																				// class
																				// is
																				// "current_on"
																				// ("current_on"
																				// will
																				// be
																				// the
																				// class
																				// of
																				// the
																				// currently
																				// expanded
																				// navigation)
			$(id).setAttribute(c,'current_off');								// Set
																				// the
																				// class
																				// to
																				// "current_off"
		}
		else if (($(id).getAttribute(c) == "on") || (!$(id).getAttribute(c))){	// If
																				// the
																				// class
																				// is
																				// "on"
																				// ("on"
																				// will
																				// be
																				// the
																				// class
																				// of
																				// non-expanded
																				// navigation;
																				// second
																				// conditional
																				// is
																				// to
																				// fix
																				// IE
																				// bugginess)
			$(id).setAttribute(c,'off');
		}
	}
	else {	// If neither of the previous two conditions are met, do nothing.
		;
	}
}
/* Function to expand the sub link navigation */
function navExpand(event) {
	var current_open = getElementsByClass('current_off', null, 'span')[0];							// Get
																									// the
																									// currently
																									// open
																									// (expanded)
																									// navigation
	var all_uls = $('nav_tertiary').getElementsByTagName('ul')[0].getElementsByTagName('ul');		// Get
																									// all
																									// sub
																									// link
																									// ul
																									// elements
	var id = getTarget(event).id;																	// Get
																									// the
																									// id
																									// of
																									// the
																									// target
																									// of
																									// the
																									// mouse
																									// event
	var expand_ul = $(id).parentNode.getElementsByTagName('ul')[0];									// Get
																									// the
																									// ul
																									// element
																									// that
																									// should
																									// be
																									// expanded/collapsed
																									// when
																									// click
																									// event
																									// occurs
	var c = classAttr();																			// Get
																									// which
																									// class
																									// attribute
																									// to
																									// set

	if (expand_ul){																					// If
																									// there
																									// is a
																									// ul
																									// element
																									// to
																									// be
																									// expanded/collapsed
		if (expand_ul.style.display == "block") {													// If
																									// the
																									// ul
																									// is
																									// expanded
			expand_ul.style.display = "none";														// Collapse
																									// the
																									// ul
																									// on
																									// click
			$(id).setAttribute(c,'on');																// Set
																									// the
																									// class
																									// of
																									// the
																									// clicked
																									// target
																									// to
																									// "on"
		}

		else {																						// Else
																									// if
																									// there
																									// is
																									// no
																									// ul
																									// that
																									// is
																									// expanded
			for(var i=0;i<all_uls.length;i++){														// Loop
																									// all
																									// sub
																									// link
																									// ul
																									// elements
				all_uls[i].style.display = "none";													// Collapse
																									// all
																									// sub
																									// link
																									// ul
																									// elements
			}
			expand_ul.style.display = "block";														// Expand
																									// the
																									// ul
																									// element
			$(id).setAttribute(c,'current_on');														// Set
																									// the
																									// class
																									// of
																									// the
																									// clicked
																									// target
																									// to
																									// "current_on"
			current_open.setAttribute(c, 'off');													// Set
																									// the
																									// class
																									// of
																									// the
																									// currently
																									// expanded
																									// navigation
																									// to
																									// "off"
		}
	}

}
/* Function to expand particular navigation on page load */
function navExpandOnload() {
	var c = classAttr();																			// Get
																									// which
																									// class
																									// attribute
																									// to
																									// set
	if(expand_num){																					// If
																									// the
																									// variable
																									// "expand_num"
																									// exists
		var expandID = 'li' + expand_num;															// Set
																									// the
																									// id
																									// of
																									// the
																									// navigation
																									// to
																									// expand
		$(expandID).parentNode.getElementsByTagName('ul')[0].style.display = "block";				// Expand
																									// the
																									// proper
																									// navigation
																									// based
																									// on
																									// it's
																									// id
		$(expandID).setAttribute(c,'current_off');													// Set
																									// the
																									// class
																									// to
																									// "current_off"
																									// of
																									// the
																									// expanded
																									// navigation
	}
}
/** *** End expandable nav function **** */

/** *** Begin tab change functions **** */
function initTabbing(){
	var tabs = getElementsByClass("tab",null,null);	// Get elements with a class
													// of "tab"

	if (tabs.length > 0){		// If there is at least one element with a class
								// "tab"
		for(var i=0;i<tabs.length;i++){	// Loop through all elements with class
										// "tab"
			addEvent(tabs[i],"click",tabClick);	// Attach click event
			addEvent(tabs[i],"mouseover",tabHover);	// Attach over event
			addEvent(tabs[i],"mouseout",tabHover);	// Attach out event
		}
	}
}

function tabClick(event, x){
    var tabs = getElementsByClass("tab",null,null);	// Get tabs
    var tabSections = getElementsByClass("tab-section",null,null);   // Get
																		// tab
																		// body
																		// sections


	for(var t=0;t<tabs.length;t++){ // Loop through all tabs
	    var tabObj = tabs[t];
	    var tabSectionObj = tabSections[t];

	    if((tabObj == this)||(t==x)){ // Change clicked tab on //To turn on a
										// section from a link
            tabObj.setAttribute(classAttribute, "tab selected");		// other
																		// then
																		// from
																		// its
																		// tab,
																		// use
            tabSectionObj.style.display = "block";						// onclick="tabClick('',x)"
																		// where
																		// x is
	    }																// the
																		// section
																		// number
																		// - BG
	    else {	// Change other tabs off
            tabObj.setAttribute(classAttribute, "tab");
            tabSectionObj.style.display = "none";
	    }
	}
}

function tabHover(event){
    var etype = event.type;

	if (this.getAttribute(classAttribute) != "tab selected"){
	    if (etype == "mouseover"){
		    this.setAttribute(classAttribute,"tab hover");
	    }

	    else if (etype == "mouseout") {
		    this.setAttribute(classAttribute,"tab");
	    }
	}
}

/** *** End tab change functions **** */

/** *** Begin accordion expand functions **** */

// These variables need to be placed at the bottom of any page with accordion
// divs.
// var accordionHeaders = getElementsByClass("accordion-header",null,null);
// //Get accordion headers
// var accordionSections = getElementsByClass("accordion-section",null,null);
// //Get accordion sections
// var icon = getElementsByClass("expand-icon",null,null); //Get accordion
// sections
// onloadfunctions.push(initAccordionClick());

function initAccordion(){

	if (accordionHeaders.length > 0){		// If there is at least one element
											// with a class "accordion-header"
		for(var i=0;i<accordionHeaders.length;i++){	// Loop through all elements
													// with class
													// "accordion-header"
			addEvent(accordionHeaders[i],"click",accordionClick);	// Attach
																	// click
																	// event
			addEvent(accordionHeaders[i],"mouseover",accordionHover);	// Attach
																		// mouseover
																		// event
			addEvent(accordionHeaders[i],"mouseout",accordionHover);	// Attach
																		// mouseover
																		// event
		}
	}

	if (accordionSections.length > 0){		// If there is at least one element
											// with a class "accordion-section"
		for(var i=0;i<accordionSections.length;i++){	// Loop through all
														// elements with class
														// "accordion-section"
		    if (accordionSections[i].getAttribute(classAttribute).indexOf("open") == -1){
			    accordionSections[i].style.display = "none";	// Set display
																// to none
			}
		}
	}

	if (icons.length > 0){		// If there is at least one element with a class
								// "expand-icon"
		for(var i=0;i<icons.length;i++){	// Loop through all elements with
											// class "expand-icon"
			addEvent(icons[i],"mouseover",rollover);	// Attach mouseover
														// event
			addEvent(icons[i],"mouseout",rollover);	// Attach mouseover event
		}
	}
}

function accordionClick(){
	for(var t=0;t<accordionHeaders.length;t++){ // Loop through all tabs
	    var accordionHeaderObj = accordionHeaders[t];
	    var accordionSectionObj = accordionSections[t];
	    var iconObj = icons[t];
	    var imgSrc = iconObj.getAttribute("src");

	    if(accordionHeaderObj == this){
            if(accordionSectionObj.style.display == "none"){    // Open
																// accordion
                accordionSectionObj.style.display = "block";
                accordionSectionObj.setAttribute(classAttribute,"accordion-section open");

                newImgSrc = imgSrc.replace("_collapsed","_expanded","gi");
		        iconObj.setAttribute("src",newImgSrc);
            }
            else {  // Close accordion
                accordionSectionObj.style.display = "none";
                accordionSectionObj.setAttribute(classAttribute,"accordion-section");

                newImgSrc = imgSrc.replace("_expanded","_collapsed","gi");
		        iconObj.setAttribute("src",newImgSrc);
            }
	    }
    }
}

function accordionHover(event){
	var etype = event.type;
	var id = getTarget(event).id;
	var iconObj = $(id).getElementsByTagName("img")[0];
	var imgSrc = iconObj.getAttribute("src");
	var newImgSrc;

	if (etype == 'mouseover'){
	    newImgSrc = imgSrc.replace('off.','on.','gi');
		iconObj.setAttribute('src',newImgSrc);
	}

	else if (etype == 'mouseout') {
	    newImgSrc = imgSrc.replace('on.','off.','gi');
		iconObj.setAttribute('src',newImgSrc);
	}
}

function expandAll(){
    for(var t=0;t<accordionSections.length;t++){ // Loop through all sections
        var iconObj = icons[t];
        var imgSrc = iconObj.getAttribute("src");

        newImgSrc = imgSrc.replace("_collapsed","_expanded","gi");
		iconObj.setAttribute("src",newImgSrc);
        accordionSections[t].style.display = "block";
    }
}

function collapseAll(){
    for(var t=0;t<accordionSections.length;t++){ // Loop through all sections
        var iconObj = icons[t];
        var imgSrc = iconObj.getAttribute("src");

        newImgSrc = imgSrc.replace("_expanded","_collapsed","gi");
		iconObj.setAttribute("src",newImgSrc);
        accordionSections[t].style.display = "none";
    }
}
/** *** End accordion expand functions **** */

/** *** Begin show/hide Flash navigation function **** */
function flashNavigation() {
	var fullFlashNav = $('flashNav');

	if (fullFlashNav.style.height == "400px"){
		fullFlashNav.style.height="25px";
	}

	else {
		fullFlashNav.style.height="400px";
	}
}
/** *** End show/hide Flash navigation function **** */

// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page
// to access data from any server in the web, which is really useful.
// Unfortunately, the data is returned in the form of a script. That script
// can deliver the data, but it runs with the same authority as scripts on
// the base page, so it is able to steal cookies or misuse the authorization
// of the user with the server. A rogue script can do destructive things to
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    // this.noCacheIE = '?noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    // this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
	this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

$(window).load(function(){
    // initSearch();
    initRollovers();
});

function sortBy(sortBy)
{
    document.getElementById('so').value=sortBy;
    document.frmsortby.submit();
}

function paginationByPage(pageno)
{
    document.getElementById('page').value=pageno;
    document.frmsortby.submit();
}

function paginationBySearchPage(pageno){
    document.getElementById('page').value=pageno;
    document.searchForm.submit();
}
function showlightbox(style, prodid, itemID, itemPrice, itemQty, itemUomId) {
    // document.getElementById('flashNav').style.visibility="hidden"; // hide
	// the flash nav to fix z-index bugs in multiple browsers
    body = document.getElementsByTagName('body')[0];
    back = document.createElement('div');
    back.id = 'lightbox-back';
    body.appendChild(back);
    front = document.createElement('div');
    front.id = 'lightbox-front';
    body.appendChild(front);

    if (style=='cv2'){
        jQuery('#lightbox-front').load('/shop/cvv2.asp?force=' + new Date().getTime());
    }
    else if (style=='what') {
        jQuery('#lightbox-front').load('/itemspopup');
    }
    else if (style=='atb') {
        jQuery('#lightbox-front').load('/addtobag/'+itemID+'/' + new Date().getTime());
        addToBagCart(itemID, itemPrice, itemQty, itemUomId);
    }

    else if (style=='nextag') {
        jQuery('#lightbox-front').load('/shop/nextag.asp?force=' + new Date().getTime());
    }
    else
    {
        jQuery('#lightbox-front').load('/product/prodpopup.asp?id='+prodid+'&force=' + new Date().getTime());
    }
    return false;
}
function addToBagCart(itemID, itemPrice, itemQty, itemUomId){
    $.ajax({
        type:"POST",
        url:"/cart",
        // datatype:"html",
        data:{
            cart_action:'add',
            itemID:itemID,
            itemPrice:itemPrice,
            itemQty:itemQty,
            itemUomId:itemUomId
        },
        success:function( data )
        {
            updateAddTobagPopUp();
        }
    });
}
function updateHomePageAddTobag(){

    $.ajax({
        type:"POST",
        url:"/shopbag",
        datatype:"html",
        data:{},
        success:function( data )
        {
            $("#indexShoppingBag").html(data);
        }
    });
}

function updateAddTobagPopUp(){

    $.ajax({
        type:"POST",
        url:"/shopbag",
        datatype:"html",
        data:{},
        success:function( data )
        {
            $("#addtoShoppingBag").html(data);
        }
    });
}


function clearlightbox() {
    // document.getElementById('flashNav').style.visibility="visible";
    back.parentNode.removeChild(back);
    front.parentNode.removeChild(front);
    updateHomePageAddTobag();
    return false;
}

function updatehomepagebag() {
	  $().ready(function() {
	        $("#indexupdate").load("/vicspick");
	    });
}

function doPrintReceipt(orderNo) {
  $().ready(function() {	  
      newWindow = window.open("printreceipt/"+orderNo, "OrderedInformation", "menubar=1, resizable=1, width=920, height=900, scrollbars=yes");
      //newWindow.document.title = "Receipt";      
      newWindow.moveTo(0,0);
      newWindow.focus();
      
  });
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}
function enlarge(el) {
    alternates = el.parentNode.parentNode.getElementsByTagName('div');
    for (i = 0; i < alternates.length; i++) alternates[i].className = 'alternate';
    el.parentNode.className = 'alternate enlarged';
    document.getElementById('largeimg').src = el.getAttribute('largefile');
}
function switchtab(el, id) {
    tabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < tabs.length; i++) tabs[i].className = '';
    tabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < tabs.length; i++) tabs[i].style.display = 'none';
    el.className = 'sel';
    document.getElementById(id).style.display = 'block';
    return false;
}
function moveDeals() {
    var step = 1;
    step = Math.min(136-Math.abs(left), Math.abs(left));
    step = Math.ceil(Math.pow(step, .5) * 2);
    step = -1 * step * (left / Math.abs(left))
    left += step;
    oldleft += step;
    newdeal.style.left = left + 'px';
    olddeal.style.left = oldleft + 'px';
    if (left == 0) {
        window.clearInterval(intervalID);
        olddeal.parentNode.removeChild(olddeal);
    }
}
function scrolldeal(direction) {
    var deals = document.getElementById('scroller-tile').getElementsByTagName('div');
    for (var i = deals.length -1; i>0; i--) {
        deals[i].parentNode.removeChild(deals[i]);
    }
    olddeal = deals[0];
    newdeal = document.createElement('div');
    var productlink = document.createElement('a');
    productlink.setAttribute('href', '#');
    newdeal.appendChild(productlink.cloneNode(false));
    var productimg = document.createElement('img');
    // product image filename
    productimg.setAttribute('src', '/img/thumbproduct.jpg');
    productimg.setAttribute('width', '56');
    productimg.setAttribute('height', '56');
    // product name
    productimg.setAttribute('alt', 'Product_Name');
    newdeal.lastChild.appendChild(productimg);
    newdeal.appendChild(document.createElement('br'));
    newdeal.appendChild(document.createElement('span'));
    newdeal.lastChild.className='tile-name';
    newdeal.lastChild.appendChild(productlink);
    // product name
    newdeal.lastChild.lastChild.appendChild(document.createTextNode('Product_Name'));
    newdeal.appendChild(document.createElement('br'));
    newdeal.appendChild(document.createElement('span'));
    // product price
    newdeal.lastChild.className='tile-price';
    newdeal.lastChild.appendChild(document.createTextNode('$' + '000'));
    newdeal.appendChild(document.createElement('img'));
    newdeal.lastChild.className='tpng';
    newdeal.lastChild.setAttribute('src', 'imgs/tiny-bubble.png');
    newdeal.lastChild.setAttribute('width', '19');
    newdeal.lastChild.setAttribute('height', '15');

    olddeal.parentNode.appendChild(newdeal);

    if (direction == 'left') {
        left = -135;
    } else if (direction == 'right') {
        left = 135;
    }
    newdeal.style.left = left + 'px';
    oldleft = 0;
    intervalID = window.setInterval(moveDeals, 30);
}
function scrolldeal_Original(direction) {
    var deals = document.getElementById('scroller-tile').getElementsByTagName('div');
    for (var i = deals.length -1; i>0; i--) {
        deals[i].parentNode.removeChild(deals[i]);
    }
    olddeal = deals[0];
    newdeal = document.createElement('div');
    var productlink = document.createElement('a');
    productlink.setAttribute('href', '#');
    newdeal.appendChild(productlink.cloneNode(false));
    var productimg = document.createElement('img');
    // product image filename
    productimg.setAttribute('src', '/img/thumbproduct.jpg');
    productimg.setAttribute('width', '56');
    productimg.setAttribute('height', '56');
    // product name
    productimg.setAttribute('alt', 'Product_Name');
    newdeal.lastChild.appendChild(productimg);
    newdeal.appendChild(document.createElement('br'));
    newdeal.appendChild(document.createElement('span'));
    newdeal.lastChild.className='tile-name';
    newdeal.lastChild.appendChild(productlink);
    // product name
    newdeal.lastChild.lastChild.appendChild(document.createTextNode('Product_Name'));
    newdeal.appendChild(document.createElement('br'));
    newdeal.appendChild(document.createElement('span'));
    // product price
    newdeal.lastChild.className='tile-price';
    newdeal.lastChild.appendChild(document.createTextNode('$' + '000'));
    newdeal.appendChild(document.createElement('img'));
    newdeal.lastChild.className='tpng';
    newdeal.lastChild.setAttribute('src', 'imgs/tiny-bubble.png');
    newdeal.lastChild.setAttribute('width', '19');
    newdeal.lastChild.setAttribute('height', '15');

    olddeal.parentNode.appendChild(newdeal);

    if (direction == 'left') {
        left = -135;
    } else if (direction == 'right') {
        left = 135;
    }
    newdeal.style.left = left + 'px';
    oldleft = 0;
    intervalID = window.setInterval(moveDeals, 30);
}
function editrow(el, buttons) {
    // el is the TR element containing the appropriate cells to edit
    // buttons is boolean - to include the save/cancel buttons or not
    var cols = el.getElementsByTagName('td').length;
    var editbox = document.createElement('tr');
    editbox.appendChild(document.createElement('td'));
    editbox.lastChild.setAttribute('colspan', cols);
    editbox.lastChild.colSpan = cols;
    editbox.lastChild.appendChild(document.createElement('div'));
    editbox.lastChild.lastChild.className = 'dot-divider';
    editbox.lastChild.lastChild.id = 'editform';

    if (buttons) {
        editbox.lastChild.appendChild(document.createElement('a'));
        editbox.lastChild.lastChild.href="#";
        editbox.lastChild.lastChild.id="savebutton";
        editbox.lastChild.lastChild.appendChild(document.createTextNode('save'));
        editbox.lastChild.appendChild(document.createElement('a'));
        editbox.lastChild.lastChild.href="#";
        editbox.lastChild.lastChild.id="cancelbutton";
        editbox.lastChild.lastChild.setAttribute('onclick', "cancel(this.parentNode.parentNode); return false;");
        editbox.lastChild.lastChild.appendChild(document.createTextNode('cancel'));
    }

    if (el.nextSibling) el.parentNode.insertBefore(editbox, el.nextSibling);
    else el.parentNode.appendChild(editbox);

    // GET CONTENT HERE!!!!
    var content = 'call here';
    document.getElementById('editform').innerHTML = content;
}
function cancel(el) {
    el.parentNode.removeChild(el);
}
function editpassword(el, buttons) {
    // el is the TR element containing the appropriate cells to edit
    // buttons is boolean - to include the save/cancel buttons or not
    var cols = el.getElementsByTagName('td').length;
    var editbox = document.createElement('tr');
    editbox.setAttribute('id', 'inputrow');
    var cell = document.createElement("td");
    var textField = document.createElement('INPUT')
    textField.type = 'text'
    textField.setAttribute('value', 'text field')
    textField.setAttribute('Name', 'myTextField')
    textField.style.display = 'block'
    cell.appendChild(textField)
    editbox.appendChild(cell);

    cell = document.createElement("td");
    textField = document.createElement('INPUT')
    textField.type = 'text'
    textField.setAttribute('value', 'text field')
    textField.setAttribute('Name', 'myTextField')
    textField.style.display = 'block'
    cell.appendChild(textField)
    editbox.appendChild(cell);

    cell = document.createElement("td");
    textField = document.createElement('INPUT')
    textField.type = 'password'
    textField.setAttribute('value', 'text field')
    textField.setAttribute('Name', 'myTextField')
    textField.style.display = 'block'
    cell.appendChild(textField)
    editbox.appendChild(cell);

    editbox.appendChild(document.createElement('td'));

    el.parentNode.appendChild(editbox);

    editbox = document.createElement('tr');
    editbox.setAttribute('id', 'buttonrow');
    editbox.appendChild(document.createElement('td'));
    editbox.lastChild.setAttribute('colspan', cols);
    editbox.lastChild.colSpan = cols;
    editbox.lastChild.appendChild(document.createElement('div'));
    editbox.lastChild.lastChild.className = 'dot-divider';
    editbox.lastChild.lastChild.id = 'editform';

    editbox.lastChild.appendChild(document.createElement('a'));
    editbox.lastChild.lastChild.href="#";
    editbox.lastChild.lastChild.id="savebutton";
    editbox.lastChild.lastChild.appendChild(document.createTextNode('save'));
    editbox.lastChild.appendChild(document.createElement('a'));
    editbox.lastChild.lastChild.href="#";
    editbox.lastChild.lastChild.id="cancelbutton";
    editbox.lastChild.lastChild.setAttribute('onclick', "canceleditpassword(this.parentNode.parentNode); return false;");
    editbox.lastChild.lastChild.appendChild(document.createTextNode('cancel'));


    el.parentNode.appendChild(editbox);
}
function canceleditpassword(el) {
    el.parentNode.removeChild(el);
    el = document.getElementById('inputrow');
    el.parentNode.removeChild(el);
}

/*
 * // this code in checkout.shtml var total = 4; var prefix = 'checkout'; //
 * prefix# is the id of each telescoping element, in this case id="checkout1"
 * and so on... // do NOT use padding on these elements, as this script makes
 * use of offsetHeight, a M$ // extension that improperly implements the W3C box
 * model. var targetheights = new Array(); var reducesize = new Array(); var
 * expandsize = '';
 * 
 * for (var i = 1; i <= total; i++) { var el = document.getElementById(prefix +
 * i); targetheights[i] = el.offsetHeight; if (i != 1) el.style.height = '0px';
 * el.style.visibility = 'visible'; }
 */
function resize() {
    for (var i = 0; i < reducesize.length; i++) {
        var reduce = document.getElementById(reducesize[i]);
        step = Math.ceil(Math.pow(reduce.offsetHeight, 2) / (reduce.offsetHeight * 5));
        var newheight = reduce.offsetHeight - step;
        reduce.style.height = newheight + 'px';
        if (newheight <= 0) {
            reducesize.splice(i, 1);
        }
    }
    if (expandsize.offsetHeight < targetsize) {
        var difference = targetsize - expandsize.offsetHeight;
        step = Math.ceil(Math.pow(difference, 2) / (difference * 5));
        expandsize.style.height = (expandsize.offsetHeight + step) + 'px';
    }
    if ((expandsize.offsetHeight >= targetsize) && (reducesize.length == 0)) {
        window.clearInterval(speed);
        expandsize.style.height = 'auto';
        speed = 0;
    // pollhash = window.setInterval(checkstate, 200);
    }
}

function edit(num) {
    window.clearInterval(pollhash);
    if (reducesize.length)
        reducesize.splice(0, reducesize.length);
    expandsize = document.getElementById(prefix + num);
    targetsize = targetheights[num];
    for (i = 1; i <= total; i++) {
        el = document.getElementById(prefix + i);
        if (el.offsetHeight > 0) {
            targetheights[i] = el.offsetHeight;
            if (i != num)
                reducesize.push(prefix + i);
        }
    }
    window.location.hash = num;
    speed = window.setInterval(resize, 30);
}
function checkstate() {
    if (window.location.hash.length < 2) hash = '1'
    else hash = window.location.hash.substring(1);
    if ((speed) || (hash == oldhash)) return;

    oldhash = hash;
    if ((!isNaN(hash)) && (hash <= total) && (hash >= 1))
        edit(hash);
}
/*
 * this code in checkout.shtml var oldhash = 'refresh'; var pollhash = 0;
 */

var xmlSaleInvHttp;

function switchtab(id) {

    vartabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < vartabs.length; i++) vartabs[i].className = '';
    vartabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < vartabs.length; i++) vartabs[i].style.display = 'none';
    document.getElementById('tablink' + id).className = 'sel';
    document.getElementById('tab' + id).style.display = 'block';
    return false;
}

function openThickBox(){
    tb_show('', 'http://www.innovateads.com/ex-unclevic.php?TB_iframe=true&height=420&width=630', '');
}

initClearValue();

function initClearValue(){
    var input = getElementsByClass("clear-value",null,null);

    if (input.length > 0){
        for(var i=0;i<input.length;i++){
            addEvent(input[i],"click",clearValue);
            addEvent(input[i],"focus",clearValue);
        }
    }
}



/** *** Begin search **** */
function initSearch(){
    $("#search-button").click(function(){
        location.href="http://www.unclevic.com/search/?search=" + $("#search-text").attr("value");
    });
}
/** *** End search **** */

/** *** Begin twitter feed **** */
function initTwitter(){
    getTwitterData();
}

function getTwitterData(){
    // Load data
    var obj=new JSONscriptRequest('http://twitter.com/statuses/user_timeline/unclevicdeals.json?count=' + twitCount + '&callback=loadTwitter');
    obj.buildScriptTag(); // Build the script tag
    obj.addScriptTag(); // Execute (add) the script tag
}


function useBillFNameasCardHolderName(){
document.getElementById('txtNameonCard').value = document.getElementById('billFirstName').value + document.getElementById('billMidInit').value + document.getElementById('billLastName').value;
}

function loadTwitter(data){
    var twitList;
    var twitItem;
    var twitDateHead;
    var twitStatus;
    var cleanDate;
    var cleanDate1;
    var cleanDate2;
    var cleanDate3;
    var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
    var tDate;
    var twitMonth;
    var twitDate;
    var twitYear;
    var newTwitDate;
    var twitText;
    var linkStart;
    var linkEnd;
    var linkURL;
    var newTwitText;

    twitList = document.createElement("ul");

    if(data==null){
        var text = "<h4>No twitter data</h4>";
        twitItem = document.createElement("li");
        $(twitItem).html(text);
        $(twitList).append(twitItem);
    }
    else {
        for(var i=0;i<data.length;i++){
            cleanDate = data[i].created_at;
            cleanDate1 = cleanDate.substring(0,10);
            cleanDate2 = cleanDate.substring(11,25);
            cleanDate3 = cleanDate.substring(26,30);
            tDate = new Date(cleanDate1 + " " + cleanDate3 + " " + cleanDate2);
            twitMonth = month[tDate.getMonth()];
            twitDate = tDate.getDate();
            twitYear = tDate.getFullYear();
            twitTime = tDate.toLocaleTimeString();
            newTwitDate = twitDate + " " + twitMonth + " " + twitYear;

            twitText = data[i].text;
            newTwitText = twitText;

            linkStart = twitText.indexOf("http://");
            if(linkStart == -1){
                linkStart = twitText.indexOf("https://");
            }

            if(linkStart > -1){
                linkEnd = twitText.indexOf(" ", linkStart);
                if(linkEnd == -1){
                    linkEnd = twitText.length;
                }

                linkURL = twitText.substring(linkStart,linkEnd);
                linkText = linkURL;

                if (linkURL.length > 40){
                    linkText = linkText.substring(0,40) + "...";
                }
                newTwitText = twitText.replace(linkURL,'<a href="' + linkURL + '" target="_blank" class="tweet-link">' + linkText + '</a>');
            }

            twitDateHead = document.createElement("h4");
            $(twitDateHead).html(newTwitDate);

            twitStatus = document.createElement("p");
            $(twitStatus).html(newTwitText);

            twitItem = document.createElement("li");
            if(i==0){
                $(twitItem).addClass("first-child");
            }
            $(twitItem).append(twitDateHead);
            $(twitItem).append(twitStatus);
            $(twitList).append(twitItem);
        }
    }
    $("#twitter-data").append(twitList);
}
/** *** End twitter feed **** */

function calculateShipping(element, value){	
	var zip = document.getElementById('zip').value;
	var str = "";
	var validZip = "";
   var regExp = new RegExp('^[0-9]*$');
   if (trim(zip).length == 0){
   	document.getElementById('zip').style.background = 'Yellow';
      str = "The required field has not been filled in.\n";
   } else if( !(regExp.test(zip))  ){
      document.getElementById('zip').style.background = 'Yellow';
      validZip = "Zip code is not valid.\n";
   } else if (trim(zip).length < 5){
   	document.getElementById('zip').style.background = 'Yellow';
   	str = "Zip code is not valid...\n";   	
   } else {
      document.getElementById('zip').style.background = 'White';
   } 
	
   str += validZip;
   if (str != '') {
   	alert(str);
      return false;
   }else{
   	$("#"+element).val(value);
   	return true;
   }   
}

function updateTotalValue(){
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode"+temp).val()) ;
    var result = (parseFloat($("#shipcode"+temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
  if(shippingAmount==0)
    $('#shippingdiv').hide();
  else
    $('#shippingdiv').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
 /*   $("#total").html(res.val());    */

}

function updateTotalValues(inPage){
	if(inPage=='cart'){
		jQuery("#zip").attr("readonly",false);
		jQuery("#gobtn").removeAttr("disabled");
 		jQuery("#shipMethod").removeAttr("disabled");
	    jQuery('#shippingRadio').attr("checked","checked");
	}
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode"+temp).val()) ;
    var result = (parseFloat($("#shipcode"+temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
  if(shippingAmount==0)
    $('#shippingdiv').hide();
  else
    $('#shippingdiv').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
 /*   $("#total").html(res.val());    */

}

/*
 * Thickbox 3.1 - One Box To Rule Them All. By Cody Lindley
 * (http://www.codylindley.com) Copyright (c) 2007 cody lindley Licensed under
 * the MIT License: http://www.opensource.org/licenses/mit-license.php
 */

var tb_pathToImage = "images/loadingAnimation.gif";

/*
 * !!!!!!!!!!!!!!!!! edit below this line at your own risk
 * !!!!!!!!!!!!!!!!!!!!!!!
 */


// on page load call tb_init
$(document).ready(function(){
    tb_init('a.thickbox, area.thickbox, input.thickbox');// pass where to
															// apply thickbox
    imgLoader = new Image();// preload image
    imgLoader.src = tb_pathToImage;
});


// add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
    $(domChunk).click(function(){
        var t = this.title || this.name || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t,a,g);
        this.blur();
        return false;
    });
}

function tb_show(caption, url, imageGroup) {// function called when the user
											// clicks on a thickbox link

    try {
        if (typeof document.body.style.maxHeight === "undefined") {// if IE 6
            $("body","html").css({
                height: "100%",
                width: "100%"
            });
            $("html").css("overflow","hidden");
            if (document.getElementById("TB_HideSelect") === null) {// iframe to
																	// hide
																	// select
																	// elements
																	// in ie6
                $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }else{// all others
            if(document.getElementById("TB_overlay") === null){
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }

        if(tb_detectMacXFF()){
            $("#TB_overlay").addClass("TB_overlayMacFFBGHack");// use png
																// overlay so
																// hide flash
        }else{
            $("#TB_overlay").addClass("TB_overlayBG");// use background and
														// opacity
        }

        if(caption===null){
            caption="";
        }
        $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");// add
																					// loader
																					// to
																					// the
																					// page
        $('#TB_load').show();// show loader

        var baseURL;
        if(url.indexOf("?")!==-1){ // ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        }else{
            baseURL = url;
        }

        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = baseURL.toLowerCase().match(urlString);

        if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){// code
																													// to
																													// show
																													// images

            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if(imageGroup){
                TB_TempArray = $("a[@rel="+imageGroup+"]").get();
                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                    if (!(TB_TempArray[TB_Counter].href == url)) {
                        if (TB_FoundURL) {
                            TB_NextCaption = TB_TempArray[TB_Counter].title;
                            TB_NextURL = TB_TempArray[TB_Counter].href;
                            TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
                        } else {
                            TB_PrevCaption = TB_TempArray[TB_Counter].title;
                            TB_PrevURL = TB_TempArray[TB_Counter].href;
                            TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
                        }
                    } else {
                        TB_FoundURL = true;
                        TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
                    }
                }
            }

            imgPreloader = new Image();
            imgPreloader.onload = function(){
                imgPreloader.onload = null;

                // Resizing large images - orginal by Christian Montoya edited
				// by me.
                var pagesize = tb_getPageSize();
                var x = pagesize[0] - 150;
                var y = pagesize[1] - 150;
                var imageWidth = imgPreloader.width;
                var imageHeight = imgPreloader.height;
                if (imageWidth > x) {
                    imageHeight = imageHeight * (x / imageWidth);
                    imageWidth = x;
                    if (imageHeight > y) {
                        imageWidth = imageWidth * (y / imageHeight);
                        imageHeight = y;
                    }
                } else if (imageHeight > y) {
                    imageWidth = imageWidth * (y / imageHeight);
                    imageHeight = y;
                    if (imageWidth > x) {
                        imageHeight = imageHeight * (x / imageWidth);
                        imageWidth = x;
                    }
                }
                // End Resizing

                TB_WIDTH = imageWidth + 30;
                TB_HEIGHT = imageHeight + 60;
                $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");

                $("#TB_closeWindowButton").click(tb_remove);

                if (!(TB_PrevHTML === "")) {
                    function goPrev(){
                        if($(document).unbind("click",goPrev)){
                            $(document).unbind("click",goPrev);
                        }
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                        return false;
                    }
                    $("#TB_prev").click(goPrev);
                }

                if (!(TB_NextHTML === "")) {
                    function goNext(){
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_NextCaption, TB_NextURL, imageGroup);
                        return false;
                    }
                    $("#TB_next").click(goNext);

                }

                document.onkeydown = function(e){
                    if (e == null) { // ie
                        keycode = event.keyCode;
                    } else { // mozilla
                        keycode = e.which;
                    }
                    if(keycode == 27){ // close
                        tb_remove();
                    } else if(keycode == 190){ // display previous image
                        if(!(TB_NextHTML == "")){
                            document.onkeydown = "";
                            goNext();
                        }
                    } else if(keycode == 188){ // display next image
                        if(!(TB_PrevHTML == "")){
                            document.onkeydown = "";
                            goPrev();
                        }
                    }
                };

                tb_position();
                $("#TB_load").remove();
                $("#TB_ImageOff").click(tb_remove);
                $("#TB_window").css({
                    display:"block"
                }); // for safari using css instead of show
            };

            imgPreloader.src = url;
        }else{// code to show html

            var queryString = url.replace(/^[^\?]+\??/,'');
            var params = tb_parseQuery( queryString );

            TB_WIDTH = (params['width']*1) + 40 || 630; // defaults to 630 if no
														// paramaters were added
														// to URL
            TB_HEIGHT = (params['height']*1) + 93 || 440; // defaults to 440
															// if no paramaters
															// were added to URL
            ajaxContentW = TB_WIDTH - 40;
            ajaxContentH = TB_HEIGHT - 93;

            if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
                urlNoQuery = url.split('TB_');
                $("#TB_iframeContent").remove();
                if(params['modal'] != "true"){// iframe no modal
                    $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 40)+"px;height:"+(ajaxContentH + 25)+"px;' > </iframe>");
                }else{// iframe modal
                    $("#TB_overlay").unbind();
                    $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
                }
            }else{// not an iframe, ajax
                if($("#TB_window").css("display") != "block"){
                    if(params['modal'] != "true"){// ajax no modal
                        $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
                    }else{// ajax modal
                        $("#TB_overlay").unbind();
                        $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
                    }
                }else{// this means the window is already up, we are just
						// loading new content via ajax
                    $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
                    $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
                    $("#TB_ajaxContent")[0].scrollTop = 0;
                    $("#TB_ajaxWindowTitle").html(caption);
                }
            }

            $("#TB_closeWindowButton").click(tb_remove);

            if(url.indexOf('TB_inline') != -1){
                $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
                $("#TB_window").unload(function () {
                    $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move
																							// elements
																							// back
																							// when
																							// you're
																							// finished
                });
                tb_position();
                $("#TB_load").remove();
                $("#TB_window").css({
                    display:"block"
                });
            }else if(url.indexOf('TB_iframe') != -1){
                tb_position();
                if($.browser.safari){// safari needs help because it will not
										// fire iframe onload
                    $("#TB_load").remove();
                    $("#TB_window").css({
                        display:"block"
                    });
                }
            }else{
                $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){// to
																								// do a
																								// post
																								// change
																								// this
																								// load
																								// method
                    tb_position();
                    $("#TB_load").remove();
                    tb_init("#TB_ajaxContent a.thickbox");
                    $("#TB_window").css({
                        display:"block"
                    });
                });
            }

        }

        if(!params['modal']){
            document.onkeyup = function(e){
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                }
            };
        }

    } catch(e) {
    // nothing here
    }
}

// helper functions below
function tb_showIframe(){
    $("#TB_load").remove();
    $("#TB_window").css({
        display:"block"
    });
}

function tb_remove() {
    $("#TB_imageOff").unbind("click");
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut("fast",function(){
        $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();
    });
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {// if IE 6
        $("body","html").css({
            height: "auto",
            width: "auto"
        });
        $("html").css("overflow","");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function tb_position() {
    $("#TB_window").css({
        marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px',
        width: TB_WIDTH + 'px'
    });
    if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away
																	// IE6
        $("#TB_window").css({
            marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'
        });
    }
}

function tb_parseQuery ( query ) {
    var Params = {};
    if ( ! query ) {
        return Params;
    }// return empty object
    var Pairs = query.split(/[;&]/);
    for ( var i = 0; i < Pairs.length; i++ ) {
        var KeyVal = Pairs[i].split('=');
        if ( ! KeyVal || KeyVal.length != 2 ) {
            continue;
        }
        var key = unescape( KeyVal[0] );
        var val = unescape( KeyVal[1] );
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}

function tb_getPageSize(){
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w,h];
    return arrayPageSize;
}

function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
        return true;
    }
}

/**
 * jCarousel - Riding carousels with jQuery http://sorgalla.com/jcarousel/
 * 
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com) Dual licensed under the
 * MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
 * 
 * Built on top of the jQuery library http://jquery.com
 * 
 * Inspired by the "Carousel Component" by Bill Scott
 * http://billwscott.com/carousel/
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(9($){$.1s.A=9(o){z 4.14(9(){2H r(4,o)})};8 q={W:F,23:1,1G:1,u:7,15:3,16:7,1H:\'2I\',24:\'2J\',1i:0,B:7,1j:7,1I:7,25:7,26:7,27:7,28:7,29:7,2a:7,2b:7,1J:\'<N></N>\',1K:\'<N></N>\',2c:\'2d\',2e:\'2d\',1L:7,1M:7};$.A=9(e,o){4.5=$.17({},q,o||{});4.Q=F;4.D=7;4.H=7;4.t=7;4.R=7;4.S=7;4.O=!4.5.W?\'1N\':\'2f\';4.E=!4.5.W?\'2g\':\'2h\';8 a=\'\',1d=e.J.1d(\' \');1k(8 i=0;i<1d.K;i++){6(1d[i].2i(\'A-2j\')!=-1){$(e).1t(1d[i]);8 a=1d[i];1l}}6(e.2k==\'2K\'||e.2k==\'2L\'){4.t=$(e);4.D=4.t.18();6(4.D.1m(\'A-H\')){6(!4.D.18().1m(\'A-D\'))4.D=4.D.B(\'<N></N>\');4.D=4.D.18()}X 6(!4.D.1m(\'A-D\'))4.D=4.t.B(\'<N></N>\').18()}X{4.D=$(e);4.t=$(e).2M(\'>2l,>2m,N>2l,N>2m\')}6(a!=\'\'&&4.D.18()[0].J.2i(\'A-2j\')==-1)4.D.B(\'<N 2N=" \'+a+\'"></N>\');4.H=4.t.18();6(!4.H.K||!4.H.1m(\'A-H\'))4.H=4.t.B(\'<N></N>\').18();4.S=$(\'.A-11\',4.D);6(4.S.u()==0&&4.5.1K!=7)4.S=4.H.1u(4.5.1K).11();4.S.V(4.J(\'A-11\'));4.R=$(\'.A-19\',4.D);6(4.R.u()==0&&4.5.1J!=7)4.R=4.H.1u(4.5.1J).11();4.R.V(4.J(\'A-19\'));4.H.V(4.J(\'A-H\'));4.t.V(4.J(\'A-t\'));4.D.V(4.J(\'A-D\'));8 b=4.5.16!=7?1n.1O(4.1o()/4.5.16):7;8 c=4.t.2O(\'1v\');8 d=4;6(c.u()>0){8 f=0,i=4.5.1G;c.14(9(){d.1P(4,i++);f+=d.T(4,b)});4.t.y(4.O,f+\'U\');6(!o||o.u===L)4.5.u=c.u()}4.D.y(\'1w\',\'1x\');4.R.y(\'1w\',\'1x\');4.S.y(\'1w\',\'1x\');4.2n=9(){d.19()};4.2o=9(){d.11()};4.1Q=9(){d.2p()};6(4.5.1j!=7)4.5.1j(4,\'2q\');6($.2r.2s){4.1e(F,F);$(2t).1y(\'2P\',9(){d.1z()})}X 4.1z()};8 r=$.A;r.1s=r.2Q={A:\'0.2.3\'};r.1s.17=r.17=$.17;r.1s.17({1z:9(){4.C=7;4.G=7;4.Y=7;4.12=7;4.1a=F;4.1f=7;4.P=7;4.Z=F;6(4.Q)z;4.t.y(4.E,4.1A(4.5.1G)+\'U\');8 p=4.1A(4.5.23);4.Y=4.12=7;4.1p(p,F);$(2t).1R(\'2u\',4.1Q).1y(\'2u\',4.1Q)},2v:9(){4.t.2w();4.t.y(4.E,\'2R\');4.t.y(4.O,\'2S\');6(4.5.1j!=7)4.5.1j(4,\'2v\');4.1z()},2p:9(){6(4.P!=7&&4.Z)4.t.y(4.E,r.I(4.t.y(4.E))+4.P);4.P=7;4.Z=F;6(4.5.1I!=7)4.5.1I(4);6(4.5.16!=7){8 a=4;8 b=1n.1O(4.1o()/4.5.16),O=0,E=0;$(\'1v\',4.t).14(9(i){O+=a.T(4,b);6(i+1<a.C)E=O});4.t.y(4.O,O+\'U\');4.t.y(4.E,-E+\'U\')}4.15(4.C,F)},2T:9(){4.Q=1g;4.1e()},2U:9(){4.Q=F;4.1e()},u:9(s){6(s!=L){4.5.u=s;6(!4.Q)4.1e()}z 4.5.u},2V:9(i,a){6(a==L||!a)a=i;6(4.5.u!==7&&a>4.5.u)a=4.5.u;1k(8 j=i;j<=a;j++){8 e=4.M(j);6(!e.K||e.1m(\'A-1b-1B\'))z F}z 1g},M:9(i){z $(\'.A-1b-\'+i,4.t)},2x:9(i,s){8 e=4.M(i),1S=0,2x=0;6(e.K==0){8 c,e=4.1C(i),j=r.I(i);1q(c=4.M(--j)){6(j<=0||c.K){j<=0?4.t.2y(e):c.1T(e);1l}}}X 1S=4.T(e);e.1t(4.J(\'A-1b-1B\'));1U s==\'2W\'?e.2X(s):e.2w().2Y(s);8 a=4.5.16!=7?1n.1O(4.1o()/4.5.16):7;8 b=4.T(e,a)-1S;6(i>0&&i<4.C)4.t.y(4.E,r.I(4.t.y(4.E))-b+\'U\');4.t.y(4.O,r.I(4.t.y(4.O))+b+\'U\');z e},1V:9(i){8 e=4.M(i);6(!e.K||(i>=4.C&&i<=4.G))z;8 d=4.T(e);6(i<4.C)4.t.y(4.E,r.I(4.t.y(4.E))+d+\'U\');e.1V();4.t.y(4.O,r.I(4.t.y(4.O))-d+\'U\')},19:9(){4.1D();6(4.P!=7&&!4.Z)4.1W(F);X 4.15(((4.5.B==\'1X\'||4.5.B==\'G\')&&4.5.u!=7&&4.G==4.5.u)?1:4.C+4.5.15)},11:9(){4.1D();6(4.P!=7&&4.Z)4.1W(1g);X 4.15(((4.5.B==\'1X\'||4.5.B==\'C\')&&4.5.u!=7&&4.C==1)?4.5.u:4.C-4.5.15)},1W:9(b){6(4.Q||4.1a||!4.P)z;8 a=r.I(4.t.y(4.E));!b?a-=4.P:a+=4.P;4.Z=!b;4.Y=4.C;4.12=4.G;4.1p(a)},15:9(i,a){6(4.Q||4.1a)z;4.1p(4.1A(i),a)},1A:9(i){6(4.Q||4.1a)z;i=r.I(i);6(4.5.B!=\'1c\')i=i<1?1:(4.5.u&&i>4.5.u?4.5.u:i);8 a=4.C>i;8 b=r.I(4.t.y(4.E));8 f=4.5.B!=\'1c\'&&4.C<=1?1:4.C;8 c=a?4.M(f):4.M(4.G);8 j=a?f:f-1;8 e=7,l=0,p=F,d=0;1q(a?--j>=i:++j<i){e=4.M(j);p=!e.K;6(e.K==0){e=4.1C(j).V(4.J(\'A-1b-1B\'));c[a?\'1u\':\'1T\'](e)}c=e;d=4.T(e);6(p)l+=d;6(4.C!=7&&(4.5.B==\'1c\'||(j>=1&&(4.5.u==7||j<=4.5.u))))b=a?b+d:b-d}8 g=4.1o();8 h=[];8 k=0,j=i,v=0;8 c=4.M(i-1);1q(++k){e=4.M(j);p=!e.K;6(e.K==0){e=4.1C(j).V(4.J(\'A-1b-1B\'));c.K==0?4.t.2y(e):c[a?\'1u\':\'1T\'](e)}c=e;8 d=4.T(e);6(d==0){2Z(\'30: 31 1N/2f 32 1k 33. 34 35 36 37 38 39. 3a...\');z 0}6(4.5.B!=\'1c\'&&4.5.u!==7&&j>4.5.u)h.3b(e);X 6(p)l+=d;v+=d;6(v>=g)1l;j++}1k(8 x=0;x<h.K;x++)h[x].1V();6(l>0){4.t.y(4.O,4.T(4.t)+l+\'U\');6(a){b-=l;4.t.y(4.E,r.I(4.t.y(4.E))-l+\'U\')}}8 n=i+k-1;6(4.5.B!=\'1c\'&&4.5.u&&n>4.5.u)n=4.5.u;6(j>n){k=0,j=n,v=0;1q(++k){8 e=4.M(j--);6(!e.K)1l;v+=4.T(e);6(v>=g)1l}}8 o=n-k+1;6(4.5.B!=\'1c\'&&o<1)o=1;6(4.Z&&a){b+=4.P;4.Z=F}4.P=7;6(4.5.B!=\'1c\'&&n==4.5.u&&(n-k+1)>=1){8 m=r.10(4.M(n),!4.5.W?\'1r\':\'1Y\');6((v-m)>g)4.P=v-g-m}1q(i-->o)b+=4.T(4.M(i));4.Y=4.C;4.12=4.G;4.C=o;4.G=n;z b},1p:9(p,a){6(4.Q||4.1a)z;4.1a=1g;8 b=4;8 c=9(){b.1a=F;6(p==0)b.t.y(b.E,0);6(b.5.B==\'1X\'||b.5.B==\'G\'||b.5.u==7||b.G<b.5.u)b.2z();b.1e();b.1Z(\'2A\')};4.1Z(\'3c\');6(!4.5.1H||a==F){4.t.y(4.E,p+\'U\');c()}X{8 o=!4.5.W?{\'2g\':p}:{\'2h\':p};4.t.1p(o,4.5.1H,4.5.24,c)}},2z:9(s){6(s!=L)4.5.1i=s;6(4.5.1i==0)z 4.1D();6(4.1f!=7)z;8 a=4;4.1f=3d(9(){a.19()},4.5.1i*3e)},1D:9(){6(4.1f==7)z;3f(4.1f);4.1f=7},1e:9(n,p){6(n==L||n==7){8 n=!4.Q&&4.5.u!==0&&((4.5.B&&4.5.B!=\'C\')||4.5.u==7||4.G<4.5.u);6(!4.Q&&(!4.5.B||4.5.B==\'C\')&&4.5.u!=7&&4.G>=4.5.u)n=4.P!=7&&!4.Z}6(p==L||p==7){8 p=!4.Q&&4.5.u!==0&&((4.5.B&&4.5.B!=\'G\')||4.C>1);6(!4.Q&&(!4.5.B||4.5.B==\'G\')&&4.5.u!=7&&4.C==1)p=4.P!=7&&4.Z}8 a=4;4.R[n?\'1y\':\'1R\'](4.5.2c,4.2n)[n?\'1t\':\'V\'](4.J(\'A-19-1E\')).20(\'1E\',n?F:1g);4.S[p?\'1y\':\'1R\'](4.5.2e,4.2o)[p?\'1t\':\'V\'](4.J(\'A-11-1E\')).20(\'1E\',p?F:1g);6(4.R.K>0&&(4.R[0].1h==L||4.R[0].1h!=n)&&4.5.1L!=7){4.R.14(9(){a.5.1L(a,4,n)});4.R[0].1h=n}6(4.S.K>0&&(4.S[0].1h==L||4.S[0].1h!=p)&&4.5.1M!=7){4.S.14(9(){a.5.1M(a,4,p)});4.S[0].1h=p}},1Z:9(a){8 b=4.Y==7?\'2q\':(4.Y<4.C?\'19\':\'11\');4.13(\'25\',a,b);6(4.Y!==4.C){4.13(\'26\',a,b,4.C);4.13(\'27\',a,b,4.Y)}6(4.12!==4.G){4.13(\'28\',a,b,4.G);4.13(\'29\',a,b,4.12)}4.13(\'2a\',a,b,4.C,4.G,4.Y,4.12);4.13(\'2b\',a,b,4.Y,4.12,4.C,4.G)},13:9(a,b,c,d,e,f,g){6(4.5[a]==L||(1U 4.5[a]!=\'2B\'&&b!=\'2A\'))z;8 h=1U 4.5[a]==\'2B\'?4.5[a][b]:4.5[a];6(!$.3g(h))z;8 j=4;6(d===L)h(j,c,b);X 6(e===L)4.M(d).14(9(){h(j,4,d,c,b)});X{1k(8 i=d;i<=e;i++)6(i!==7&&!(i>=f&&i<=g))4.M(i).14(9(){h(j,4,i,c,b)})}},1C:9(i){z 4.1P(\'<1v></1v>\',i)},1P:9(e,i){8 a=$(e).V(4.J(\'A-1b\')).V(4.J(\'A-1b-\'+i));a.20(\'3h\',i);z a},J:9(c){z c+\' \'+c+(!4.5.W?\'-3i\':\'-W\')},T:9(e,d){8 a=e.2C!=L?e[0]:e;8 b=!4.5.W?a.1F+r.10(a,\'2D\')+r.10(a,\'1r\'):a.2E+r.10(a,\'2F\')+r.10(a,\'1Y\');6(d==L||b==d)z b;8 w=!4.5.W?d-r.10(a,\'2D\')-r.10(a,\'1r\'):d-r.10(a,\'2F\')-r.10(a,\'1Y\');$(a).y(4.O,w+\'U\');z 4.T(a)},1o:9(){z!4.5.W?4.H[0].1F-r.I(4.H.y(\'3j\'))-r.I(4.H.y(\'3k\')):4.H[0].2E-r.I(4.H.y(\'3l\'))-r.I(4.H.y(\'3m\'))},3n:9(i,s){6(s==L)s=4.5.u;z 1n.3o((((i-1)/s)-1n.3p((i-1)/s))*s)+1}});r.17({3q:9(d){z $.17(q,d||{})},10:9(e,p){6(!e)z 0;8 a=e.2C!=L?e[0]:e;6(p==\'1r\'&&$.2r.2s){8 b={\'1w\':\'1x\',\'3r\':\'3s\',\'1N\':\'1i\'},21,22;$.2G(a,b,9(){21=a.1F});b[\'1r\']=0;$.2G(a,b,9(){22=a.1F});z 22-21}z r.I($.y(a,p))},I:9(v){v=3t(v);z 3u(v)?0:v}})})(3v);',62,218,'||||this|options|if|null|var|function||||||||||||||||||||list|size||||css|return|jcarousel|wrap|first|container|lt|false|last|clip|intval|className|length|undefined|get|div|wh|tail|locked|buttonNext|buttonPrev|dimension|px|addClass|vertical|else|prevFirst|inTail|margin|prev|prevLast|callback|each|scroll|visible|extend|parent|next|animating|item|circular|split|buttons|timer|true|jcarouselstate|auto|initCallback|for|break|hasClass|Math|clipping|animate|while|marginRight|fn|removeClass|before|li|display|block|bind|setup|pos|placeholder|create|stopAuto|disabled|offsetWidth|offset|animation|reloadCallback|buttonNextHTML|buttonPrevHTML|buttonNextCallback|buttonPrevCallback|width|ceil|format|funcResize|unbind|old|after|typeof|remove|scrollTail|both|marginBottom|notify|attr|oWidth|oWidth2|start|easing|itemLoadCallback|itemFirstInCallback|itemFirstOutCallback|itemLastInCallback|itemLastOutCallback|itemVisibleInCallback|itemVisibleOutCallback|buttonNextEvent|click|buttonPrevEvent|height|left|top|indexOf|skin|nodeName|ul|ol|funcNext|funcPrev|reload|init|browser|safari|window|resize|reset|empty|add|prepend|startAuto|onAfterAnimation|object|jquery|marginLeft|offsetHeight|marginTop|swap|new|normal|swing|UL|OL|find|class|children|load|prototype|0px|10px|lock|unlock|has|string|html|append|alert|jCarousel|No|set|items|This|will|cause|an|infinite|loop|Aborting|push|onBeforeAnimation|setTimeout|1000|clearTimeout|isFunction|jcarouselindex|horizontal|borderLeftWidth|borderRightWidth|borderTopWidth|borderBottomWidth|index|round|floor|defaults|float|none|parseInt|isNaN|jQuery'.split('|'),0,{}))

var lastpaymentid;

jQuery(document).ready(function() {	
	//jQuery('#mainnavcontainer').show();
	jQuery('#smenu').show();
	jQuery('textarea#giftnotes').keyup(function(){		
		//get the limit from maxlength attribute
		var limit = parseInt(jQuery(this).attr('maxlength'));
		//get the current text inside the textarea
		var text = jQuery(this).val();
		//count the number of characters in the text
		var chars = text.length;
		
		//check if there are more characters then allowed
		if(chars > limit){
			//and if there are use substr to get the text before the limit
			var new_text = text.substr(0, limit);
			
			//and change the current text with the new text
			jQuery(this).val(new_text);
		}
	});		
    
if( jQuery('#isVisible').val()== "No"){
		jQuery('#rowNewCard').show();
        document.getElementById('new_card').checked=true;
        }else{
            jQuery('#rowNewCard').hide();
        }

});

function toggleShipping() {
	jQuery("input#shipFName").val(jQuery("input#billFirstName").val());
	jQuery("input#shipLName").val(jQuery("input#billLastName").val());
	jQuery("input#shipcompany").val(jQuery("input#billCompany").val());
	jQuery("input#shipAddress1").val(jQuery("input#billAddress").val());
	jQuery("input#shipAddress2").val(jQuery("input#billAddress2").val());
	jQuery("input#shipcity").val(jQuery("input#billCity").val());
	jQuery("select#shipstate").val(jQuery("select#billState").val());
	jQuery("input#shipzip").val(jQuery("input#billZip").val());
	jQuery("select#shipcountry").val(jQuery("select#billcountry").val());
	jQuery("input#shipphone1").val(jQuery("input#billPhone1").val());
	jQuery("input#shipphone2").val(jQuery("input#billPhone2").val());
	jQuery("input#shipphone3").val(jQuery("input#billPhone3").val());
	jQuery("select#shipexistaddr").val(0);
}

function disableAddToBag(itemId){
   jQuery("#"+itemId).attr("disabled","disabled");
}

function displayCVVContent(cardType){
 if(cardType=="amex"){
   jQuery("#amextxtCCID").show();
   jQuery("#deftxtCCID").hide(); 
  }else{
    jQuery("#amextxtCCID").hide();
    jQuery("#deftxtCCID").show(); 
 }
}

function AddNewShipTo() {
	jQuery("input#shipFName").val('');
	jQuery("input#shipLName").val('');
	jQuery("input#shipcompany").val('');
	jQuery("input#shipAddress1").val('');
	jQuery("input#shipAddress2").val('');
	jQuery("input#shipcity").val('');
	jQuery("select#shipstate").val(0);
	jQuery("input#shipzip").val('');
	jQuery("select#shipcountry").val(0);
	jQuery("input#shipphone1").val('');
	jQuery("input#shipphone2").val('');
	jQuery("input#shipphone3").val('');
	jQuery("select#shipexistaddr").val(0);

	$("input#shipFName").attr("readonly",false);
	$("input#shipLName").attr("readonly",false);
	$("input#shipcompany").attr("readonly",false);
	$("input#shipAddress1").attr("readonly",false);
	$("input#shipAddress2").attr("readonly",false);
	$("input#shipcity").attr("readonly",false);
	$("input#shipstate").attr("readonly",false);
	$("input#shipzip").attr("readonly",false);
	$("input#shipcountry").attr("readonly",false);
	$("input#shipphone1").attr("readonly",false);
	$("input#shipphone2").attr("readonly",false);
	$("input#shipphone3").attr("readonly",false);
}


$( function() {
	$("select#billexistaddr").change( function() {
		var id = $(this).val();
		// alert(id);
		if( id == "") {
			// alert(id);
			jQuery("input#billFirstName").val("");
			jQuery("input#billMidInit").val("");
			jQuery("input#billLastName").val("");
			jQuery("input#billCompany").val("");
			jQuery("input#billAddress").val("");
			jQuery("input#billAddress2").val("");
			jQuery("input#billCity").val("");
			jQuery("select#billState").val(0);
			jQuery("input#billZip").val("");
			jQuery("input#billPhone1").val("");
			jQuery("input#billPhone2").val("");
			jQuery("input#billPhone3").val("");
			jQuery("input#billcell1").val("");
			jQuery("input#billcell2").val("");
			jQuery("input#billcell3").val("");
			jQuery("input#billingAddressId").val("");

			$("input#billFirstName").attr("readonly",false);
			$("input#billMidInit").attr("readonly",false);
			$("input#billLastName").attr("readonly",false);
			$("input#billCompany").attr("readonly",false);
			$("input#billAddress").attr("readonly",false);
			$("input#billAddress2").attr("readonly",false);
			$("input#billCity").attr("readonly",false);
			$("input#billState").attr("readonly",false);
			$("input#billZip").attr("readonly",false);
			$("input#billPhone1").attr("readonly",false);
			$("input#billPhone2").attr("readonly",false);
			$("input#billPhone3").attr("readonly",false);
			$("input#billcell1").attr("readonly",false);
			$("input#billcell2").attr("readonly",false);
			$("input#billcell3").attr("readonly",false);
		}
		var aId = 'selectBilling_' + id;
		var content = document.getElementById(aId).innerHTML;
		var mySplitResult = content.split("||");

		var fName = mySplitResult[0];
		var mName = mySplitResult[1];
		var lName = mySplitResult[2];
		var company = mySplitResult[3];
		var address1 = mySplitResult[4];
		var address2 = mySplitResult[5];
		var city = mySplitResult[6];
		var state = mySplitResult[7];
		var zip = mySplitResult[8];
		var country = mySplitResult[9];
		var phone1 = mySplitResult[10];
		var phone2 = mySplitResult[11];
		var phone3 = mySplitResult[12];
		var mobphone1 = mySplitResult[13];
		var mobphone2 = mySplitResult[14];
		var mobphone3 = mySplitResult[15];
		var addressId = mySplitResult[16];

		jQuery("input#billFirstName").val(fName);
		jQuery("input#billMidInit").val(mName);
		jQuery("input#billLastName").val(lName);
		jQuery("input#billCompany").val(company);
		jQuery("input#billAddress").val(address1);
		jQuery("input#billAddress2").val(address2);
		jQuery("input#billCity").val(city);
		jQuery("select#billState").val(state);
		jQuery("input#billZip").val(zip);
		jQuery("input#billPhone1").val(phone1);
		jQuery("input#billPhone2").val(phone2);
		jQuery("input#billPhone3").val(phone3);
		jQuery("input#billcell1").val(mobphone1);
		jQuery("input#billcell2").val(mobphone2);
		jQuery("input#billcell3").val(mobphone3);
		jQuery("input#billingAddressId").val(addressId);

		$("input#billFirstName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billMidInit").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billLastName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCompany").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billAddress").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billAddress2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCity").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billState").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billZip").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone3").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billcell1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billcell2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billcell3").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
	})
})


$( function() {
	$("select#shipexistaddr").change( function() {
		var id = $(this).val();
		if( id == "") {
			// alert(id);
			jQuery("input#shipFName").val("");
			jQuery("input#shipLName").val("");
			jQuery("input#shipcompany").val("");
			jQuery("input#shipAddress1").val("");
			jQuery("input#shipAddress2").val("");
			jQuery("input#shipcity").val("");
			jQuery("select#shipstate").val(0);
			jQuery("input#shipzip").val("");
			jQuery("input#shipphone1").val("");
			jQuery("input#shipphone2").val("");
			jQuery("input#shipphone3").val("");
			jQuery("input#shippingAddressId").val("");
			jQuery("input#shippingContactId").val("");

			$("input#shipFName").attr("readonly",false);
			$("input#shipLName").attr("readonly",false);
			$("input#shipcompany").attr("readonly",false);
			$("input#shipAddress1").attr("readonly",false);
			$("input#shipAddress2").attr("readonly",false);
			$("input#shipcity").attr("readonly",false);
			$("input#shipstate").attr("readonly",false);
			$("input#shipzip").attr("readonly",false);
			$("input#shipphone1").attr("readonly",false);
			$("input#shipphone2").attr("readonly",false);
			$("input#shipphone3").attr("readonly",false);
		}
		var aId = 'selectShipping_' + id;
		var content = document.getElementById(aId).innerHTML;
		var mySplitResult = content.split("||");

		var fName = mySplitResult[0];
		var lName = mySplitResult[1];
		var company = mySplitResult[2];
		var address1 = mySplitResult[3];
		var address2 = mySplitResult[4];
		var city = mySplitResult[5];
		var state = mySplitResult[6];
		var zip = mySplitResult[7];
		var country = mySplitResult[8];
		var phone1 = mySplitResult[9];
		var phone2 = mySplitResult[10];
		var phone3 = mySplitResult[11];
		var addressId = mySplitResult[12];
		var emailId = mySplitResult[13];
		var contactId = mySplitResult[14];

		jQuery("input#shipFName").val(fName);
		jQuery("input#shipLName").val(lName);
		jQuery("input#shipcompany").val(company);
		jQuery("input#shipAddress1").val(address1);
		jQuery("input#shipAddress2").val(address2);
		jQuery("input#shipcity").val(city);
		jQuery("select#shipstate").val(state);
		jQuery("input#shipzip").val(zip);
		jQuery("input#shipphone1").val(phone1);
		jQuery("input#shipphone2").val(phone2);
		jQuery("input#shipphone3").val(phone3);
		jQuery("input#shippingAddressId").val(addressId);
		jQuery("input#shippingContactId").val(contactId);

		$("input#shipFName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipLName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipcompany").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipcity").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipstate").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipzip").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipphone1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipphone2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipphone3").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
	})
})


function loginToCheckoutValidate(frm) {
	// alert(frm);
	var elem = document.getElementById(frm).elements;
	var str = '';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text')) {
			if ( elem[i].name == 'email' && trim(elem[i].value).length == 0) {
				str = 'The required field has not been filled in.\n';
				if (trim(elem[i].value).length == 0)
					elem[i].style.background = 'Yellow';
				else
					elem[i].style.background = 'White';
			} else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
				str += validateEmail(elem[i]);
			}
		}
		if ((elem[i].type == 'password')) {
			if (elem[i].name == 'pass' && trim(elem[i].value).length == 0) {
				str = 'The required field has not been filled in.\n';
				if (trim(elem[i].value).length == 0)
					elem[i].style.background = 'Yellow';
				else
					elem[i].style.background = 'White';
			} else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
				str += validatePassword(elem[i]);
			}
		}
	}
	if (str != '') {
		alert(str);
		return false;
	}
	return true;
}



function checkoutStep1Validate(frm,buttonId) {
	//alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	var reason = "";	
	var validZip = "";
	var validBillEmail = "";
	var validBillCEmail = "";
	var validBillPhone= "";
	var validShipPhone = "";
	var validBillCell = "";
	var validBillPassword = "" ;
    var validBillCPassword = "";
    var emailFlag = false;
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text') || (elem[i].type == 'password')) {
			if ( ( (elem[i].id != 'billMidInit')
					&& (elem[i].id != 'billcell1')
					&& (elem[i].id != 'billcell2')
					&& (elem[i].id != 'billcell3')				
					&& (elem[i].id != 'billPhone1')
					&& (elem[i].id != 'billPhone2')
					&& (elem[i].id != 'billPhone3')	
					&& (elem[i].id != 'shipphone1')
					&& (elem[i].id != 'shipphone2')
					&& (elem[i].id != 'shipphone3')				
					&& (elem[i].id != 'billCompany')
					&& (elem[i].id != 'billAddress2')
					&& (elem[i].id != 'shipcompany')
					&& (elem[i].id != 'shipAddress2'))) {
				reason += validateEmpty(document.getElementById(elem[i].id));
				if (reason != "")
					reason = reason.replace("The required field", elem[i].title);
			}			
			if ((elem[i].name == 'billZip' || elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
				validZip = validateZipCode(elem[i]);
			}			
			if ((elem[i].name == 'billemail') && (elem[i].value.length != 0)) {
				emailFlag= true;
				validBillEmail = validateEmail(elem[i]);
				if(validBillEmail!='') validBillEmail = validBillEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if ((elem[i].name == 'billcemail') && (elem[i].value.length != 0)) {				
				validBillCEmail = validateEmail(elem[i]);
				if(validBillCEmail!='') validBillCEmail = validBillCEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if(((elem[i].name == 'billpass') && (elem[i].value.length != 0))){
			validBillPassword = validatePassword(elem[i]);
			if(validBillPassword!='') validBillPassword = validBillPassword.replace("password", (elem[i].title).toLowerCase());
			}

			if(((elem[i].name == 'billcpass') && (elem[i].value.length != 0))){
			validBillCPassword = validatePassword(elem[i]);
			if(validBillCPassword!='') validBillCPassword = validBillCPassword.replace("password", (elem[i].title).toLowerCase());
			}
		}
		if((elem[i].name == 'billState' || elem[i].name == 'shipstate') && (elem[i].value == 0)){			
			reason += elem[i].title + " has not been selected.\n";
			elem[i].style.background = 'Yellow';
		}
		if(elem[i].name == 'billState' && (elem[i].value != 0)){			
			elem[i].style.background = 'White';
		}
		if(elem[i].name == 'shipstate' && (elem[i].value != 0)){			
			elem[i].style.background = 'White';
		}
	}
	validBillPhone = validateCheckoutPhoneSections('billPhone','Bill Phone');
	validShipPhone = validateCheckoutPhoneSections('shipphone','Ship Phone');
	if(document.getElementById('billcell1').value.length!=0 || document.getElementById('billcell2').value.length!=0 || document.getElementById('billcell3').value.length!=0)
	validBillCell = validateCheckoutPhoneSections("billcell",'Bill Cell Phone');
	reason += validZip + validBillPhone +  validBillCell + validBillEmail + validBillCEmail + validBillPassword + validBillCPassword + validShipPhone;		

	if(emailFlag){
		if (reason=="" && (document.getElementById('billemail').value != document.getElementById('billcemail').value)){
			reason = "Email addresses does not match."
		}
		if (reason=="" && (document.getElementById('billpass').value != document.getElementById('billcpass').value)){
			reason = "Passwords does not match."
		}
	}
	
	if (reason != "") {		
		str+= reason;
		alert(str);
		return false;
	}
	if (jQuery('#termsandcond').attr("checked")) {
        disableAddToBag(buttonId);
	return true;
	}else{
	       jQuery('#termsId').removeClass('isChecked');
		jQuery('#termsId').addClass('isNotChecked');
	      alert(jQuery('#termsandcond').attr("title") + " has not been selected");
	      return false;
	}
}



function googleChecktoutValidate(frm) {
	//alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	var reason = "";
	var validZip = "";
	var validShipPhone = "";
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text')) {
			if ((elem[i].id != 'shipcompany')
                && (elem[i].id != 'shipphone1')
                && (elem[i].id != 'shipAddress2')
                && (elem[i].id != 'shipphone2')
                && (elem[i].id != 'shipphone3')) {
				reason += validateEmpty(document.getElementById(elem[i].id));
				if (reason != "")
					reason = reason.replace("The required field", elem[i].title);
			}
			if ((elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
				validZip = validateZipCode(elem[i]);
			}
		}
		if(elem[i].name == 'shipstate' && (elem[i].value == 0)){
			reason += elem[i].title + " has not been selected.\n";
			elem[i].style.background = 'Yellow';
		}else if(elem[i].name == 'shipstate' && (elem[i].value != 0)){
			elem[i].style.background = 'White';
		}   
	}
    
	validShipPhone = validatePhoneSections('shipphone');
    
	reason += validZip + validShipPhone;
	if (reason != "") {
		str+= reason;
		alert(str);
		return false;
	}

	return true;
}

function updateGoogleShippingCharge(){
var limit = parseInt('5');
		//get the current text inside the textarea
		var text = jQuery('input#shipzip').val();
		//count the number of characters in the text
		var chars = text.length;
                if(chars >= limit){
                    jQuery("#updateShippingCharge").load('/loadshipmethod',{
		zipCode:jQuery('input#shipzip').val(),
                shipMethod: jQuery('input#hiddenshipmethod').val()
});
}
}

function checkoutStep2Validate(frm,buttonId) {
	var flag = document.getElementById('hidCCType').value;
    var profileId='';
	var cardType="";
    var cardError="";
	var existCardType="";
        var cvvValue = '';
	if(flag ==""){
	var elem = document.getElementById(frm).elements;
	var count = document.getElementsByName('PayMethodGroup1').length;		
	for (var i=0; i < count; i++)
	   {
	   if (document.getElementsByName('PayMethodGroup1')[i].checked)
	      var cardType = document.getElementsByName('PayMethodGroup1')[i];
	   }	

    var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
	for(i=0;i<paymentDetailsGroup.length;i++){
	    if(paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value!='new'){
	    	   profileId = paymentDetailsGroup[i].value;
	   }
          }

    	for ( var i = 0; i < elem.length; i++) {
     	if((elem[i].type == 'password') && (elem[i].alt =='cvvText')){
		elem[i].style.background = 'White';
	}
  	}
	     document.getElementById('creditCartId').value = profileId;
	var str = "";	
	var validCVV = "";
        var existValidCVV = "";
	var validCCN = "";
	var validED = "";
	if(profileId==''){
	if(cardType!=""){
	for ( var i = 0; i < elem.length; i++) {
		if (((elem[i].type == 'text') || (elem[i].type == 'password')) && elem[i].alt!='cvvText') {
			if (elem[i].name != 'PayMethodGroup1'){		
				if (trim(elem[i].value).length == 0){
					elem[i].style.background = 'Yellow';
					str = 'The required field has not been filled in.\n';
				}else{					
					elem[i].style.background = 'White';
				}
			}			
			if ((elem[i].name == 'ccId') && (elem[i].value.length != 0)) {
				validCVV = validateCvvCode(cardType, elem[i]);
				if(validCVV!="")
					elem[i].style.background = 'Yellow';
			}
			if ((elem[i].name == 'ccNum') && (elem[i].value.length != 0)) {
				validCCN = validateCreditCardNumber(cardType, elem[i]);
				if(validCCN!="")
					elem[i].style.background = 'Yellow';
			}
		}
		
	}
		validED += validateExpDate(document.getElementById('ccExpMonth').value,document.getElementById('ccExpYear').value)
			if(validED!=""){
					document.getElementById('ccExpMonth').style.background = 'Yellow';
					document.getElementById('ccExpYear').style.background = 'Yellow';				
				}else{
					document.getElementById('ccExpMonth').style.background = 'White';
					document.getElementById('ccExpYear').style.background = 'White';
	}
	}else
  		cardError = "Please select the credit card type.";
    }		
	if(profileId!=''){
	cvvValue = document.getElementById(profileId).value;
        existCardType = document.getElementById('cardType'+profileId).value;
             if(cvvValue!=''){
                  existValidCVV = validateCvvCodeforExistCard(existCardType,cvvValue);
                  if(existValidCVV!='')
		        document.getElementById(profileId).style.background = 'Yellow';
                  else
                        document.getElementById('ccId').value = cvvValue;
             }else
	     {
		  str = 'The required field has not been filled in.\n';
		  document.getElementById(profileId).style.background = 'Yellow';
             }

	}
	str += validCCN + validED + validCVV + existValidCVV +cardError;	
	if (str != "") {		
		alert(str);
		return false;
	}	
        disableAddToBag(buttonId);
	return true;
	}
}


function forgotPassword(type){
    var reason = "";
    if(type=='login'){
    reason += validateEmail(document.frmLogin.loginemail);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }else{
        document.frmLogin.actionParam.value="lostpass";
        document.frmLogin.submit();
    }
    }else{
    	 reason += validateEmail(document.logintocheckout.loginemail);
    	    if (reason != "") {
    	        alert("Some fields need correction:\n" + reason);
    	        return false;
    	    }else{
    	        document.logintocheckout.actionParam.value="lostpass";
    	        document.logintocheckout.submit();
    	    }
    }
}

  function searchAction(){
        var q= $('#search-text').val();
        if(q == '' || q == 'SEARCH UNCLE VIC'){
            alert('Please enter valid data');
            return false;
        }
        return true;
    }

function submitStep1Form(login) {
	var reason = "";
	var email = document.getElementById('loginemail')
	var pass = document.getElementById('loginpasswd')
	reason += validateEmail(email);
	pass.style.background = 'White';
	if (login) {
		reason += validatePassword(pass);
	}

	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	} else {
		if (login) {
			var url = "/checklogin/" + pass.value + "/" + email.value;
			jQuery.get(url, function(data) {
				gotoStep2(data, login);
			});
		} else {
			document.cookie = "acctEmail=" + email.value + "; path=/;";
			gotoStep2("", login);
		}
	}
}
function gotoStep2(data, login) {
	data = trim(data);
	if (data == "success") { // login sucessful
		jQuery("#lostpass").html('');
		jQuery("#addcustomerhead").hide();
		jQuery("#existcustomerhead").show();
		// hideShipAddressForm();
		loadShipAddys();
		jQuery('#payform').html('');
		edit(2);
		return false;
	} else {
		if (login) { // login failed
			jQuery("#lostpass").html(data);
			jQuery("#checkout2edit").hide();
			jQuery("#checkout3edit").hide();
			jQuery("#checkout4edit").hide();
			return false;
		} else { // no login
			jQuery("#lostpass").html('');
			jQuery("#checkout2edit").show();
			loadShipAddys();
			edit(2);
			return false;
		}
	}
}


function giftNote() {
	if (jQuery('#addgiftcheck').attr("checked")) {
		jQuery("#addgiftsub").hide();
		jQuery("#addgiftrow").show();
	} else {
		jQuery("#addgiftrow").hide();
		jQuery("#addgiftsub").show();
		jQuery("#giftnotes").val('');
	}
}


/*function submitShipAddress() {
	var reason = "";
	reason += validateEmpty(document.getElementById('shipFirstName'));
	if (reason != "")
		reason = reason.replace("The required field", "First Name");
	reason += validateEmpty(document.getElementById('shipLastName'));
	if (reason != "")
		reason = reason.replace("The required field", "Last Name");
	reason += validateEmpty(document.getElementById('shipAddress'));
	if (reason != "")
		reason = reason.replace("The required field", "Address");
	reason += validateEmpty(document.getElementById('shipCity'));
	if (reason != "")
		reason = reason.replace("The required field", "City");
	reason += validateEmpty(document.getElementById('shipState'));
	if (reason != "")
		reason = reason.replace("The required field", "State");
	reason += validateZIP(document.getElementById('shipZip'));
	reason += validatePhoneSections("shipPhone");
	reason += validateEmail(document.getElementById('shipEmail'));

	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		jQuery("#checkout3edit").hide();
		jQuery("#checkout4edit").hide();
		return false;
	} else {

		var param = '/fname/'
				+ escape(jQuery("input#shipFirstName").val())
				+ '/lname/'
				+ escape(jQuery("input#shipLastName").val())
				+ '/company/'
				+ escape(jQuery("input#shipCompany").val())
				+ '/address/'
				+ escape(jQuery("input#shipAddress").val())
				+ '/address2/'
				+ escape(jQuery("input#shipAddress2").val())
				+ '/city/'
				+ escape(jQuery("input#shipCity").val())
				+ '/state/'
				+ jQuery("#shipState option:selected").val()
				+ '/zip/'
				+ escape(jQuery("input#shipZip").val())
				+ '/phone/'
				+ escape(jQuery("input#shipPhone1").val() + '-'
						+ jQuery("input#shipPhone2").val() + '-'
						+ jQuery("input#shipPhone3").val()) + '/email/'
				+ escape(jQuery("input#shipEmail").val())
		jQuery.get('/index/address/pl/add' + param, function() {
			jQuery("#addshipform").hide();
			jQuery("#shipform").html('');
			jQuery("#step2continue").show();
			loadShipAddys();
		});
		return false;
	}
}*/

function showPayEditForm(id) {
	if (typeof id == "undefined") {
		id = '';
	}
	jQuery("#paymsg").html('');
	jQuery("#step3continue").hide();
	// var url = "checkoututil.asp?action=payform&id="+id+"&force="+ new
	// Date().getTime();
	var url = "/index/payform/";
	jQuery('#payform').load(
			url,
			function() {
				var ship = jQuery(
						"#shipaddress" + jQuery("input#orderShipID").val())
						.html();
				if (ship.indexOf("will-call pick up") > 0)
					jQuery("#useship").hide();
				jQuery("#billFirstName").focus();
			});
}

function showCV2(id) {
	jQuery(".cardcode").hide();
	jQuery("#txtCardCode" + id).show();
	jQuery("#cardcodelabel" + id).show();
	jQuery("#cardcodeQ" + id).show();

}

function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    if(fld.type == 'select-one'){    	
    	if(fld.value == 0){
    		fld.style.background = 'Yellow';
            error = "The required field has not been filled in.\n"
    	}else{
    		fld.style.background = 'White';
    	}    	
    }
    return error;
}


function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if (fld.value.length < 8) {
        error = "The password length should be 8 characters minimum. \n";
        fld.style.background = 'Yellow';
    } else if (fld.value.length > 15) {
        error = "The password length should be 14 characters maximum. \n";
        fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
    return error;
}


function trim(s)
{
    return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with
														// whitespace trimmed
														// off
    // var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    // var emailFilter = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$');
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    // var emailFilter = new
	// RegExp('[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}');
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              // test email for
														// illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}


function validatePhoneSections(fldname) {
    var error = "";

    var s1 = document.getElementById(fldname+'1')
    var s2 = document.getElementById(fldname+'2')
    var s3 = document.getElementById(fldname+'3')
    fld = s1.value + s2.value + s3.value;

    if (fld == "") {
        error = "The phone number has not been filled in.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else if (isNaN(parseInt(fld))) {
        error = "The phone number contains illegal characters.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else if (fld.length < 10) {
        error = "The phone number is the wrong length.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else {
        s1.style.background = 'White';
        s2.style.background = 'White';
        s3.style.background = 'White';
    }
    return error;
}


function validateTelephoneSection(fldname) {
    var error = "";
    var s1 = document.getElementById(fldname)

    if (s1.value == "") {
        error = "The phone number has not been filled in.\n";
        s1.style.background = 'Yellow';
    } else if (isNaN(parseInt(s1.value))) {
        error = "The phone number contains illegal characters.\n";
        s1.style.background = 'Yellow';
    } else if (s1.value.length < 10) {
        error = "The phone number is the wrong length.\n";
        s1.style.background = 'Yellow';
    } else {
        s1.style.background = 'White';
    }
    return error;
}


function validateCheckoutPhoneSections(fldname,title) {
    var error = "";

    var s1 = document.getElementById(fldname+'1')
    var s2 = document.getElementById(fldname+'2')
    var s3 = document.getElementById(fldname+'3')
    fld = s1.value + s2.value + s3.value;

    if (fld == "") {
        error = title+" has not been filled in.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else if (isNaN(parseInt(fld))) {
        error = title+" contains illegal characters.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else if (fld.length < 10) {
        error = title+" is the wrong length.\n";
        s1.style.background = 'Yellow';
        s2.style.background = 'Yellow';
        s3.style.background = 'Yellow';
    } else {
        s1.style.background = 'White';
        s2.style.background = 'White';
        s3.style.background = 'White';
    }
    return error;
}


function validateZIP(fld)  {
    var error = "";
    var valid = "0123456789-";
    var hyphencount = 0;
    var field = fld.value;

    if (field.length!=5 && field.length!=10) {
        // alert("Please enter your 5 digit or 5 digit+4 zip code.");
        // return false;
        error = "Please enter your 5 digit or 5 digit+4 zip code.\n";
    }
    for (var i=0; i < field.length; i++) {
        temp = "" + field.substring(i, i+1);
        if (temp == "-") hyphencount++;
        if (valid.indexOf(temp) == "-1") {
            error = "Invalid characters in your zip code.  Please try again.\n";
        }
        if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
            error = "The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'. Please try again.\n";
        }
    }

    if (error.length>0){
        fld.style.background = 'Yellow';
    }
    else{
        fld.style.background='White';
    }

    return error;
}


function validateContactUsFields(frm) {
    var str = 'Following required field has not been filled in.\n';
    var reason = "";
    var email = "";
    var phoneNo = "";
    var needHelp = "";
    var isChooseHelp="";
    var allElements = document.getElementById(frm).elements;
    var needHelpType = document.getElementById('needHelpType').value;
    for(i=0; i< allElements.length; i++) {
    	if(allElements[i].type != 'hidden'){
    		var isMandatory = document.getElementById(allElements[i].id).getAttribute("isMandatory");
    		if(isMandatory=='true' && allElements[i].type=="text" && allElements[i].id!="txtCAPTCHA"){
    			 reason += validateEmpty(document.getElementById(allElements[i].id));
    		if (reason != "")
		         reason = reason.replace("The required field", allElements[i].title);
    		}
		if(isMandatory=='true' && allElements[i].type=="checkbox"){
                         if(!document.getElementById(allElements[i].id).checked)
                             reason += allElements[i].value +" has not been selected in.\n";
    		}
//                if((allElements[i].id=='txtCAPTCHA') && (allElements[i].value.length == 0))
//                   allElements[i].style.background = 'Yellow';
//		else if((allElements[i].id=='txtCAPTCHA') && (allElements[i].value.length != 0))
//                   allElements[i].style.background = 'White';
                if(needHelpType=='dropDownOption'){
                if((allElements[i].id=='needhelp') && (allElements[i].value=='')){
                   document.getElementById('needforhelp').style.background = 'Yellow';
 		   needHelp = "Need help has not been selected in.\n";
		}else if((allElements[i].id=='needhelp') && (allElements[i].value!=''))
                   document.getElementById('needforhelp').style.background = '';
                }
               if((allElements[i].title=='Email') && (allElements[i].value.length != 0))
               email = validateEmail(document.getElementById(allElements[i].id));
               if((allElements[i].title=='Telephone Number') && (allElements[i].value.length != 0))
                  phoneNo = validateTelephoneSection(allElements[i].id);                 
    	     }
    }
		if(needHelpType=='radioOption'){
                var count = document.getElementsByName('needhelp').length;		
		for (var i=0; i < count; i++)
	   	{
	   	if (document.getElementsByName('needhelp')[i].checked)
	           var isChooseHelp = document.getElementsByName('needhelp')[i];
	        }
		if(isChooseHelp==''){
		   document.getElementById('needforhelp').style.background = 'Yellow';
 		   needHelp = "Need help has not been selected in.\n";		
                 }else
                   document.getElementById('needforhelp').style.background = '';
		}
		
        reason += needHelp +email + phoneNo;

        if (reason!= "") {
	str += reason;
		alert(str);
		return false;
	}
	return true;
}

function validateExpDate(expmo,expyr) {
    var error="";
    var ccExpYear = expyr;
    var ccExpMonth = expmo;
    var expDate=new Date();
    expDate.setFullYear(ccExpYear, ccExpMonth, 1);
    var today = new Date();
    // alert(expDate+'=='+today);
    if (expDate < today) {
        // Credit Card is expire
        // expmo.style.background = 'Yellow';
        // expyr.style.background = 'Yellow';
        error = "Credit Card is expired.\n";
    }
    return error;
}

function validateLoginFormOnSubmit(theForm) {
    theForm.action.value="login";
    var reason = "";
    reason += validateEmail(theForm.loginemail);
    reason += validatePassword(theForm.loginpasswd);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function validateRegisterFormOnSubmit(theForm) {
    var reason = "";
    reason += validateEmpty(theForm.firstname);
    if (reason!="") reason = reason.replace("The required field","First Name")
    reason += validateEmpty(theForm.lastname);
    if (reason!="") reason = reason.replace("The required field","Last Name")
    reason += validateEmail(theForm.email);
    if ((reason=="") && (theForm.email.value != theForm.cemail.value)){
        reason = "Email addresses does not match."
    }
    reason += validatePassword(theForm.passwd);
    if ((reason=="") && (theForm.passwd.value != theForm.passwd2.value)){
        reason = "Passwords does not match."
    }
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}



function validateCvvCode(optName, fldId) {
    var error="";
    // Get the text of the selected card type
    var cardType = optName.value;
    // Get the value of the CVV code
    var cvvCode = fldId.value;
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
        case '002':
        case '001':
        case '004':
            cvvDigits = 3;
            break;
        case '003':
            cvvDigits = 4;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if( !(cvvCode.length == cvvDigits && regExp.test(cvvCode)) ) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}

function validateCvvCodeforExistCard(cardType,cvvCode) {
    var error="";
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
        case 'VISA':
        case 'MASTER':
        case 'DISCOVER':
            cvvDigits = 3;
            break;
        case 'AMERICAN EXPRESS':
            cvvDigits = 4;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if( !(cvvCode.length == cvvDigits && regExp.test(cvvCode)) ) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}


// Second
function validateCreditCardNumber(optName, fldId) {
    var error="";
    // Get the text of the selected card type
    var cardType = optName.value;
    // Get the value of the CVV code
    var ccnNumber = fldId.value;
    var ccnDigits = 0;
    switch (cardType.toUpperCase()) {
        case '002':
        case '001':
        case '004':
            ccnDigits = 16;
            break;
        case '003':
            ccnDigits = 15;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + ccnDigits + '}');
    if( !(ccnNumber.length == ccnDigits && regExp.test(ccnNumber)) ) {
        error = "Invalid Credit Card Number.\n";
    }
    return error;
}

//Second
function validateCreditCardDate(fld) {	
	var error="";
	var d = new Date();
	var cur_date = d.getMonth() + 1 ;
	if(fld.value < 13 ) {		
		if(fld.value < cur_date) {
			error = "Credit card date expired.";
		}
	} else {
		if(fld.value < d.getFullYear()) {
			error = "Credit card date expired.";
		}
	}	
	return error;
}

// Second
function validateZipCode(fld) {
    var error = "";
    var regExp = new RegExp('^[0-9]*$');
    if(fld.value.length != 5 ){
        fld.style.background = 'Yellow';
        error += "Please enter your 5 digit or 5 digit+4 zip code.\n";
    }
    if( !(regExp.test(fld.value)) ) {
        fld.style.background = 'Yellow';
        error += "Not a valid Zip Code.\n";
    }
    return error;
}

function validateQuantity(frm) {
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    for ( var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ( elem[i].name == 'hidItemQty[]') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0){
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.\n";
                } else if( !(regExp.test(elem[i].value) && parseInt(elem[i].value,10) > 0) ){
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.\n";
                } else {
                    elem[i].style.background = 'White';
                }
            }
        }
    }
    str += validNo;
    if (str != '') {
        alert(str);
        return false;
    }
    return true;
}

function validateQuantityAtItem(frm,itemId) {
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    var bulkOrder = "";
    var maxQty = document.getElementById('maximumOrderQuantity').value;
    for ( var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ( elem[i].name == 'itemQty') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0){
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.\n";
                } else if( !(regExp.test(elem[i].value) && parseInt(elem[i].value,10) > 0) ){
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.\n";
                } else if(parseInt(elem[i].value,10) > parseInt(maxQty,10)){
                    elem[i].style.background = 'Yellow';
                    bulkOrder = "Please contact us for quantity orders.\n";
                } else {
                    elem[i].style.background = 'White';
                }
            }
        }
    }
    str += validNo + bulkOrder;
    if (str != '') {
        alert(str);
        return false;
    }
	disableAddToBag(itemId);
    return true;
}

function wayToCheckout(ele) {
    if(ele == 'securecheckout') {
        document.getElementById('checkout_action').value="secureCheckout";
        return true;
    } else {
        document.getElementById('checkout_action').value="googleCheckout";
        return true;
    }
}

function subscriptionEmail(fld){
    var error = validateEmail(fld);
    if(error == ""){
        return true;
    }
    alert(error);
    return false;
}

function managesubs(){
    var error = validateEmpty(document.getElementById('txtFirstname'));
if(error!='') error = error.replace("The required field","First name");
    error += validateEmpty(document.getElementById('txtLastname'));
if(error!='') error = error.replace("The required field","Last name");
    error += validateZIP(document.getElementById('txtZipcode'));
    if(error == ""){
    	onchangeSubscriptionAction();
     return true;
    }
    alert(error);
    return false;
}

function onchangeSubscriptionAction(){

	    var hidSubscribeIds = new Array();
	    var hidUnSubscribeIds = new Array();
	    	var newsLetter = document.getElementsByName('newsLetter');
	    	for(i=0,j=0,k=0;i<newsLetter.length;i++){
	    		if(newsLetter[i].checked){
	    			hidSubscribeIds[j] = newsLetter[i].value;
	    			++j;
	    		}else{
	    			hidUnSubscribeIds[k] = newsLetter[i].value;
	    			++k;
	    		}
	    	}
	    	document.getElementById('hidSubscribeIds[]').value = hidSubscribeIds;
	    	document.getElementById('hidUnSubscribeIds[]').value = hidUnSubscribeIds;

}

function validateFormOnSubmitFrd() {
    var reason = "";
    var yourEmail = "";
    var friendEmail = "";
    reason += validateEmpty(document.getElementById('yourname'));
	if(reason!='')
  	reason = reason.replace("The required field","Your Name");
    yourEmail = validateEmail(document.getElementById('youremail'));
	if(yourEmail!='')
  	yourEmail = yourEmail.replace("email","your email");
    reason += validateEmpty(document.getElementById('friendname'));
	if(reason!='')
  	reason = reason.replace("The required field","Friend Name");
    friendEmail += validateEmail(document.getElementById('friendemail'));
	if(friendEmail!='')
  	friendEmail = friendEmail.replace("email","friend email");
    if((document.getElementById('txtCAPTCHA').value.length == 0))
        document.getElementById('txtCAPTCHA').style.background = 'Yellow';
    else if((document.getElementById('txtCAPTCHA').value.length != 0))
        document.getElementById('txtCAPTCHA').style.background = 'White';

	reason += yourEmail + friendEmail;
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        //alert("Please be sure highlighted fields contain valid information.");
        return false;
    }

    return true;
}

function validateLoginPassForm(theForm) {
	var reason = "";
	reason += validateEmpty(theForm.txtNewFirstName);
	if (reason!="") reason = reason.replace("The required field","First Name")
	reason += validateEmpty(theForm.txtNewLastName);
	if (reason!="") reason = reason.replace("The required field","Last Name")
	reason += validateEmail(theForm.txtNewLogin);
	if (theForm.txtOldPassword.value.length!=0)
		reason += validatePassword(theForm.txtOldPassword);
	if (theForm.txtNewPassword.value.length!=0)
		reason += validatePassword(theForm.txtNewPassword);

	if (reason != "") {
	alert("Some fields need correction:\n" + reason);
	return false;
	}
	jQuery("#changepass").hide();
	jQuery("#buttonrow").hide();
	jQuery("#ajaxLoader").show();
	document.frmchangepass.submit();
}

function showhidePass() {
 if( document.getElementById('changepass').style.display=='none' ){
   jQuery("#changepass").show();
   jQuery("#buttonrow").show();
 }else{
   jQuery("#changepass").hide();
   jQuery("#buttonrow").hide();
   if(document.getElementById('changepasserr')){jQuery("#changepasserr").hide();}
 }
}

function addAddress(){
	// alert(jQuery("#addshipform").html().length);
	if (jQuery("#addshipform").html().length==0){
		jQuery('#addshipform').replaceWith("<div id='addshipform'></div>");
		jQuery('#addshipform').load('/addaddress/');
	}
}

function submitShipAddress(){
	var reason = "";
	reason += validateEmpty(document.getElementById('shipFirstName'));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('shipLastName'));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('shipAddress'));
	if (reason!="") reason = reason.replace("The required field","Address");
	reason += validateEmpty(document.getElementById('shipCity'));
	if (reason!="") reason = reason.replace("The required field","City");
	reason += validateEmpty(document.getElementById('shipState'));
	if (reason!="") reason = reason.replace("The required field","State");
	reason += validateZIP(document.getElementById('shipZip'));
	reason += validatePhoneSections("shipPhone");
	
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{
		jQuery("#addshipform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/address",{
			fname: jQuery("input#shipFirstName").val(),
			lname: jQuery("input#shipLastName").val(),
			company : jQuery("input#shipCompany").val(),
			address:jQuery("input#shipAddress").val(),
			address2:jQuery("input#shipAddress2").val(),
			city:jQuery("input#shipCity").val(),				
			state: jQuery("#shipState option:selected").val(),
			zip: jQuery("input#shipZip").val(),
			phone: jQuery("input#shipPhone1").val()+'-'+jQuery("input#shipPhone2").val()+'-'+jQuery("input#shipPhone3").val(),			
			pl: "add"
		 }, function(data) {
			jQuery("#addshipform").html('');
			jQuery("#ajaxLoader").hide();
			loadShipAddys();
	 }); 
		// return false;
	}
}
function updateShipRow(id){
	var reason = "";
	reason += validateEmpty(document.getElementById('shipFirstName'+id));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('shipLastName'+id));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('shipAddress'+id));
	if (reason!="") reason = reason.replace("The required field","Address");
	reason += validateEmpty(document.getElementById('shipCity'+id));
	if (reason!="") reason = reason.replace("The required field","City");
	if(document.getElementById('shipState'+id).value=='...'){
		if (reason!="")   
	        reason += "The required field","State";
		else
			reason = "State";
	}
	reason += validateZIP(document.getElementById('shipZip'+id));
	reason += validatePhoneSections(id+"shipPhone");
	
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{
		jQuery("#addshipform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/address",{
			id: id,
			fname: jQuery("input#shipFirstName"+id).val(),
			lname: jQuery("input#shipLastName"+id).val(),
			company : jQuery("input#shipCompany"+id).val(),
			address: jQuery("input#shipAddress"+id).val(),
			address2: jQuery("input#shipAddress2"+id).val(),
			city: jQuery("input#shipCity"+id).val(),				
			state: jQuery("#shipState"+id+" option:selected").val(),
			zip:  jQuery("input#shipZip"+id).val(),
			phone: jQuery("input#"+id+"shipPhone1").val()+'-'+jQuery("input#"+id+"shipPhone2").val()+'-'+jQuery("input#"+id+"shipPhone3").val(),				
			contactid: jQuery("input#contactId"+id).val(),
			accountid: jQuery("input#accountId"+id).val(),
			pl: "update"
		 }, function(data) {		 
			 jQuery("#addshipform").html('');
			 jQuery("#ajaxLoader").hide();
			 loadShipAddys();
	 });
	}
}

function deleteShipRow(id){
	jQuery("#ajaxLoader").show();
	jQuery.post('/deleteshippingaddress',{
		contactId:jQuery("input#contactId"+id).val()
	},function(){ 
		loadShipAddys();
		jQuery("#ajaxLoader").hide();
	}); 
}


function loadShipAddys(){
	jQuery("#shiplist").html('<p><span class=processing>Loading...</span></p>');
	jQuery('#shiplist').load("/fetchaddress/");
}

function changeShippingOption(shipMethod,postalCode,status){
	var temp = shipMethod;
	$("#shipMethod").val(temp); 
	if (jQuery('#willCallRadio').attr("checked")) {
		jQuery("#zip").attr("readonly",true).val('').css({'background-color':'#D4D4D4'});
		jQuery("#gobtn").attr("disabled","disabled");		
    		var shippingAmount = '0.00' ;
    		var result = (parseFloat(shippingAmount) + parseFloat($("#hiddensubtotal").val()) + 
		parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    		$("#hiddentotal").val(result);
    		$("#hiddenshipmethod").val(temp);
    		$("#hiddenshipping").val(shippingAmount);
    		$('#hiddentotal').formatCurrency('#total');
    		$('#hiddenshipping').formatCurrency('#shipping');
		jQuery('#shippmentDiv').hide();
  		if(shippingAmount==0)
    			$('#shippingdiv').hide();
  		else
    			$('#shippingdiv').show();
    			$("#hiddentotal").hide();
    			$("#hiddenshipping").hide();	
	} else {
		jQuery("#zip").attr("readonly",false).val(postalCode).css({'background-color':''});
		jQuery("#gobtn").removeAttr("disabled");	
		jQuery('#shippmentDiv').show();
		if(status=='Yes')	
 		jQuery("#shipMethod").removeAttr("disabled");
    		updateTotalValue();
	}
}

function showHideShipRow(id) {
 if( document.getElementById('editShipRow'+id).style.display=='none' ){
   jQuery("#displayShipRow"+id).hide();
   jQuery("#editShipRow"+id).show();
 }else{
	jQuery("#displayShipRow"+id).show();
   	jQuery("#editShipRow"+id).hide();
 }
}

function addPayment(){
	if (jQuery("#payform").html().length==0){
		jQuery('#payform').replaceWith("<div id='payform'></div>");
		jQuery('#payform').load('/addcreditcard');
	}
}

function loadPayments(){	
	jQuery("#paymentlist").html('<p><span class=processing>Loading...</span></p>')
	jQuery('#paymentlist').load("/paymentdetail");
}

function showHideBillRow(id) {
 if( document.getElementById('editBillRow'+id).style.display=='none' ){
   jQuery("#displayBillRow"+id).hide();
   jQuery("#editBillRow"+id).show();
 }else{
	jQuery("#displayBillRow"+id).show();
   	jQuery("#editBillRow"+id).hide();
 }
}

function savePayment(){
	var reason = "";
	var validCCN = "";
	var validCVV = "";
	reason += validateEmpty(document.getElementById('billFirstName'));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('billLastName'));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('billAddress'));
	if (reason!="") reason = reason.replace("The required field","Address");
	reason += validateEmpty(document.getElementById('billCity'));
	if (reason!="") reason = reason.replace("The required field","City");
	reason += validateEmpty(document.getElementById('billState'));
	if (reason!="") reason = reason.replace("The required field","State");
	reason += validateZIP(document.getElementById('billZip'));
	reason += validatePhoneSections("billPhone");
	reason += validateEmpty(document.getElementById('selCardType'));
	if (reason!="") reason = reason.replace("The required field","Credit Card Type");
        reason +=validateEmpty(document.getElementById('txtCreditCard'));
        if (reason!="") reason = reason.replace("The required field","Credit Card Number");

        if(document.getElementById('txtCreditCard').value.length!=0){       
	validCCN = validateCreditCardNumber(document.getElementById('selCardType'), document.getElementById('txtCreditCard'));
	if(validCCN !="") {
		document.getElementById('txtCreditCard').style.background = 'Yellow';
		reason += validCCN;
	}
	}

	reason += validateEmpty(document.getElementById('selExpMonth'));
	if (reason!="") reason = reason.replace("The required field","Expiration Month");
	reason += validateEmpty(document.getElementById('selExpYear'));
	if (reason!="") reason = reason.replace("The required field","Expiration Year");
	if (reason=="") reason += validateExpDate(document.getElementById('selExpMonth').value,document.getElementById('selExpYear').value)
	 reason +=validateEmpty(document.getElementById('txtCardVerificationValue'));
        if (reason!="") reason = reason.replace("The required field","Card Verification Value");

	if(document.getElementById('txtCardVerificationValue').value.length!=0){
        validCVV = validateCvvCode(document.getElementById('selCardType'), document.getElementById('txtCardVerificationValue'));
        if(validCVV!=""){
             document.getElementById('txtCardVerificationValue').style.background = 'Yellow';
		reason += validCVV;
	} 
	} 
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{
		jQuery("#payform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/createcreditcard",{
			fname: jQuery("input#billFirstName").val(),
			lname: jQuery("input#billLastName").val(),
			company : jQuery("input#billCompany").val(),
			address:jQuery("input#billAddress").val(),
			address2:jQuery("input#billAddress2").val(),
			city:jQuery("input#billCity").val(),				
			state: jQuery("#billState option:selected").val(),
			zip: jQuery("input#billZip").val(),
			phone: jQuery("input#billPhone1").val()+'-'+jQuery("input#billPhone2").val()+'-'+jQuery("input#billPhone3").val(),
			cname: jQuery("input#billFirstName").val()+' '+jQuery("input#billLastName").val(),
			ctype: jQuery("#selCardType option:selected").val(),
			cnum: jQuery("input#txtCreditCard").val(),
			cmonth: jQuery("#selExpMonth option:selected").val(),
			cyear: jQuery("#selExpYear option:selected").val(),			
			cvv:jQuery("input#txtCardVerificationValue").val(),		
			pl: "add"
		 }, function(data) {	   		
			jQuery("#payform").html('');
			jQuery("#ajaxLoader").hide();
			 // AfterSavePayment(data);
			loadPayments();
	 }); 
	}
}


//New or old card option choosen
function image1(value){
var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
    if(value=="new"){
        document.getElementById('rowNewCard').style.display="block";
	for(i=0;i<paymentDetailsGroup.length;i++){
	           jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'white'});
          }
    }else {
        document.getElementById('rowNewCard').style.display="none";
        document.getElementById('new_card').checked=false;
	jQuery("input#ccId").val('');
	for(i=0;i<paymentDetailsGroup.length;i++){
	    if(paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value!='new'){
	    	   jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'white'});
	   }else{
		   jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'white'});
		}
          }
    }
}


function updateBillRow(id){
	var reason = "";
	reason += validateEmpty(document.getElementById('billFirstName'+id));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('billLastName'+id));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('billAddress'+id));
	if (reason!="") reason = reason.replace("The required field","Address");	
	
	reason += validateEmpty(document.getElementById('billCity'+id));
	if (reason!="") reason = reason.replace("The required field","City");
	reason += validateEmpty(document.getElementById('billState'+id));
	if (reason!="") reason = reason.replace("The required field","State");
	reason += validateZIP(document.getElementById('billZip'+id));
	reason += validatePhoneSections(id+"billPhone");
	reason += validateEmpty(document.getElementById('txtNameonCard'+id));	
	
	if (reason!="") reason = reason.replace("The required field","Name on card");
	reason += validateEmpty(document.getElementById('selExpMonth'+id));
	if (reason!="") reason = reason.replace("The required field","Expiration Month");
	reason += validateEmpty(document.getElementById('selExpYear'+id));
	if (reason!="") reason = reason.replace("The required field","Expiration Year");
	if (reason=="") reason += validateExpDate(document.getElementById('selExpMonth'+id).value,document.getElementById('selExpYear'+id).value)	
	
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{	

		jQuery.post("/createcreditcard",{
			id: id,
			fname: escape(jQuery("input#billFirstName"+id).val()),
			lname: escape(jQuery("input#billLastName"+id).val()),
			company : escape(jQuery("input#billCompany"+id).val()),
			address:escape(jQuery("input#billAddress"+id).val()),
			address2:escape(jQuery("input#billAddress2"+id).val()),
			city:escape(jQuery("input#billCity"+id).val()),				
			state: jQuery("#billState"+id+" option:selected").val(),
			zip: escape(jQuery("input#billZip"+id).val()),
			phone: escape(jQuery("input#"+id+"billPhone1").val()+'-'+jQuery("input#"+id+"billPhone2").val()+'-'+jQuery("input#"+id+"billPhone3").val()) ,
			cname: escape(jQuery("input#txtNameonCard"+id).val()),
			contactid: escape(jQuery("input#contactId"+id).val()),
			accountid: escape(jQuery("input#accountId"+id).val()),
			maskednumber: escape(jQuery("input#maskednumber"+id).val()),
			paymentprofileid: escape(jQuery("input#paymentprofileId"+id).val()),
			profileid: escape(jQuery("input#profileId"+id).val()),
			cmonth: jQuery("#selExpMonth"+id+" option:selected").val(),
			cyear: jQuery("#selExpYear"+id+" option:selected").val(),			
			pl: "update"
		 }, function(data) {
			 alert(data);
			jQuery("#payform").hide();
			jQuery("#payform").html('');
			 // AfterSavePayment(data);
			loadPayments();
	 }); 
	}
}

function deleteBillRow(id){
	jQuery("#payform").hide();
	jQuery("#ajaxLoader").show();
		jQuery.post('/deletebillingaddress',{
			contactId:jQuery("input#contactId"+id).val(),
			creditCartId:jQuery("input#creditCartId"+id).val()
		}, function(data) {
			jQuery("#payform").html('');
			jQuery("#ajaxLoader").hide();
			loadPayments();
	 }); 
} 
function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });

    jQuery('.jcarousel-control a').bind('click', function() {
        alert("esese");
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    jQuery('.jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

    jQuery('#mycarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });

};
