CDN_SERVER="http://www.hungryforchange.com";
RELEASE_VERSION="84.01";
/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);


/*!
 * jQuery UI 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
return;
}

//Helper functions and ui object
$.extend( $.ui, {
version: "1.8.4",

// $.ui.plugin is deprecated.  Use the proxy pattern instead.
plugin: {
add: function( module, option, set ) {
var proto = $.ui[ module ].prototype;
for ( var i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode ) {
return;
}

for ( var i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},

contains: function( a, b ) {
return document.compareDocumentPosition ?
a.compareDocumentPosition( b ) & 16 :
a !== b && a.contains( b );
},

hasScroll: function( el, a ) {

//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}

var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;

if ( el[ scroll ] > 0 ) {
return true;
}

// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
},

isOverAxis: function( x, reference, size ) {
//Determines when x coordinate is over "b" element axis
return ( x > reference ) && ( x < ( reference + size ) );
},

isOver: function( y, x, top, left, height, width ) {
//Determines when x, y coordinates is over "b" element
return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
},

keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
}
});

//jQuery plugins
$.fn.extend({
_focus: $.fn.focus,
focus: function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
this._focus.apply( this, arguments );
},

enableSelection: function() {
return this
.attr( "unselectable", "off" )
.css( "MozUserSelect", "" );
},

disableSelection: function() {
return this
.attr( "unselectable", "on" )
.css( "MozUserSelect", "none" );
},

scrollParent: function() {
var scrollParent;
if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
}

return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
},

zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}

if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ) );
if ( !isNaN( value ) && value != 0 ) {
return value;
}
}
elem = elem.parent();
}
}

return 0;
}
});

$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};

function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
if ( border ) {
size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
}
});
return size;
}

$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}

return this.each(function() {
$.style( this, type, reduce( this, size ) + "px" );
});
};

$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}

return this.each(function() {
$.style( this, type, reduce( this, size, true, margin ) + "px" );
});
};
});

//Additional selectors
function visible( element ) {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
}

$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},

focusable: function( element ) {
var nodeName = element.nodeName.toLowerCase(),
tabIndex = $.attr( element, "tabindex" );
if ( "area" === nodeName ) {
var map = element.parentNode,
mapName = map.name,
img;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName )
? !element.disabled
: "a" == nodeName
? element.href || !isNaN( tabIndex )
: !isNaN( tabIndex ))
// the element and all of its ancestors must be visible
&& visible( element );
},

tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" );
return ( isNaN( tabIndex ) || tabIndex >= 0 ) && $( element ).is( ":focusable" );
}
});

})( jQuery );
/*!
 * jQuery UI Widget 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

var _remove = $.fn.remove;

$.fn.remove = function( selector, keepData ) {
return this.each(function() {
if ( !keepData ) {
if ( !selector || $.filter( selector, [ this ] ).length ) {
$( "*", this ).add( [ this ] ).each(function() {
$( this ).triggerHandler( "remove" );
});
}
}
return _remove.call( $(this), selector, keepData );
});
};

$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;

if ( !prototype ) {
prototype = base;
base = $.Widget;
}

// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};

$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};

var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
//$.each( basePrototype, function( key, val ) {
//if ( $.isPlainObject(val) ) {
//basePrototype[ key ] = $.extend( {}, val );
//}
//});
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );

$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = Array.prototype.slice.call( arguments, 1 ),
returnValue = this;

// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.extend.apply( null, [ true, options ].concat(args) ) :
options;

// prevent calls to internal methods
if ( isMethodCall && options.substring( 0, 1 ) === "_" ) {
return returnValue;
}

if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name ),
methodValue = instance && $.isFunction( instance[options] ) ?
instance[ options ].apply( instance, args ) :
instance;
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
if ( options ) {
instance.option( options );
}
instance._init();
} else {
$.data( this, name, new object( options, this ) );
}
});
}

return returnValue;
};
};

$.Widget = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};

$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
options: {
disabled: false
},
_createWidget: function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
$.metadata && $.metadata.get( element )[ this.widgetName ],
options );

var self = this;
this.element.bind( "remove." + this.widgetName, function() {
self.destroy();
});

this._create();
this._init();
},
_create: function() {},
_init: function() {},

destroy: function() {
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
},

widget: function() {
return this.element;
},

option: function( key, value ) {
var options = key,
self = this;

if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.extend( {}, self.options );
}

if  (typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
options = {};
options[ key ] = value;
}

$.each( options, function( key, value ) {
self._setOption( key, value );
});

return self;
},
_setOption: function( key, value ) {
this.options[ key ] = value;

if ( key === "disabled" ) {
this.widget()
[ value ? "addClass" : "removeClass"](
this.widgetBaseClass + "-disabled" + " " +
"ui-state-disabled" )
.attr( "aria-disabled", value );
}

return this;
},

enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},

_trigger: function( type, event, data ) {
var callback = this.options[ type ];

event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
data = data || {};

// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( event.originalEvent ) {
for ( var i = $.event.props.length, prop; i; ) {
prop = $.event.props[ --i ];
event[ prop ] = event.originalEvent[ prop ];
}
}

this.element.trigger( event, data );

return !( $.isFunction(callback) &&
callback.call( this.element[0], event, data ) === false ||
event.isDefaultPrevented() );
}
};

})( jQuery );
/*!
 * jQuery UI Mouse 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.mouse", {
options: {
cancel: ':input,option',
distance: 1,
delay: 0
},
_mouseInit: function() {
var self = this;

this.element
.bind('mousedown.'+this.widgetName, function(event) {
return self._mouseDown(event);
})
.bind('click.'+this.widgetName, function(event) {
if(self._preventClickEvent) {
self._preventClickEvent = false;
event.stopImmediatePropagation();
return false;
}
});

this.started = false;
},

// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);
},

_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
// TODO: figure out why we have to use originalEvent
event.originalEvent = event.originalEvent || {};
if (event.originalEvent.mouseHandled) { return; }

// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));

this._mouseDownEvent = event;

var self = this,
btnIsLeft = (event.which == 1),
elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}

this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self.mouseDelayMet = true;
}, this.options.delay);
}

if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}

// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return self._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return self._mouseUp(event);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

// preventDefault() is used to prevent the selection of text here -
// however, in Safari, this causes select boxes not to be selectable
// anymore, so this fix is needed
($.browser.safari || event.preventDefault());

event.originalEvent.mouseHandled = true;
return true;
},

_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.browser.msie && !event.button) {
return this._mouseUp(event);
}

if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}

if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}

return !this._mouseStarted;
},

_mouseUp: function(event) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

if (this._mouseStarted) {
this._mouseStarted = false;
this._preventClickEvent = (event.target == this._mouseDownEvent.target);
this._mouseStop(event);
}

return false;
},

_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},

_mouseDelayMet: function(event) {
return this.mouseDelayMet;
},

// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(event) {},
_mouseDrag: function(event) {},
_mouseStop: function(event) {},
_mouseCapture: function(event) { return true; }
});

})(jQuery);
/*
 * jQuery UI Sortable 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *jquery.ui.core.js
 *jquery.ui.mouse.js
 *jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.sortable", $.ui.mouse, {
widgetEventPrefix: "sort",
options: {
appendTo: "parent",
axis: false,
connectWith: false,
containment: false,
cursor: 'auto',
cursorAt: false,
dropOnEmpty: true,
forcePlaceholderSize: false,
forceHelperSize: false,
grid: false,
handle: false,
helper: "original",
items: '> *',
opacity: false,
placeholder: false,
revert: false,
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
scope: "default",
tolerance: "intersect",
zIndex: 1000
},
_create: function() {

var o = this.options;
this.containerCache = {};
this.element.addClass("ui-sortable");

//Get the items
this.refresh();

//Let's determine if the items are floating
this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;

//Let's determine the parent's offset
this.offset = this.element.offset();

//Initialize mouse events for interaction
this._mouseInit();

},

destroy: function() {
this.element
.removeClass("ui-sortable ui-sortable-disabled")
.removeData("sortable")
.unbind(".sortable");
this._mouseDestroy();

for ( var i = this.items.length - 1; i >= 0; i-- )
this.items[i].item.removeData("sortable-item");

return this;
},

_setOption: function(key, value){
if ( key === "disabled" ) {
this.options[ key ] = value;

this.widget()
[ value ? "addClass" : "removeClass"]( "ui-sortable-disabled" );
} else {
// Don't call widget base _setOption for disable as it adds ui-state-disabled class
$.Widget.prototype._setOption.apply(this, arguments);
}
},

_mouseCapture: function(event, overrideHandle) {

if (this.reverting) {
return false;
}

if(this.options.disabled || this.options.type == 'static') return false;

//We have to refresh the items data once first
this._refreshItems(event);

//Find out if the clicked node (or one of its parents) is a actual item in this.items
var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
if($.data(this, 'sortable-item') == self) {
currentItem = $(this);
return false;
}
});
if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);

if(!currentItem) return false;
if(this.options.handle && !overrideHandle) {
var validHandle = false;

$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
if(!validHandle) return false;
}

this.currentItem = currentItem;
this._removeCurrentsFromItems();
return true;

},

_mouseStart: function(event, overrideHandle, noActivation) {

var o = this.options, self = this;
this.currentContainer = this;

//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
this.refreshPositions();

//Create and append the visible helper
this.helper = this._createHelper(event);

//Cache the helper size
this._cacheHelperProportions();

/*
 * - Position generation -
 * This block generates everything position related - it's the core of draggables.
 */

//Cache the margins of the original element
this._cacheMargins();

//Get the next scrolling parent
this.scrollParent = this.helper.scrollParent();

//The element's absolute position on the page minus margins
this.offset = this.currentItem.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};

// Only after we got the offset, we can change the helper's position to absolute
// TODO: Still need to figure out a way to make relative sorting possible
this.helper.css("position", "absolute");
this.cssPosition = this.helper.css("position");

$.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});

//Generate the original position
this.originalPosition = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;

//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

//Cache the former DOM position
this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
if(this.helper[0] != this.currentItem[0]) {
this.currentItem.hide();
}

//Create the placeholder
this._createPlaceholder();

//Set a containment if given in the options
if(o.containment)
this._setContainment();

if(o.cursor) { // cursor option
if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
$('body').css("cursor", o.cursor);
}

if(o.opacity) { // opacity option
if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
this.helper.css("opacity", o.opacity);
}

if(o.zIndex) { // zIndex option
if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
this.helper.css("zIndex", o.zIndex);
}

//Prepare scrolling
if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
this.overflowOffset = this.scrollParent.offset();

//Call callbacks
this._trigger("start", event, this._uiHash());

//Recache the helper size
if(!this._preserveHelperProportions)
this._cacheHelperProportions();


//Post 'activate' events to possible containers
if(!noActivation) {
 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
}

//Prepare possible droppables
if($.ui.ddmanager)
$.ui.ddmanager.current = this;

if ($.ui.ddmanager && !o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this, event);

this.dragging = true;

this.helper.addClass("ui-sortable-helper");
this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
return true;

},

_mouseDrag: function(event) {

//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");

if (!this.lastPositionAbs) {
this.lastPositionAbs = this.positionAbs;
}

//Do scrolling
if(this.options.scroll) {
var o = this.options, scrolled = false;
if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {

if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;

if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;

} else {

if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

}

if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this, event);
}

//Regenerate the absolute position used for position checks
this.positionAbs = this._convertPositionTo("absolute");

//Set the helper position
if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';

//Rearrange
for (var i = this.items.length - 1; i >= 0; i--) {

//Cache variables and intersection, continue if no intersection
var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
if (!intersection) continue;

if(itemElement != this.currentItem[0] //cannot intersect with itself
&&this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
&&!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
) {

this.direction = intersection == 1 ? "down" : "up";

if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
this._rearrange(event, item);
} else {
break;
}

this._trigger("change", event, this._uiHash());
break;
}
}

//Post events to containers
this._contactContainers(event);

//Interconnect with droppables
if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

//Call callbacks
this._trigger('sort', event, this._uiHash());

this.lastPositionAbs = this.positionAbs;
return false;

},

_mouseStop: function(event, noPropagation) {

if(!event) return;

//If we are using droppables, inform the manager about the drop
if ($.ui.ddmanager && !this.options.dropBehaviour)
$.ui.ddmanager.drop(this, event);

if(this.options.revert) {
var self = this;
var cur = self.placeholder.offset();

self.reverting = true;

$(this.helper).animate({
left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
}, parseInt(this.options.revert, 10) || 500, function() {
self._clear(event);
});
} else {
this._clear(event, noPropagation);
}

return false;

},

cancel: function() {

var self = this;

if(this.dragging) {

this._mouseUp();

if(this.options.helper == "original")
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
else
this.currentItem.show();

//Post deactivating events to containers
for (var i = this.containers.length - 1; i >= 0; i--){
this.containers[i]._trigger("deactivate", null, self._uiHash(this));
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", null, self._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}

}

//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();

$.extend(this, {
helper: null,
dragging: false,
reverting: false,
_noFinalSort: null
});

if(this.domPosition.prev) {
$(this.domPosition.prev).after(this.currentItem);
} else {
$(this.domPosition.parent).prepend(this.currentItem);
}

return this;

},

serialize: function(o) {

var items = this._getItemsAsjQuery(o && o.connected);
var str = []; o = o || {};

$(items).each(function() {
var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
});

if(!str.length && o.key) {
str.push(o.key + '=');
}

return str.join('&');

},

toArray: function(o) {

var items = this._getItemsAsjQuery(o && o.connected);
var ret = []; o = o || {};

items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
return ret;

},

/* Be careful with the following core functions */
_intersectsWith: function(item) {

var x1 = this.positionAbs.left,
x2 = x1 + this.helperProportions.width,
y1 = this.positionAbs.top,
y2 = y1 + this.helperProportions.height;

var l = item.left,
r = l + item.width,
t = item.top,
b = t + item.height;

var dyClick = this.offset.click.top,
dxClick = this.offset.click.left;

var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

if(   this.options.tolerance == "pointer"
|| this.options.forcePointerForContainers
|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
) {
return isOverElement;
} else {

return (l < x1 + (this.helperProportions.width / 2) // Right Half
&& x2 - (this.helperProportions.width / 2) < r // Left Half
&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
&& y2 - (this.helperProportions.height / 2) < b ); // Top Half

}
},

_intersectsWithPointer: function(item) {

var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
isOverElement = isOverElementHeight && isOverElementWidth,
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();

if (!isOverElement)
return false;

return this.floating ?
( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );

},

_intersectsWithSides: function(item) {

var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();

if (this.floating && horizontalDirection) {
return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
} else {
return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
}

},

_getDragVerticalDirection: function() {
var delta = this.positionAbs.top - this.lastPositionAbs.top;
return delta != 0 && (delta > 0 ? "down" : "up");
},

_getDragHorizontalDirection: function() {
var delta = this.positionAbs.left - this.lastPositionAbs.left;
return delta != 0 && (delta > 0 ? "right" : "left");
},

refresh: function(event) {
this._refreshItems(event);
this.refreshPositions();
return this;
},

_connectWith: function() {
var options = this.options;
return options.connectWith.constructor == String
? [options.connectWith]
: options.connectWith;
},

_getItemsAsjQuery: function(connected) {

var self = this;
var items = [];
var queries = [];
var connectWith = this._connectWith();

if(connectWith && connected) {
for (var i = connectWith.length - 1; i >= 0; i--){
var cur = $(connectWith[i]);
for (var j = cur.length - 1; j >= 0; j--){
var inst = $.data(cur[j], 'sortable');
if(inst && inst != this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]);
}
};
};
}

queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]);

for (var i = queries.length - 1; i >= 0; i--){
queries[i][0].each(function() {
items.push(this);
});
};

return $(items);

},

_removeCurrentsFromItems: function() {

var list = this.currentItem.find(":data(sortable-item)");

for (var i=0; i < this.items.length; i++) {

for (var j=0; j < list.length; j++) {
if(list[j] == this.items[i].item[0])
this.items.splice(i,1);
};

};

},

_refreshItems: function(event) {

this.items = [];
this.containers = [this];
var items = this.items;
var self = this;
var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
var connectWith = this._connectWith();

if(connectWith) {
for (var i = connectWith.length - 1; i >= 0; i--){
var cur = $(connectWith[i]);
for (var j = cur.length - 1; j >= 0; j--){
var inst = $.data(cur[j], 'sortable');
if(inst && inst != this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
this.containers.push(inst);
}
};
};
}

for (var i = queries.length - 1; i >= 0; i--) {
var targetData = queries[i][1];
var _queries = queries[i][0];

for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
var item = $(_queries[j]);

item.data('sortable-item', targetData); // Data for target checking (mouse manager)

items.push({
item: item,
instance: targetData,
width: 0, height: 0,
left: 0, top: 0
});
};
};

},

refreshPositions: function(fast) {

//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
if(this.offsetParent && this.helper) {
this.offset.parent = this._getParentOffset();
}

for (var i = this.items.length - 1; i >= 0; i--){
var item = this.items[i];

var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

if (!fast) {
item.width = t.outerWidth();
item.height = t.outerHeight();
}

var p = t.offset();
item.left = p.left;
item.top = p.top;
};

if(this.options.custom && this.options.custom.refreshContainers) {
this.options.custom.refreshContainers.call(this);
} else {
for (var i = this.containers.length - 1; i >= 0; i--){
var p = this.containers[i].element.offset();
this.containers[i].containerCache.left = p.left;
this.containers[i].containerCache.top = p.top;
this.containers[i].containerCache.width= this.containers[i].element.outerWidth();
this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
};
}

return this;
},

_createPlaceholder: function(that) {

var self = that || this, o = self.options;

if(!o.placeholder || o.placeholder.constructor == String) {
var className = o.placeholder;
o.placeholder = {
element: function() {

var el = $(document.createElement(self.currentItem[0].nodeName))
.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
.removeClass("ui-sortable-helper")[0];

if(!className)
el.style.visibility = "hidden";

return el;
},
update: function(container, p) {

// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
if(className && !o.forcePlaceholderSize) return;

//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
}
};
}

//Create the placeholder
self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));

//Append it after the actual current item
self.currentItem.after(self.placeholder);

//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
o.placeholder.update(self, self.placeholder);

},

_contactContainers: function(event) {

// get innermost container that intersects with item 
var innermostContainer = null, innermostIndex = null;


for (var i = this.containers.length - 1; i >= 0; i--){

// never consider a container that's located within the item itself 
if($.ui.contains(this.currentItem[0], this.containers[i].element[0]))
continue;

if(this._intersectsWith(this.containers[i].containerCache)) {

// if we've already found a container and it's more "inner" than this, then continue 
if(innermostContainer && $.ui.contains(this.containers[i].element[0], innermostContainer.element[0]))
continue;

innermostContainer = this.containers[i]; 
innermostIndex = i;

} else {
// container doesn't intersect. trigger "out" event if necessary 
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", event, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}

}

// if no intersecting containers found, return 
if(!innermostContainer) return; 

// move the item into the container if it's not there already
if(this.containers.length === 1) {
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
} else if(this.currentContainer != this.containers[innermostIndex]) { 

//When entering a new container, we will find the item with the least distance and append our item near it 
var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[innermostIndex].floating ? 'left' : 'top']; 
for (var j = this.items.length - 1; j >= 0; j--) { 
if(!$.ui.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue; 
var cur = this.items[j][this.containers[innermostIndex].floating ? 'left' : 'top']; 
if(Math.abs(cur - base) < dist) { 
dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; 
} 
} 

if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled 
return; 

this.currentContainer = this.containers[innermostIndex]; 
itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); 
this._trigger("change", event, this._uiHash()); 
this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); 

//Update the placeholder 
this.options.placeholder.update(this.currentContainer, this.placeholder); 

this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); 
this.containers[innermostIndex].containerCache.over = 1;
} 


},

_createHelper: function(event) {

var o = this.options;
var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);

if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);

if(helper[0] == this.currentItem[0])
this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };

if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());

return helper;

},

_adjustOffsetFromHelper: function(obj) {
if (typeof obj == 'string') {
obj = obj.split(' ');
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ('left' in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ('right' in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ('top' in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ('bottom' in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},

_getParentOffset: function() {


//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();

// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}

if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
po = { top: 0, left: 0 };

return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};

},

_getRelativeOffset: function() {

if(this.cssPosition == "relative") {
var p = this.currentItem.position();
return {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}

},

_cacheMargins: function() {
this.margins = {
left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
};
},

_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},

_setContainment: function() {

var o = this.options;
if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
if(o.containment == 'document' || o.containment == 'window') this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];

if(!(/^(document|window|parent)$/).test(o.containment)) {
var ce = $(o.containment)[0];
var co = $(o.containment).offset();
var over = ($(ce).css("overflow") != 'hidden');

this.containment = [
co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
];
}

},

_convertPositionTo: function(d, pos) {

if(!pos) pos = this.position;
var mod = d == "absolute" ? 1 : -1;
var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

return {
top: (
pos.top// The absolute mouse position
+ this.offset.relative.top * mod// Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top * mod// The offsetParent's offset without borders (offset + border)
- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
),
left: (
pos.left// The absolute mouse position
+ this.offset.relative.left * mod// Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left * mod// The offsetParent's offset without borders (offset + border)
- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
)
};

},

_generatePosition: function(event) {

var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

// This is another very weird special case that only happens for relative elements:
// 1. If the css position is relative
// 2. and the scroll parent is the document or similar to the offset parent
// we have to refresh the relative offset during the scroll so there are no jumps
if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
this.offset.relative = this._getRelativeOffset();
}

var pageX = event.pageX;
var pageY = event.pageY;

/*
 * - Position constraining -
 * Constrain the position to a mix of grid, containment.
 */

if(this.originalPosition) { //If we are not dragging yet, we won't check for options

if(this.containment) {
if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
}

if(o.grid) {
var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}

}

return {
top: (
pageY// The absolute mouse position
- this.offset.click.top// Click offset (relative to the element)
- this.offset.relative.top// Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top// The offsetParent's offset without borders (offset + border)
+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
),
left: (
pageX// The absolute mouse position
- this.offset.click.left// Click offset (relative to the element)
- this.offset.relative.left// Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left// The offsetParent's offset without borders (offset + border)
+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
)
};

},

_rearrange: function(event, i, a, hardRefresh) {

a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));

//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var self = this, counter = this.counter;

window.setTimeout(function() {
if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
},0);

},

_clear: function(event, noPropagation) {

this.reverting = false;
// We delay all events that have to be triggered to after the point where the placeholder has been removed and
// everything else normalized again
var delayedTriggers = [], self = this;

// We first have to update the dom position of the actual currentItem
// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem);
this._noFinalSort = null;

if(this.helper[0] == this.currentItem[0]) {
for(var i in this._storedCSS) {
if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
}
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}

if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
for (var i = this.containers.length - 1; i >= 0; i--){
if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
}
};
};

//Post events to containers
for (var i = this.containers.length - 1; i >= 0; i--){
if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
if(this.containers[i].containerCache.over) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
this.containers[i].containerCache.over = 0;
}
}

//Do what was originally in plugins
if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity
if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index

this.dragging = false;
if(this.cancelHelperRemoval) {
if(!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
return false;
}

if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());

//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;

if(!noPropagation) {
for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}

this.fromOutside = false;
return true;

},

_trigger: function() {
if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
this.cancel();
}
},

_uiHash: function(inst) {
var self = inst || this;
return {
helper: self.helper,
placeholder: self.placeholder || $([]),
position: self.position,
originalPosition: self.originalPosition,
offset: self.positionAbs,
item: self.currentItem,
sender: inst ? inst.element : null
};
}

});

$.extend($.ui.sortable, {
version: "1.8.4"
});

})(jQuery);



(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);

/*
 * jQuery history plugin
 * 
 * sample page: http://www.mikage.to/jquery/jquery_history.html
 *
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
historyCurrentHash: undefined,
historyCallback: undefined,
historyIframeSrc: undefined,
historyNeedIframe: jQuery.browser.msie && (jQuery.browser.version < 8 || document.documentMode < 8),

historyInit: function(callback, src){
jQuery.historyCallback = callback;
if (src) jQuery.historyIframeSrc = src;
var current_hash = location.hash.replace(/\?.*$/, '');

jQuery.historyCurrentHash = current_hash;
if (jQuery.historyNeedIframe) {
// To stop the callback firing twice during initilization if no hash present
if (jQuery.historyCurrentHash == '') {
jQuery.historyCurrentHash = '#';
}

var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = current_hash;
}
else if (jQuery.browser.safari) {
// etablish back/forward stacks
jQuery.historyBackStack = [];
jQuery.historyBackStack.length = history.length;
jQuery.historyForwardStack = [];
jQuery.lastHistoryLength = history.length;

jQuery.isFirst = true;
}
if(current_hash)
jQuery.historyCallback(current_hash.replace(/^#/, ''));
setInterval(jQuery.historyCheck, 100);
},

historyAddHistory: function(hash) {
// This makes the looping function do something
jQuery.historyBackStack.push(hash);

jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
this.isFirst = true;
},

historyCheck: function(){
if (jQuery.historyNeedIframe) {
// On IE, check for location.hash of iframe
var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
var current_hash = iframe.location.hash.replace(/\?.*$/, '');
if(current_hash != jQuery.historyCurrentHash) {

location.hash = current_hash;
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));

}
} else if (jQuery.browser.safari) {
if(jQuery.lastHistoryLength == history.length && jQuery.historyBackStack.length > jQuery.lastHistoryLength) {
jQuery.historyBackStack.shift();
}
if (!jQuery.dontCheck) {
var historyDelta = history.length - jQuery.historyBackStack.length;
jQuery.lastHistoryLength = history.length;

if (historyDelta) { // back or forward button has been pushed
jQuery.isFirst = false;
if (historyDelta < 0) { // back button has been pushed
// move items to forward stack
for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
} else { // forward button has been pushed
// move items to back stack
for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
}
var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
if (cachedHash != undefined) {
jQuery.historyCurrentHash = location.hash.replace(/\?.*$/, '');
jQuery.historyCallback(cachedHash);
}
} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
// document.URL doesn't change in Safari
if (location.hash) {
var current_hash = location.hash;
jQuery.historyCallback(location.hash.replace(/^#/, ''));
} else {
var current_hash = '';
jQuery.historyCallback('');
}
jQuery.isFirst = true;
}
}
} else {
// otherwise, check for location.hash
var current_hash = location.hash.replace(/\?.*$/, '');
if(current_hash != jQuery.historyCurrentHash) {
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));
}
}
},
historyLoad: function(hash){
var newhash;
hash = decodeURIComponent(hash.replace(/\?.*$/, ''));

if (jQuery.browser.safari) {
newhash = hash;
}
else {
newhash = '#' + hash;
location.hash = newhash;
}
jQuery.historyCurrentHash = newhash;

if (jQuery.historyNeedIframe) {
var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = newhash;
jQuery.lastHistoryLength = history.length;
jQuery.historyCallback(hash);
}
else if (jQuery.browser.safari) {
jQuery.dontCheck = true;
// Manually keep track of the history values for Safari
this.historyAddHistory(hash);

// Wait a while before allowing checking so that Safari has time to update the "history" object
// correctly (otherwise the check loop would detect a false change in hash).
var fn = function() {jQuery.dontCheck = false;};
window.setTimeout(fn, 200);
jQuery.historyCallback(hash);
// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
//      URL in the browser and the "history" object are both updated correctly.
location.hash = newhash;
}
else {
  jQuery.historyCallback(hash);
}
}
});




(function(){var n=this,A=n._,r=typeof StopIteration!=="undefined"?StopIteration:"__break__",j=Array.prototype,l=Object.prototype,o=j.slice,B=j.unshift,C=l.toString,p=l.hasOwnProperty,s=j.forEach,t=j.map,u=j.reduce,v=j.reduceRight,w=j.filter,x=j.every,y=j.some,m=j.indexOf,z=j.lastIndexOf;l=Array.isArray;var D=Object.keys,b=function(a){return new k(a)};if(typeof exports!=="undefined")exports._=b;n._=b;b.VERSION="1.1.0";var i=b.forEach=function(a,c,d){try{if(s&&a.forEach===s)a.forEach(c,d);else if(b.isNumber(a.length))for(var e=
0,f=a.length;e<f;e++)c.call(d,a[e],e,a);else for(e in a)p.call(a,e)&&c.call(d,a[e],e,a)}catch(g){if(g!=r)throw g;}return a};b.map=function(a,c,d){if(t&&a.map===t)return a.map(c,d);var e=[];i(a,function(f,g,h){e.push(c.call(d,f,g,h))});return e};b.reduce=function(a,c,d,e){if(u&&a.reduce===u){if(e)c=b.bind(c,e);return a.reduce(c,d)}i(a,function(f,g,h){d=c.call(e,d,f,g,h)});return d};b.reduceRight=function(a,c,d,e){if(v&&a.reduceRight===v){if(e)c=b.bind(c,e);return a.reduceRight(c,d)}a=b.clone(b.toArray(a)).reverse();
return b.reduce(a,c,d,e)};b.detect=function(a,c,d){var e;i(a,function(f,g,h){if(c.call(d,f,g,h)){e=f;b.breakLoop()}});return e};b.filter=function(a,c,d){if(w&&a.filter===w)return a.filter(c,d);var e=[];i(a,function(f,g,h){c.call(d,f,g,h)&&e.push(f)});return e};b.reject=function(a,c,d){var e=[];i(a,function(f,g,h){!c.call(d,f,g,h)&&e.push(f)});return e};b.every=function(a,c,d){c=c||b.identity;if(x&&a.every===x)return a.every(c,d);var e=true;i(a,function(f,g,h){(e=e&&c.call(d,f,g,h))||b.breakLoop()});
return e};b.some=function(a,c,d){c=c||b.identity;if(y&&a.some===y)return a.some(c,d);var e=false;i(a,function(f,g,h){if(e=c.call(d,f,g,h))b.breakLoop()});return e};b.include=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c)!=-1;var d=false;i(a,function(e){if(d=e===c)b.breakLoop()});return d};b.invoke=function(a,c){var d=b.rest(arguments,2);return b.map(a,function(e){return(c?e[c]:e).apply(e,d)})};b.pluck=function(a,c){return b.map(a,function(d){return d[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,
a);var e={computed:-Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g>=e.computed&&(e={value:f,computed:g})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);var e={computed:Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g<e.computed&&(e={value:f,computed:g})});return e.value};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(e,f,g){return{value:e,criteria:c.call(d,e,f,g)}}).sort(function(e,f){var g=e.criteria,h=f.criteria;return g<h?-1:g>h?
1:0}),"value")};b.sortedIndex=function(a,c,d){d=d||b.identity;for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?(e=g+1):(f=g)}return e};b.toArray=function(a){if(!a)return[];if(a.toArray)return a.toArray();if(b.isArray(a))return a;if(b.isArguments(a))return o.call(a);return b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=function(a,c,d){return c&&!d?o.call(a,0,c):a[0]};b.rest=function(a,c,d){return o.call(a,b.isUndefined(c)||d?1:c)};b.last=function(a){return a[a.length-1]};
b.compact=function(a){return b.filter(a,function(c){return!!c})};b.flatten=function(a){return b.reduce(a,function(c,d){if(b.isArray(d))return c.concat(b.flatten(d));c.push(d);return c},[])};b.without=function(a){var c=b.rest(arguments);return b.filter(a,function(d){return!b.include(c,d)})};b.uniq=function(a,c){return b.reduce(a,function(d,e,f){if(0==f||(c===true?b.last(d)!=e:!b.include(d,e)))d.push(e);return d},[])};b.intersect=function(a){var c=b.rest(arguments);return b.filter(b.uniq(a),function(d){return b.every(c,
function(e){return b.indexOf(e,d)>=0})})};b.zip=function(){for(var a=b.toArray(arguments),c=b.max(b.pluck(a,"length")),d=new Array(c),e=0;e<c;e++)d[e]=b.pluck(a,String(e));return d};b.indexOf=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c);for(var d=0,e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,c){if(z&&a.lastIndexOf===z)return a.lastIndexOf(c);for(var d=a.length;d--;)if(a[d]===c)return d;return-1};b.range=function(a,c,d){var e=b.toArray(arguments),f=e.length<=
1;a=f?0:e[0];c=f?e[0]:e[1];d=e[2]||1;e=Math.ceil((c-a)/d);if(e<=0)return[];e=new Array(e);f=a;for(var g=0;;f+=d){if((d>0?f-c:c-f)>=0)return e;e[g++]=f}};b.bind=function(a,c){var d=b.rest(arguments,2);return function(){return a.apply(c||{},d.concat(b.toArray(arguments)))}};b.bindAll=function(a){var c=b.rest(arguments);if(c.length==0)c=b.functions(a);i(c,function(d){a[d]=b.bind(a[d],a)});return a};b.memoize=function(a,c){var d={};c=c||b.identity;return function(){var e=c.apply(this,arguments);return e in
d?d[e]:(d[e]=a.apply(this,arguments))}};b.delay=function(a,c){var d=b.rest(arguments,2);return setTimeout(function(){return a.apply(a,d)},c)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(b.rest(arguments)))};b.wrap=function(a,c){return function(){var d=[a].concat(b.toArray(arguments));return c.apply(c,d)}};b.compose=function(){var a=b.toArray(arguments);return function(){for(var c=b.toArray(arguments),d=a.length-1;d>=0;d--)c=[a[d].apply(this,c)];return c[0]}};b.keys=D||function(a){if(b.isArray(a))return b.range(0,
a.length);var c=[];for(var d in a)p.call(a,d)&&c.push(d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=function(a){return b.filter(b.keys(a),function(c){return b.isFunction(a[c])}).sort()};b.extend=function(a){i(b.rest(arguments),function(c){for(var d in c)a[d]=c[d]});return a};b.clone=function(a){if(b.isArray(a))return a.slice(0);return b.extend({},a)};b.tap=function(a,c){c(a);return a};b.isEqual=function(a,c){if(a===c)return true;var d=typeof a;if(d!=typeof c)return false;
if(a==c)return true;if(!a&&c||a&&!c)return false;if(a.isEqual)return a.isEqual(c);if(b.isDate(a)&&b.isDate(c))return a.getTime()===c.getTime();if(b.isNaN(a)&&b.isNaN(c))return false;if(b.isRegExp(a)&&b.isRegExp(c))return a.source===c.source&&a.global===c.global&&a.ignoreCase===c.ignoreCase&&a.multiline===c.multiline;if(d!=="object")return false;if(a.length&&a.length!==c.length)return false;d=b.keys(a);var e=b.keys(c);if(d.length!=e.length)return false;for(var f in a)if(!(f in c)||!b.isEqual(a[f],
c[f]))return false;return true};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(p.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=l||function(a){return!!(a&&a.concat&&a.unshift&&!a.callee)};b.isArguments=function(a){return a&&a.callee};b.isFunction=function(a){return!!(a&&a.constructor&&a.call&&a.apply)};b.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)};b.isNumber=function(a){return a===
+a||C.call(a)==="[object Number]"};b.isBoolean=function(a){return a===true||a===false};b.isDate=function(a){return!!(a&&a.getTimezoneOffset&&a.setUTCFullYear)};b.isRegExp=function(a){return!!(a&&a.test&&a.exec&&(a.ignoreCase||a.ignoreCase===false))};b.isNaN=function(a){return b.isNumber(a)&&isNaN(a)};b.isNull=function(a){return a===null};b.isUndefined=function(a){return typeof a=="undefined"};b.noConflict=function(){n._=A;return this};b.identity=function(a){return a};b.times=function(a,c,d){for(var e=
0;e<a;e++)c.call(d,e)};b.breakLoop=function(){throw r;};b.mixin=function(a){i(b.functions(a),function(c){E(c,b[c]=a[c])})};var F=0;b.uniqueId=function(a){var c=F++;return a?a+c:c};b.templateSettings={start:"<%",end:"%>",interpolate:/<%=(.+?)%>/g};b.template=function(a,c){var d=b.templateSettings,e=new RegExp("'(?=[^"+d.end.substr(0,1)+"]*"+d.end.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")+")","g");d=new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj||{}){p.push('"+a.replace(/\r/g,
"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(e,"\u2704").split("'").join("\\'").split("\u2704").join("'").replace(d.interpolate,"',$1,'").split(d.start).join("');").split(d.end).join("p.push('")+"');}return p.join('');");return c?d(c):d};b.each=b.forEach;b.foldl=b.inject=b.reduce;b.foldr=b.reduceRight;b.select=b.filter;b.all=b.every;b.any=b.some;b.contains=b.include;b.head=b.first;b.tail=b.rest;b.methods=b.functions;var k=function(a){this._wrapped=a},q=function(a,c){return c?b(a).chain():
a},E=function(a,c){k.prototype[a]=function(){var d=b.toArray(arguments);B.call(d,this._wrapped);return q(c.apply(b,d),this._chain)}};b.mixin(b);i(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var c=j[a];k.prototype[a]=function(){c.apply(this._wrapped,arguments);return q(this._wrapped,this._chain)}});i(["concat","join","slice"],function(a){var c=j[a];k.prototype[a]=function(){return q(c.apply(this._wrapped,arguments),this._chain)}});k.prototype.chain=function(){this._chain=
true;return this};k.prototype.value=function(){return this._wrapped}})();


/*
 * Thickbox 3 - 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 = "http://www.hungryforchange.com/image/loadingAnimation.gif";

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}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<U 5=\'1F\'></U><4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' /></4>");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D<E.1c)&&(R===""));D++){6 k=E[D].u.1C().2h(i);3(!(E[D].u==f)){3(1r){1z=E[D].Q;1x=E[D].u;R="<1e 5=\'1X\'>&1d;&1d;<a u=\'#\'>2T &2R;</a></1e>"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;<a u=\'#\'>&2O; 2N</a></1e>"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<a u=\'\' 5=\'1L\' Q=\'1o\'><1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/></a>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"</4></4><4 5=\'2A\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4>");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4></4><U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\' > </U>")}n{$("#B").N();$("#8").q("<U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\'> </U>")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\'>1l</a> 1k 1j 1s</4></4><4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'></4>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'></4>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i<c.1c;i++){6 d=c[i].1B(\'=\');3(!d||d.1c!=2){39}6 e=2a(d[0]);6 f=2a(d[1]);f=f.2r(/\\+/g,\' \');b[e]=f}H b}9 2x(){6 a=o.2M;6 w=1S.2o||1R.2o||(a&&a.1Q)||o.v.1Q;6 h=1S.1P||1R.1P||(a&&a.2n)||o.v.2n;1O=[w,h];H 1O}9 1K(){6 a=2K.2J.1C();3(a.O(\'2I\')!=-1&&a.O(\'3o\')!=-1){H 1b}}',62,211,'|||if|div|id|var||TB_window|function||||||||||||||else|document|px|append|css|click||href|body||||width|height|TB_overlay|remove|TB_Counter|TB_TempArray|TB_ajaxContent|tb_remove|return|keycode|style|TB_load|src|null|unbind|indexOf|false|title|TB_NextHTML|imgPreloader|block|iframe|ajaxContentH|ajaxContentW|this|display|TB_closeWindowButton||html|goPrev|TB_WIDTH|TB_PrevHTML|TB_iframeContent|tb_position||thickbox|tb_show|TB_HEIGHT|true|length|nbsp|span|Math|onload|onkeydown|goNext|Esc|or|close|tb_showIframe|TB_imageCount|Close|new|browser|TB_FoundURL|Key|Image|tb_init|name|imgLoader|TB_NextURL|random|TB_NextCaption|modal|split|toLowerCase|TB_PrevCaption|urlNoQuery|TB_HideSelect|TB_PrevURL|TB_ajaxWindowTitle|img|addClass|tb_detectMacXFF|TB_ImageOff|150|rel|arrayPageSize|innerHeight|clientWidth|self|window|children|TB_prev|jQuery|frameborder|TB_next|getElementById|auto|parseInt|onkeyup|overflow|alt|unload|for|inlineId||100||unescape|1000|round|hspace|TB_closeAjaxWindow|TB_title|undefined|match|maxHeight|TB_iframe|bmp|gif|png|clientHeight|innerWidth|tb_parseQuery|jpeg|replace|jpg|typeof|which|keyCode|event|tb_getPageSize|show|TB_overlayBG|TB_closeWindow|TB_overlayMacFFBGHack|TB_secondLine|TB_caption|blur|TB_Image|60|tb_pathToImage|mac|userAgent|navigator|of|documentElement|Prev|lt|version|msie|gt|ready|Next|marginLeft|trigger|fast|fadeOut|TB_imageOff|hidden||catch|getTime|Date|load|safari|get|TB_inline|marginTop|continue|scrollTop|TB_modal|class|TB_|45|440|40|630|input|188|190|substr|try|area|firefox'.split('|'),0,{}))

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*!
 * jQuery resize event - v1.1 - 3/14/2010
 * http://benalman.com/projects/jquery-resize-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery resize event
//
// *Version: 1.1, Last updated: 3/14/2010*
// 
// Project Home - http://benalman.com/projects/jquery-resize-plugin/
// GitHub       - http://github.com/cowboy/jquery-resize/
// Source       - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.js
// (Minified)   - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.min.js (1.0kb)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// This working example, complete with fully commented code, illustrates a few
// ways in which this plugin can be used.
// 
// resize event - http://benalman.com/code/projects/jquery-resize/examples/resize/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome, Opera 9.6-10.1.
// Unit Tests      - http://benalman.com/code/projects/jquery-resize/unit/
// 
// About: Release History
// 
// 1.1 - (3/14/2010) Fixed a minor bug that was causing the event to trigger
//       immediately after bind in some circumstances. Also changed $.fn.data
//       to $.data to improve performance.
// 1.0 - (2/10/2010) Initial release

(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // A jQuery object containing all non-window elements to which the resize
  // event is bound.
  var elems = $([]),
    
    // Extend $.resize if it already exists, otherwise create it.
    jq_resize = $.resize = $.extend( $.resize, {} ),
    
    timeout_id,
    
    // Reused strings.
    str_setTimeout = 'setTimeout',
    str_resize = 'resize',
    str_data = str_resize + '-special-event',
    str_delay = 'delay',
    str_throttle = 'throttleWindow';
  
  // Property: jQuery.resize.delay
  // 
  // The numeric interval (in milliseconds) at which the resize event polling
  // loop executes. Defaults to 250.
  
  jq_resize[ str_delay ] = 250;
  
  // Property: jQuery.resize.throttleWindow
  // 
  // Throttle the native window object resize event to fire no more than once
  // every <jQuery.resize.delay> milliseconds. Defaults to true.
  // 
  // Because the window object has its own resize event, it doesn't need to be
  // provided by this plugin, and its execution can be left entirely up to the
  // browser. However, since certain browsers fire the resize event continuously
  // while others do not, enabling this will throttle the window resize event,
  // making event behavior consistent across all elements in all browsers.
  // 
  // While setting this property to false will disable window object resize
  // event throttling, please note that this property must be changed before any
  // window object resize event callbacks are bound.
  
  jq_resize[ str_throttle ] = true;
  
  // Event: resize event
  // 
  // Fired when an element's width or height changes. Because browsers only
  // provide this event for the window element, for other elements a polling
  // loop is initialized, running every <jQuery.resize.delay> milliseconds
  // to see if elements' dimensions have changed. You may bind with either
  // .resize( fn ) or .bind( "resize", fn ), and unbind with .unbind( "resize" ).
  // 
  // Usage:
  // 
  // > jQuery('selector').bind( 'resize', function(e) {
  // >   // element's width or height has changed!
  // >   ...
  // > });
  // 
  // Additional Notes:
  // 
  // * The polling loop is not created until at least one callback is actually
  //   bound to the 'resize' event, and this single polling loop is shared
  //   across all elements.
  // 
  // Double firing issue in jQuery 1.3.2:
  // 
  // While this plugin works in jQuery 1.3.2, if an element's event callbacks
  // are manually triggered via .trigger( 'resize' ) or .resize() those
  // callbacks may double-fire, due to limitations in the jQuery 1.3.2 special
  // events system. This is not an issue when using jQuery 1.4+.
  // 
  // > // While this works in jQuery 1.4+
  // > $(elem).css({ width: new_w, height: new_h }).resize();
  // > 
  // > // In jQuery 1.3.2, you need to do this:
  // > var elem = $(elem);
  // > elem.css({ width: new_w, height: new_h });
  // > elem.data( 'resize-special-event', { width: elem.width(), height: elem.height() } );
  // > elem.resize();
      
  $.event.special[ str_resize ] = {
    
    // Called only when the first 'resize' event callback is bound per element.
    setup: function() {
      // Since window has its own native 'resize' event, return false so that
      // jQuery will bind the event using DOM methods. Since only 'window'
      // objects have a .setTimeout method, this should be a sufficient test.
      // Unless, of course, we're throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var elem = $(this);
      
      // Add this element to the list of internal elements to monitor.
      elems = elems.add( elem );
      
      // Initialize data store on the element.
      $.data( this, str_data, { w: elem.width(), h: elem.height() } );
      
      // If this is the first element added, start the polling loop.
      if ( elems.length === 1 ) {
        loopy();
      }
    },
    
    // Called only when the last 'resize' event callback is unbound per element.
    teardown: function() {
      // Since window has its own native 'resize' event, return false so that
      // jQuery will unbind the event using DOM methods. Since only 'window'
      // objects have a .setTimeout method, this should be a sufficient test.
      // Unless, of course, we're throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var elem = $(this);
      
      // Remove this element from the list of internal elements to monitor.
      elems = elems.not( elem );
      
      // Remove any data stored on the element.
      elem.removeData( str_data );
      
      // If this is the last element removed, stop the polling loop.
      if ( !elems.length ) {
        clearTimeout( timeout_id );
      }
    },
    
    // Called every time a 'resize' event callback is bound per element (new in
    // jQuery 1.4).
    add: function( handleObj ) {
      // Since window has its own native 'resize' event, return false so that
      // jQuery doesn't modify the event object. Unless, of course, we're
      // throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var old_handler;
      
      // The new_handler function is executed every time the event is triggered.
      // This is used to update the internal element data store with the width
      // and height when the event is triggered manually, to avoid double-firing
      // of the event callback. See the "Double firing issue in jQuery 1.3.2"
      // comments above for more information.
      
      function new_handler( e, w, h ) {
        var elem = $(this),
          data = $.data( this, str_data );
        
        // If called from the polling loop, w and h will be passed in as
        // arguments. If called manually, via .trigger( 'resize' ) or .resize(),
        // those values will need to be computed.
        data.w = w !== undefined ? w : elem.width();
        data.h = h !== undefined ? h : elem.height();
        
        old_handler.apply( this, arguments );
      };
      
      // This may seem a little complicated, but it normalizes the special event
      // .add method between jQuery 1.4/1.4.1 and 1.4.2+
      if ( $.isFunction( handleObj ) ) {
        // 1.4, 1.4.1
        old_handler = handleObj;
        return new_handler;
      } else {
        // 1.4.2+
        old_handler = handleObj.handler;
        handleObj.handler = new_handler;
      }
    }
    
  };
  
  function loopy() {
    
    // Start the polling loop, asynchronously.
    timeout_id = window[ str_setTimeout ](function(){
      
      // Iterate over all elements to which the 'resize' event is bound.
      elems.each(function(){
        var elem = $(this),
          width = elem.width(),
          height = elem.height(),
          data = $.data( this, str_data );
        
        // If element size has changed since the last time, update the element
        // data store and trigger the 'resize' event.
        if ( width !== data.w || height !== data.h ) {
          elem.trigger( str_resize, [ data.w = width, data.h = height ] );
        }
        
      });
      
      // Loop.
      loopy();
      
    }, jq_resize[ str_delay ] );
    
  };
  
})(jQuery,this);


/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id$
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Objectsettingshash with options, described below.
 *scrollbarWidth-The width of the generated scrollbar in pixels
 *scrollbarMargin-The amount of space to leave on the side of the scrollbar in pixels
 *wheelSpeed-The speed the pane will scroll in response to the mouse wheel in pixels
 *showArrows-Whether to display arrows for the user to scroll with
 *arrowSize-The height of the arrow buttons if showArrows=true
 *animateTo-Whether to animate when calling scrollTo and scrollBy
 *dragMinHeight-The minimum height to allow the drag bar to be
 *dragMaxHeight-The maximum height to allow the drag bar to be
 *animateInterval-The interval in milliseconds to update an animating scrollPane (default 100)
 *animateStep-The amount to divide the remaining scroll distance by when animating (default 3)
 *maintainPosition-Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *tabIndex-The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *scrollbarOnLeft-Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *topCapHeight-The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *bottomCapHeight-The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 *observeHash-Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
active : []
};
$.fn.jScrollPane = function(settings)
{
settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

var rf = function() { return false; };

return this.each(
function()
{
var $this = $(this);
var paneEle = this;
var currentScrollPosition = 0;
var paneWidth;
var paneHeight;
var trackHeight;
var trackOffset = settings.topCapHeight;
var $container;

if ($(this).parent().is('.jScrollPaneContainer')) {
$container = $(this).parent();
currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
var $c = $(this).parent();
paneWidth = $c.innerWidth();
paneHeight = $c.outerHeight();
$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
$this.css({'top':0});
} else {
$this.data('originalStyleTag', $this.attr('style'));
// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
$this.css('overflow', 'hidden');
this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
paneWidth = $this.innerWidth();
paneHeight = $this.innerHeight();
$container = $('<div></div>')
.attr({'className':'jScrollPaneContainer'})
.css(
{
'height':paneHeight+'px', 
'width':paneWidth+'px'
}
);
if (settings.enableKeyboardNavigation) {
$container.attr(
'tabindex', 
settings.tabIndex
);
}
$this.wrap($container);
$container = $this.parent();
// deal with text size changes (if the jquery.em plugin is included)
// and re-initialise the scrollPane so the track maintains the
// correct size
$(document).bind(
'emchange', 
function(e, cur, prev)
{
$this.jScrollPane(settings);
}
);

}
trackHeight = paneHeight;

if (settings.reinitialiseOnImageLoad) {
// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
var loadedImages = [];

if ($imagesToLoad.length) {
$imagesToLoad.each(function(i, val){
$(this).bind('load readystatechange', function() {
if($.inArray(i, loadedImages) == -1){ //don't double count images
loadedImages.push(val); //keep a record of images we've seen
$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
return n != val;
});
$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
$this.jScrollPane(s2); // re-initialise
}
}).each(function(i, val) {
if(this.complete || this.complete===undefined) { 
//needed for potential cached images
this.src = this.src; 
} 
});
});
};
}

var p = this.originalSidePaddingTotal;
var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

var cssToApply = {
'height':'auto',
'width': realPaneWidth + 'px'
}

if(settings.scrollbarOnLeft) {
cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
} else {
cssToApply.paddingRight = settings.scrollbarMargin + 'px';
}

$this.css(cssToApply);

var contentHeight = $this.outerHeight();
var percentInView = paneHeight / contentHeight;

var isScrollable = percentInView < .99;
$container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');

if (isScrollable) {
$container.append(
$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
)
),
$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
);

var $track = $('>.jScrollPaneTrack', $container);
var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);


var currentArrowDirection;
var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
var currentArrowInc;
var whileArrowButtonDown = function() 
{
if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
}
currentArrowInc++;
};

if (settings.enableKeyboardNavigation) {
$container.bind(
'keydown.jscrollpane',
function(e) 
{
switch (e.keyCode) {
case 38: //up
currentArrowDirection = -1;
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
return false;
case 40: //down
currentArrowDirection = 1;
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
return false;
case 33: // page up
case 34: // page down
// TODO
return false;
default:
}
}
).bind(
'keyup.jscrollpane',
function(e) 
{
if (e.keyCode == 38 || e.keyCode == 40) {
for (var i = 0; i < currentArrowTimerArr.length; i++) {
clearInterval(currentArrowTimerArr[i]);
}
return false;
}
}
);
}

if (settings.showArrows) {

var currentArrowButton;
var currentArrowInterval;

var onArrowMouseUp = function(event)
{
$('html').unbind('mouseup', onArrowMouseUp);
currentArrowButton.removeClass('jScrollActiveArrowButton');
clearInterval(currentArrowInterval);
};
var onArrowMouseDown = function() {
$('html').bind('mouseup', onArrowMouseUp);
currentArrowButton.addClass('jScrollActiveArrowButton');
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowInterval = setInterval(whileArrowButtonDown, 100);
};
$container
.append(
$('<a></a>')
.attr(
{
'href':'javascript:;', 
'className':'jScrollArrowUp', 
'tabindex':-1
}
)
.css(
{
'width':settings.scrollbarWidth+'px',
'top':settings.topCapHeight + 'px'
}
)
.html('Scroll up')
.bind('mousedown', function()
{
currentArrowButton = $(this);
currentArrowDirection = -1;
onArrowMouseDown();
this.blur();
return false;
})
.bind('click', rf),
$('<a></a>')
.attr(
{
'href':'javascript:;', 
'className':'jScrollArrowDown', 
'tabindex':-1
}
)
.css(
{
'width':settings.scrollbarWidth+'px',
'bottom':settings.bottomCapHeight + 'px'
}
)
.html('Scroll down')
.bind('mousedown', function()
{
currentArrowButton = $(this);
currentArrowDirection = 1;
onArrowMouseDown();
this.blur();
return false;
})
.bind('click', rf)
);
var $upArrow = $('>.jScrollArrowUp', $container);
var $downArrow = $('>.jScrollArrowDown', $container);
}

if (settings.arrowSize) {
trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
trackOffset += settings.arrowSize;
} else if ($upArrow) {
var topArrowHeight = $upArrow.height();
settings.arrowSize = topArrowHeight;
trackHeight = paneHeight - topArrowHeight - $downArrow.height();
trackOffset += topArrowHeight;
}
trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
$track.css({'height': trackHeight+'px', top:trackOffset+'px'})

var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});

var currentOffset;
var maxY;
var mouseWheelMultiplier;
// store this in a seperate variable so we can keep track more accurately than just updating the css property..
var dragPosition = 0;
var dragMiddle = percentInView*paneHeight/2;

// pos function borrowed from tooltip plugin and adapted...
var getPos = function (event, c) {
var p = c == 'X' ? 'Left' : 'Top';
return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
};

var ignoreNativeDrag = function() {return false; };

var initDrag = function()
{
ceaseAnimation();
currentOffset = $drag.offset(false);
currentOffset.top -= dragPosition;
maxY = trackHeight - $drag[0].offsetHeight;
mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
};

var onStartDrag = function(event)
{
initDrag();
dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind('mouseleave', onStopDrag)
if ($.browser.msie) {
$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
}
return false;
};
var onStopDrag = function()
{
$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
dragMiddle = percentInView*paneHeight/2;
if ($.browser.msie) {
$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
}
};
var positionDrag = function(destY)
{
$container.scrollTop(0);
destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
dragPosition = destY;
$drag.css({'top':destY+'px'});
var p = destY / maxY;
$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
$this.trigger('scroll');
if (settings.showArrows) {
$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
}
};
var updateScroll = function(e)
{
positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
};

var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);

$drag.css(
{'height':dragH+'px'}
).bind('mousedown', onStartDrag);

var trackScrollInterval;
var trackScrollInc;
var trackScrollMousePos;
var doTrackScroll = function()
{
if (trackScrollInc > 8 || trackScrollInc%4==0) {
positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
}
trackScrollInc ++;
};
var onStopTrackClick = function()
{
clearInterval(trackScrollInterval);
$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
};
var onTrackMouseMove = function(event)
{
trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
};
var onTrackClick = function(event)
{
initDrag();
onTrackMouseMove(event);
trackScrollInc = 0;
$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
trackScrollInterval = setInterval(doTrackScroll, 100);
doTrackScroll();
return false;
};

$track.bind('mousedown', onTrackClick);

$container.bind(
'mousewheel',
function (event, delta) {
delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
initDrag();
ceaseAnimation();
var d = dragPosition;
positionDrag(dragPosition - delta * mouseWheelMultiplier);

var dragOccured = d != dragPosition;
return !dragOccured;
}
);

var _animateToPosition;
var _animateToInterval;
function animateToPosition()
{
var diff = (_animateToPosition - dragPosition) / settings.animateStep;
if (diff > 1 || diff < -1) {
positionDrag(dragPosition + diff);
} else {
positionDrag(_animateToPosition);
ceaseAnimation();
}
}
var ceaseAnimation = function()
{
if (_animateToInterval) {
clearInterval(_animateToInterval);
delete _animateToPosition;
}
};
var scrollTo = function(pos, preventAni)
{
if (typeof pos == "string") {
// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
// errors from the lookup...
try {
$e = $(pos, $this);
} catch (err) {
return;
}
if (!$e.length) return;
pos = $e.offset().top - $this.offset().top;
}
ceaseAnimation();
var maxScroll = contentHeight - paneHeight;
pos = pos > maxScroll ? maxScroll : pos;
$this.data('jScrollPaneMaxScroll', maxScroll);
var destDragPosition = pos/maxScroll * maxY;
if (preventAni || !settings.animateTo) {
positionDrag(destDragPosition);
} else {
$container.scrollTop(0);
_animateToPosition = destDragPosition;
_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
}
};
$this[0].scrollTo = scrollTo;

$this[0].scrollBy = function(delta)
{
var currentPos = -parseInt($pane.css('top')) || 0;
scrollTo(currentPos + delta);
};

initDrag();

scrollTo(-currentScrollPosition, true);

// Deal with it when the user tabs to a link or form element within this scrollpane
$('*', this).bind(
'focus',
function(event)
{
var $e = $(this);

// loop through parents adding the offset top of any elements that are relatively positioned between
// the focused element and the jScrollPaneContainer so we can get the true distance from the top
// of the focused element to the top of the scrollpane...
var eleTop = 0;

var preventInfiniteLoop = 100;

while ($e[0] != $this[0]) {
eleTop += $e.position().top;
$e = $e.offsetParent();
if (!preventInfiniteLoop--) {
return;
}
}

var viewportTop = -parseInt($pane.css('top')) || 0;
var maxVisibleEleTop = viewportTop + paneHeight;
var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
if (!eleInView) {
var destPos = eleTop - settings.scrollbarMargin;
if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
}
scrollTo(destPos);
}
}
)


if (settings.observeHash) {
if (location.hash && location.hash.length > 1) {
setTimeout(function(){
scrollTo(location.hash);
}, $.browser.safari ? 100 : 0);
}

// use event delegation to listen for all clicks on links and hijack them if they are links to
// anchors within our content...
$(document).bind('click', function(e){
$target = $(e.target);
if ($target.is('a')) {
var h = $target.attr('href');
if (h && h.substr(0, 1) == '#' && h.length > 1) {
setTimeout(function(){
scrollTo(h, !settings.animateToInternalLinks);
}, $.browser.safari ? 100 : 0);
}
}
});
}

// Deal with dragging and selecting text to make the scrollpane scroll...
function onSelectScrollMouseDown(e)
{
   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
  
}

var textDragDistanceAway;
var textSelectionInterval;

function onTextSelectionInterval()
{
direction = textDragDistanceAway < 0 ? -1 : 1;
$this[0].scrollBy(textDragDistanceAway / 2);
}

function clearTextSelectionInterval()
{
if (textSelectionInterval) {
clearInterval(textSelectionInterval);
textSelectionInterval = undefined;
}
}

function onTextSelectionScrollMouseMove(e)
{
var offset = $this.parent().offset().top;
var maxOffset = offset + paneHeight;
var mouseOffset = getPos(e, 'Y');
textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
if (textDragDistanceAway == 0) {
clearTextSelectionInterval();
} else {
if (!textSelectionInterval) {
textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
}
}
}

function onSelectScrollMouseUp(e)
{
   $(document)
  .unbind('mousemove.jScrollPaneDragging')
  .unbind('mouseup.jScrollPaneDragging');
   clearTextSelectionInterval();
}

$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);


$.jScrollPane.active.push($this[0]);

} else {
$this.css(
{
'height':paneHeight+'px',
'width':paneWidth-this.originalSidePaddingTotal+'px',
'padding':this.originalPadding
}
);
$this[0].scrollTo = $this[0].scrollBy = function() {};
// clean up listeners
$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
}

}
)
};

$.fn.jScrollPaneRemove = function()
{
$(this).each(function()
{
$this = $(this);
var $c = $this.parent();
if ($c.is('.jScrollPaneContainer')) {
$this.css(
{
'top':'',
'height':'',
'width':'',
'padding':'',
'overflow':'',
'position':''
}
);
$this.attr('style', $this.data('originalStyleTag'));
$c.after($this).remove();
}
});
}

$.fn.jScrollPane.defaults = {
scrollbarWidth : 10,
scrollbarMargin : 5,
wheelSpeed : 18,
showArrows : false,
arrowSize : 0,
animateTo : false,
dragMinHeight : 1,
dragMaxHeight : 99999,
animateInterval : 100,
animateStep: 3,
maintainPosition: true,
scrollbarOnLeft: false,
reinitialiseOnImageLoad: false,
tabIndex : 0,
enableKeyboardNavigation: true,
animateToInternalLinks: false,
topCapHeight: 0,
bottomCapHeight: 0,
observeHash: true
};

// clean up the scrollTo expandos
$(window)
.bind('unload', function() {
var els = $.jScrollPane.active; 
for (var i=0; i<els.length; i++) {
els[i].scrollTo = els[i].scrollBy = null;
}
}
);

})(jQuery);

/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/**
 *----------------------------------------
 * dimage
 * @uses jQuery >= v1.2
 * @since 2010-06-24
 *----------------------------------------
 */
var dimage = {
"displayUrl" : "/include/lib/dimage/display.php",
"cache" : true
};


/**
 *----------------------------------------
 * Get HTML <img> tag for dimage
 * @param mixed p_mText String of text or JSON array of texts
 * @param mixed p_mStyle String of JSON or JavaScript object or string of style name
 * @param array p_aAttribs
 * @return string HTML
 * @todo Add alt and class attributes
 *----------------------------------------
 */
dimage.img = function(p_mText, p_xStyle, p_aAttribs) {
if(typeof(p_aAttribs) !== 'object') {
p_aAttribs = {};
}
return Array(
'<img',
' src="' + dimage.url(p_mText, p_xStyle) + '"',
' />'
).join('');
};


/**
 *----------------------------------------
 * Get the URL for a dimage
 * @param mixed p_mText String of text or JSON array of texts
 * @param mixed p_mStyle String of JSON or JavaScript object or string of style name
 * @return string URL on success, FALSE on fail
 *----------------------------------------
 */
dimage.url = function(p_mText, p_xStyle) {
var l_sUrl = dimage.displayUrl + '?';
var l_mText = p_mText;
var params = {
"cache": dimage.cache,
"text": (typeof(l_mText) === 'string') ? escape(l_mText) : l_mText
};
if(p_xStyle) {
params['style'] = p_xStyle;
if(typeof(p_xStyle) === 'string') {
try {
params['style'] = $.parseJSON(p_xStyle);
} catch(e) {}
}
}
return l_sUrl + $.param(params);
};

/*SWFObject v2.2 <http://code.google.com/p/swfobject/> 
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158; 
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */


// ------------------------ Ajax Engine ----------------------------------------

var l_sAJ = '/ajax/ajax.php';

BaseAjax = {};
BaseAjax._count = 0;
BaseAjax._xArgs = {};

BaseAjax._xArray = {};


BaseAjax.makeAjaxCall = function() {

BaseAjax._count++;

BaseAjax._xArray[BaseAjax._count] = BaseAjax._xArgs;
var ajax = BaseAjax.doAjax(BaseAjax._count,l_sAJ);

BaseAjax._xArgs = {};

return ajax
}

BaseAjax.abort=function(countVar){
if(BaseAjax._xArray[countVar]){
BaseAjax._xArray[countVar] = null;
return true;
}
return false;
}

BaseAjax.doAjax = function(countVar, url){

if (BaseAjax._xArray[countVar].noOverlay != true) {BaseAjax.setLoaderOverlay(BaseAjax._xArray[countVar].returnDiv);}
if(BaseAjax._xArray[countVar].loaderDiv && BaseAjax._xArray[countVar].loaderType){

BaseAjax.setInsideLoaderOverlay(BaseAjax._xArray[countVar].loaderDiv, BaseAjax._xArray[countVar].loaderType);

BaseAjax._xArray[countVar].noloader = false;
}
var requestType = "POST";
if(BaseAjax._xArray[countVar].requestType != null){
requestType = BaseAjax._xArray[countVar].requestType;
}

$.ajax({
type:      requestType,
url:        url,
data:       BaseAjax._xArray[countVar].data,
success:    function(p_sMsg,status,etc) {
BaseAjax.onAjaxCallReturned(countVar, p_sMsg);
},
error:    function() {
BaseAjax.onAjaxCallFailure(countVar);
}
});

return countVar;
}




BaseAjax.onAjaxCallReturned = function(countVar, p_sMsg) {
if(BaseAjax._xArray[countVar].returnDiv){
$(BaseAjax._xArray[countVar].returnDiv).html(p_sMsg);
}

BaseAjax.returnVar = p_sMsg;
if(BaseAjax._xArray[countVar].callBack) {
BaseAjax._xArray[countVar].callBack();
}

BaseAjax._xArray[countVar] = null;
}


BaseAjax.onAjaxCallFailure = function(countVar) {
if(BaseAjax._xArray[countVar].failureCallBack) {
BaseAjax._xArray[countVar].failureCallBack();
}
BaseAjax._xArray[countVar] = null;
}



BaseAjax.setInsideLoaderOverlay = function( theElement,type ){

$(theElement).height( $(theElement).height() );
$(theElement).width( $(theElement).width() );
$(theElement).css( 'float','left' );

var padLeft = $(theElement).css('padding-left');
var padTop = $(theElement).css('padding-top');

$(theElement).empty();

if( $(theElement).css('position') != 'absolute' )
$(theElement).css('position','relative');

var l_nHeight = $(theElement).height();
var l_nWidth = $(theElement).width();


/*
$(theElement).append(
'<img src="'+eval('loadingImg_'+type)+'" style="'+
 'position:absolute; '+
'margin-top:'+ padTop+'; '+
'margin-left:'+padLeft+'; '+
 'left:'+(l_nWidth - 100) / 2+'px; '+
'top:'+(l_nHeight - 100) / 2+'px; '+
'z-index:1201; '+
'" /> '
);
*/
}


BaseAjax.setLoaderOverlay = function( theElement ){

var loadingImg = "http://hungryforchange.com/image/space.gif";

if( $(theElement).css('position') != 'absolute' && $(theElement).css('position') != 'fixed' )
$(theElement).css('position','relative');

var padLeft = $(theElement).css('padding-left');
var padTop = $(theElement).css('padding-top');


var l_nHeight = $(theElement).height();
var l_nWidth = $(theElement).width();


$(theElement).append(
'<div id="ajaxoverlay" style="background:#fff;'+
 'width:'+l_nWidth+'px; '+
'height:'+l_nHeight+'px; '+
 'position:absolute; '+
'top:'+ padTop+'; '+
'left:'+padLeft+'; '+
'z-index:20; '+
'filter:alpha(opacity=20);-moz-opacity:.2;opacity:.2;'+
'z-index:1200; '+
'"></div> '
);



}






_xUtils = {

checkEmpty : function(p_sVal){
l_sVal = escape(p_sVal);
l_sVal = l_sVal.replace(/\s*((\S+\s*)*)/, "$1");
l_sVal = l_sVal.replace(/((\s*\S+)*)\s*/, "$1");
return l_sVal.length < 1;
}
,
checkEmail : function(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){ return false }
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ return false }
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return false }
if (str.indexOf(at,(lat+1))!=-1){ return false }
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ return false }
if (str.indexOf(dot,(lat+2))==-1){ return false }
if (str.indexOf(" ")!=-1){ return false }
return true
},
checkAlphaNumeric : function(p_sVal){
return !(/[^a-zA-Z0-9]/.test(p_sVal));
}

}




function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}


/**
*
*  Base64 encode / decode
*
**/
 
var Base64 = {
 
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
 
input = Base64._utf8_encode(input);
 
while (i < input.length) {
 
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
 
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
 
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
 
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
}
 
return output;
},
 
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
 
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
while (i < input.length) {
 
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
 
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
 
output = output + String.fromCharCode(chr1);
 
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
 
}
 
output = Base64._utf8_decode(output);
 
return output;
 
},
 
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
 
for (var n = 0; n < string.length; n++) {
 
var c = string.charCodeAt(n);
 
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
 
}
 
return utftext;
},
 
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
 
while ( i < utftext.length ) {
 
c = utftext.charCodeAt(i);
 
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
 
}
 
return string;
}
 
}

/**
*
*  Serializer for php
*
**/

function php_serialize(obj)
{
    var string = '';

    if (typeof(obj) == 'object') {
        if (obj instanceof Array) {
            string = 'a:';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                tmpstring += php_serialize(obj[key]);
                count++;
            }
            string += count + ':{';
            string += tmpstring;
            string += '}';
        } else if (obj instanceof Object) {
            classname = obj.toString();

            if (classname == '[object Object]') {
                classname = 'StdClass';
            }

            string = 'O:' + classname.length + ':"' + classname + '":';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                if (obj[key]) {
                    tmpstring += php_serialize(obj[key]);
                } else {
                    tmpstring += php_serialize('');
                }
                count++;
            }
            string += count + ':{' + tmpstring + '}';
        }
    } else {
        switch (typeof(obj)) {
            case 'number':
                if (obj - Math.floor(obj) != 0) {
                    string += 'd:' + obj + ';';
                } else {
                    string += 'i:' + obj + ';';
                }
                break;
            case 'string':
                string += 's:' + obj.length + ':"' + obj + '";';
                break;
            case 'boolean':
                if (obj) {
                    string += 'b:1;';
                } else {
                    string += 'b:0;';
                }
                break;
        }
    }

    return string;
}


/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/
 
var MD5 = function (string) {
 
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
 
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
 }
 
 function F(x,y,z) { return (x & y) | ((~x) & z); }
 function G(x,y,z) { return (x & z) | (y & (~z)); }
 function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
 
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
 
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
 
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
 
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
 
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
 
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
 
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
 
for (var n = 0; n < string.length; n++) {
 
var c = string.charCodeAt(n);
 
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
 
}
 
return utftext;
};
 
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
 
string = Utf8Encode(string);
 
x = ConvertToWordArray(string);
 
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
 
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 
return temp.toLowerCase();
}

$(document).ready(function(){

_xParties.init();


})

_xParties = {

init:function(){
_xParties.initHovers();
_xParties.fixTwoItemCarousels();
if(_xParties._bIsDetail)
_xParties.setCarousel();

},
_nExclude:0,
_nAnim : 250,

/*********************
*
* Init
*
**********************/

initHovers:function(){

$('a.party_holder').live('mouseenter',function(){
var l_nHeightDiff = $(this).find('.bottom').height();
$reel = $(this).find('.text_reel');
$reel.animate({bottom:l_nHeightDiff},_xParties._nAnim);
$overlay = $(this).find('.overlay');
$overlay.fadeIn(_xParties._nAnim);
})
$('a.party_holder').live('mouseleave',function(){
$reel = $(this).find('.text_reel');
$reel.animate({bottom:0},_xParties._nAnim);
$overlay = $(this).find('.overlay');
$overlay.fadeOut(_xParties._nAnim);
})

},


/*********************
*
* Carousel
*
**********************/

_nCurrentCarouselSlide:0,
_bIsCarouselAnimating:false,
_nCarouselSpeed:400,
_sPartyTitle:'',
_bHasAd:false,
_xAdPollInterval : false,
_nAdPollTime:500,
_nAdWidth:0,
_nAdPosition : 0,
_nPollCount:0,

setCarousel:function(){
_xParties.mapPartyKeys();

$(window).resize(function(e){
_xParties.snapToCorrectSlide()
});


$('#parties_slideshow').find('.parties_arrow_left').click(function(){
_xParties.jumpToCarousel(-1);
});
$('#parties_slideshow').find('.parties_arrow_right').click(function(){
_xParties.jumpToCarousel(1);
});

$('#parties_slideshow').find('a.thumbnails').click(function(){
_xParties.showThumbnails();
});

$('#parties_slideshow').find('a.lightbox').click(function(){
$target = $('#parties_slideshow').find('.homebase[data-number='+_xParties._nCurrentCarouselSlide+']');
var l_nAssetId = $target.attr('rev');
var l_sTitle = $.trim(_xParties._sPartyTitle);
var l_sDesc = $.trim(  $('#meta_data_holder').find('.meta_data[rel='+_xParties._nCurrentCarouselSlide+']').find('.parties_hiddendesc').html()  );
_xLightboxes.openUI(l_nAssetId, this,l_sTitle,l_sDesc);
});

//setTimeout(function(){ _xParties.snapToCorrectSlide(); },100);

_xParties._xAdPollInterval = setInterval(function(){  _xParties.pollForAd();  }, _xParties._nAdPollTime);
_xParties.pollForAd();
},

prepAdForCarousel:function(){
//console.log(_xParties._sAdBackupImage);
if(_xParties._nAdWidth > 1){
_xParties._bHasAd = true;
if(_xParties._nAdWidth==300){
$('#parties_slideshow').find('.ad_item').addClass('small_ad_holder');
}else{
}

$('#parties_slideshow').find('.ad_item').width(_xParties._nAdWidth);

}else{
$('#parties_slideshow').find('.ad_item').hide();
}
_xParties.snapToCorrectSlide();
$('#parties_block_overlay').fadeOut(200);

},

pollForAd:function(){ 
var l_xPollReturn = _xParties.pollForAdReal('parties_ad_holder');
if(l_xPollReturn){
clearInterval(_xParties._xAdPollInterval);
_xParties._nAdWidth = parseInt(l_xPollReturn._sWidth);
_xParties.prepAdForCarousel()
// if 1 second of polling pass, give it up for lost
} else if(_xParties._nPollCount++==3){
clearInterval(_xParties._xAdPollInterval);
_xParties._nAdWidth = 0;
_xParties.prepAdForCarousel()
}
},
pollForAdReal:function(p_sDivId){
var $ad_holder = $('#'+p_sDivId);

var $l_axNoScripts = $ad_holder.find('noscript');
var $l_axAnchorTags = $ad_holder.find('a');

var $l_xReturn = {};
var l_bReturn = false;

if($l_axNoScripts.length>1){
var $l_xNoScript;
$l_axNoScripts.each(function(){
if(!$(this).hasClass('original_noscript')){
$l_xNoScript = $(this);
}
});


var $l_axObjects = $ad_holder.find('object');
var $l_axEmbeds = $ad_holder.find('embed');

if($l_axObjects.length){
$l_xReturn._sWidth = $l_axObjects.attr('width');
}
else if($l_axEmbeds.length){
$l_xReturn._sWidth = $l_axEmbeds.attr('width');
}
return $l_xReturn;
}
else if($l_axAnchorTags.length){
$l_xReturn._sImg =  $l_axAnchorTags.eq(0).html();
$l_xReturn._sWidth =  $l_axAnchorTags.find('img').attr('width');
return $l_xReturn;
}

return false;
},


jumpToNextSlide:function(){
_xParties.jumpToCarousel(1);
},
jumpToPrevCSlide:function(){
_xParties.jumpToCarousel(-1);
},

// Target is 1 or -1
jumpToCarousel:function(p_nTarget){
if(!_xParties._bIsCarouselAnimating){
_xParties._bIsCarouselAnimating = true

$current = $('#parties_images_shifter').find('.homebase[data-number='+_xParties._nCurrentCarouselSlide+']')
var l_nRealTarget = parseInt(p_nTarget+ parseInt($current.attr('rel')) )

if(!_xParties._bHasAd){
if( p_nTarget > 0 && _xParties._nCurrentCarouselSlide+1 == _xParties._nAdPosition  ){
l_nRealTarget++;
}
if( p_nTarget < 0 && (_xParties._nCurrentCarouselSlide-1 == _xParties._nAdPosition || _xParties._nCurrentCarouselSlide == 0) ){ 
l_nRealTarget--;
}
}

$target = $('#parties_images_shifter').find('.parties_item[rel='+l_nRealTarget+']')


$target.find('.party_overlay').hide();
$current.find('.party_overlay').show();
var l_nTargetDataNumber = parseInt($target.attr('data-number'));

var l_nWidth = $(window).width();
var l_nTargetWidth = parseInt($target.css('width'));

var l_aPosition = $target.position();
var l_nLeft = parseInt(parseInt(l_aPosition.left) - parseInt(l_nWidth/2) + parseInt(l_nTargetWidth/2))

$('#parties_images_shifter').animate({left: -l_nLeft},_xParties._nCarouselSpeed,function(){_xParties.jumpToCarouselCallback(l_nTargetDataNumber)})

if($target.hasClass('ad_item')){
var $ad_container;
$('.homebase').each(function(){
if($(this).hasClass('ad_item')){$ad_container = $(this);} 
});
setTimeout(function(){
var l_xPosition = $ad_container.offset();
$('#parties_carousel_ad').css({'top': l_xPosition.top+113, 'left': l_xPosition.left+20}).show();
}, _xParties._nCarouselSpeed);
$('#parties_slideshow').find('.button_holder').hide();
$('#meta_data_holder').find('.meta_data').css('visibility','hidden');
}
else{
$('#parties_carousel_ad').hide();
$('#parties_slideshow').find('.button_holder').show();
$('#meta_data_holder').find('.meta_data').css('visibility','visible');
}
}

},
jumpToCarouselCallback:function(p_nTargetNumber){
_xMain.callOmniture(p_nTargetNumber, 'slide')
                _xParties._bIsCarouselAnimating = false
_xParties._nCurrentCarouselSlide = p_nTargetNumber
_xParties.snapToCorrectSlide()

$('#meta_data_holder').find('.meta_data').hide()
$('#meta_data_holder').find('.meta_data[rel='+p_nTargetNumber+']').fadeIn(200)
},

showThumbnails:function(){
$('#thumbnail_overlay').fadeIn(200);
_xParties.paginateParty(1);
},

paginateParty:function(p_nPage){
BaseAjax._xArgs.data = 'a=PartiesDetailPagination';
BaseAjax._xArgs.data += '&id='+_xParties._nPartyId
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#thumbnail_holder';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax._xArgs.callBack = function(){_xParties.paginatePartyCallback()};

BaseAjax.makeAjaxCall();


},

paginatePartyCallback:function(){
$('#thumbnail_holder').fadeIn(200);
},

leaveThumbnails:function(){
$('#thumbnail_overlay').hide();
$('#thumbnail_holder').hide();
},
selectImage:function(p_nIndex){

if(p_nIndex > _xParties._nAdPosition-1 && _xParties._bHasAd){p_nIndex++}

        _xMain.callOmniture(p_nIndex, 'slide')
_xParties._nCurrentCarouselSlide = p_nIndex
_xParties.snapToCorrectSlide();
_xParties.leaveThumbnails();
$('#meta_data_holder').find('.meta_data').hide()
$('#meta_data_holder').find('.meta_data[rel='+p_nIndex+']').fadeIn(200)
},

snapToCorrectSlide:function(){

$target = $('#parties_images_shifter').find('div.homebase[data-number='+_xParties._nCurrentCarouselSlide+']')

var l_nWidth = $(window).width();
var l_nTargetWidth = parseInt($target.css('width'));

var l_aPosition = $target.position();
var l_nLeft = parseInt(parseInt(l_aPosition.left) - parseInt(l_nWidth/2) + parseInt(l_nTargetWidth/2))
$('#parties_images_shifter').css('left','-'+l_nLeft+'px')

$('#parties_slideshow').find('.party_overlay').show();
$target.find('.party_overlay').hide();

},



/*********************
*
* Landing
*
**********************/

paginateLanding:function(p_nPage, p_xThis){
_xMain.callOmniture(p_nPage, 'slide')
var l_sTerm = _xParties._sCurrentSearchTerm;
var l_nCategory = _xParties._nCurrentCategoryFilter;

BaseAjax._xArgs.data = 'a=PartiesUpdateLanding';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&exclude='+_xParties._nExclude;

if(l_nCategory != undefined)
BaseAjax._xArgs.data += '&category='+l_nCategory;
if(l_sTerm != undefined)
BaseAjax._xArgs.data += '&deepsearch='+escape(l_sTerm);
BaseAjax._xArgs.returnDiv = '#parties_landing_inner';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

$.scrollTo('#parties_grand_holder');

},

searchLanding:function(){
var l_sTerm = $('#parties_search').val();
var l_sRel = $('#parties_search').attr('rel');
if(l_sRel==l_sTerm) l_sTerm = ''
var l_nCategory = _xParties._nCurrentCategoryFilter;

_xParties._sCurrentSearchTerm = escape(l_sTerm)
BaseAjax._xArgs.data = 'a=PartiesUpdateLanding';
BaseAjax._xArgs.data += '&page=1';
BaseAjax._xArgs.data += '&exclude='+_xParties._nExclude;
if(parseInt(l_nCategory))
BaseAjax._xArgs.data += '&category='+l_nCategory;
if(l_sTerm != undefined)
BaseAjax._xArgs.data += '&deepsearch='+escape(l_sTerm);
BaseAjax._xArgs.returnDiv = '#parties_landing_inner';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

},

categorizeLanding:function(p_nCategory){
_xParties._nCurrentCategoryFilter = p_nCategory
var l_sTerm = _xParties._sCurrentSearchTerm;

BaseAjax._xArgs.data = 'a=PartiesUpdateLanding';
BaseAjax._xArgs.data += '&category='+p_nCategory;
BaseAjax._xArgs.data += '&exclude='+_xParties._nExclude;
if(l_sTerm != undefined)
BaseAjax._xArgs.data += '&deepsearch='+escape(l_sTerm);
BaseAjax._xArgs.data += '&page=1';
BaseAjax._xArgs.returnDiv = '#parties_landing_inner';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},

getPrev:function(){
var $photo_holder = $('#parties_photo');

if($photo_holder.find('.party_holder').length > 1){
var $first = $photo_holder.find('.party_holder:first');
var $last = $photo_holder.find('.party_holder:last');
var $selected = $photo_holder.find('.selected');
var $next = $photo_holder.find('.next');
var $prev = $photo_holder.find('.prev');

if($prev[0] == $first[0]){
var $prevprev = $last;
}
else{
var $prevprev = $prev.prev();
}

$selected.fadeOut(_xParties._nAnim).attr('class', 'party_holder next');
$prev.fadeIn(_xParties._nAnim).attr('class', 'party_holder selected');
$next.attr('class', 'party_holder');
$prevprev.attr('class', 'party_holder prev');

var l_nNumber = $prev.attr('data-count');
$('#parties_module_count').children('span').text(l_nNumber);
}
},

getNext:function(){
var $photo_holder = $('#parties_photo');

if($photo_holder.find('.party_holder').length > 1){
var $first = $photo_holder.find('.party_holder:first');
var $last = $photo_holder.find('.party_holder:last');
var $selected = $photo_holder.find('.selected');
var $next = $photo_holder.find('.next');
var $prev = $photo_holder.find('.prev');

if($next[0] == $last[0]){
var $nextnext = $first;
}
else{
var $nextnext = $next.next();
}

$selected.fadeOut(_xParties._nAnim).attr('class', 'party_holder prev');
$next.fadeIn(_xParties._nAnim).attr('class', 'party_holder selected');
$prev.attr('class', 'party_holder');
$nextnext.attr('class', 'party_holder next');

var l_nNumber = $next.attr('data-count');
$('#parties_module_count').children('span').text(l_nNumber);
}
},

fixTwoItemCarousels:function(){
var $parties_photo = $('#parties_photo');
var l_nPartyCount = $parties_photo.find('.party_holder').length;

if(l_nPartyCount==2){
var $selected = $parties_photo.find('.selected');
var $next = $parties_photo.find('.next');
var $prev = $parties_photo.find('.prev');
var $last = $parties_photo.find('.party_holder:last');

$next.clone().attr('class', 'party_holder prev').insertAfter($last);
$selected.clone().attr('class', 'party_holder').insertAfter($last);
}
},

        mapPartyKeys:function() {
                $(document).unbind("keydown");

                $(document).keydown(function(e){
                        if (e.keyCode == 37) {
                           _xParties.jumpToCarousel(-1);
                           e.preventDefault;
                        }

                            if (e.keyCode == 39) {
                           _xParties.jumpToCarousel(1);
                           return false;
                        }
                    });
        }


}


$(document).ready(function(){
_xhfcFeatureArea.init(); 
});

_xhfcFeatureArea = {

_nAmountBelowFold: 250, //pixel height to be shown below features
_nMinimumFeatureHeight: 480, //400, TODO: uncomment this line to return to prev dynamic height settings
_nAnimationTime: 800,
_aFeatures: {},
_nCurrentFeature: 0,
_nNextFeature: '',
_nPrevFeature: '',
_nNextNextFeature: '',
_nPrevPrevFeature: '',

_nCurrentImageHeight: '',
_nCurrentImageWidth: 0,

_nCurrentWindowHeight: 0,
_nCurrentWindowWidth: 0,

_xLoadInterval: '',

_bLoadOne: false,
_bLoadTwo: false,
_bLoadThree: false,

_nAutoTimer: 8000,
_xAutoInterval: '',


_nAdPollTime: 100,
_xAdPollInterval: '',
_sAdBackupImage1: '',
_sAdBackupImage2: '',
_bAdOneLoaded: false,
_bAdTwoLoaded: false,

 
init:function(){
if ($('#header').length) {
this.setClickHandlers();
this.setHovers();
this.setNextPrev();
this.checkForInitialAds();
this.loadImages();
this._xLoadInterval = setInterval(function(){ _xhfcFeatureArea.checkForLoadedImages(); }, _xhfcFeatureArea._nAdPollTime);
this._xAdPollIntervalOne = setInterval(function(){ _xhfcFeatureArea.pollForAdOne(); }, _xhfcFeatureArea._nAdPollTime);
this._xAdPollIntervalTwo = setInterval(function(){ _xhfcFeatureArea.pollForAdTwo(); }, _xhfcFeatureArea._nAdPollTime);
if(!document.isHomePage){ this.autoScrollToContent(); }
}


//$(window).resize(function(){ _xhfcFeatureArea.adjustImages(); });

 //temporary replacement for calling adjustImages on resize
$(window).resize(function(){
_xhfcFeatureArea.getWindowDimensions();
_xhfcFeatureArea.adjustImagePositions(); 
}); 
},


pollForAdOne:function(){ 
var l_sPollReturn = this.pollForAd('feature_ad_holder_1');
if(l_sPollReturn){
clearInterval(this._xAdPollIntervalOne);
this._sAdBackupImage1 = l_sPollReturn;
this._bAdOneLoaded = true;
} 
},

pollForAdTwo:function(){ 
var l_sPollReturn = this.pollForAd('feature_ad_holder_2');
if(l_sPollReturn){
clearInterval(this._xAdPollIntervalTwo);
this._sAdBackupImage2 = l_sPollReturn; 
this._bAdTwoLoaded = true;
} 
},

pollForAd:function(p_sDivId){
var $ad_holder = $('#'+p_sDivId);

var $l_axNoScripts = $ad_holder.find('noscript');
var $l_axAnchorTags = $ad_holder.find('a');

if($l_axNoScripts.length>1){
var $l_xNoScript;
$l_axNoScripts.each(function(){
if(!$(this).hasClass('original_noscript')){
$l_xNoScript = $(this);
}
});

var l_xRegEx = new RegExp(/img src="(.+?)"/i);
var l_aMatches = l_xRegEx.exec($l_xNoScript.html());

if(l_aMatches){
var l_sImgSrc = l_aMatches[1];
return '<img src="'+l_sImgSrc+' />';
}
else return true;
}
else if($l_axAnchorTags.length){
return $l_axAnchorTags.eq(0).html();
}

return false;
},


checkForInitialAds:function(){
if(this.isAd(this._nCurrentFeature))
this._bLoadOne = true;
if(this.isAd(this._nNextFeature))
this._bLoadTwo = true;
if(this.isAd(this._nPrevFeature))
this._bLoadThree = true;
},

alterLogo:function(p_sVariation){
if(p_sVariation == 'D')
$('#logo').addClass('dark')
else
$('#logo').removeClass('dark')
},

setNextPrev:function(){
this._nPrevFeature = this._nCurrentFeature - 1;
this._nPrevPrevFeature = this._nCurrentFeature - 2;
this._nNextFeature = this._nCurrentFeature + 1;
this._nNextNextFeature = this._nCurrentFeature + 2;

if(this._nCurrentFeature == 0){
this._nPrevFeature = this._aFeatures.length - 1;
this._nPrevPrevFeature = this._aFeatures.length - 2;
}
else if(this._nCurrentFeature == 1){
this._nPrevPrevFeature = this._aFeatures.length - 1;
}
else if(this._nCurrentFeature == this._aFeatures.length - 1){
this._nNextFeature = 0;
this._nNextNextFeature = 1;
}
else if(this._nCurrentFeature == this._aFeatures.length - 2){
this._nNextNextFeature = 0;
}
},

loadImages:function(){
$('#imageloadone').load( function(){ _xhfcFeatureArea._bLoadOne = true; } );
$('#imageloadone').attr('src',this._aFeatures[this._nCurrentFeature].image_uri);

this.alterLogo(this._aFeatures[this._nCurrentFeature].variation);

$('#imageloadtwo').load(function(){ _xhfcFeatureArea._bLoadTwo = true; } );
$('#imageloadtwo').attr('src',this._aFeatures[this._nNextFeature].image_uri);

$('#imageloadthree').load( function(){ _xhfcFeatureArea._bLoadThree = true; } );
$('#imageloadthree').attr('src',this._aFeatures[this._nPrevFeature].image_uri);
},

checkForLoadedImages:function(){
if(this._bLoadOne && this._bLoadTwo && this._bLoadThree && this._bAdOneLoaded && this._bAdTwoLoaded){
clearInterval(this._xLoadInterval);

_xhfcFeatureArea.setFeatureImages();
setTimeout(function(){  
_xhfcFeatureArea.adjustImages(true); 
$('#header').find('.init_wrapper').fadeTo(400, 1);
$('#logo').fadeTo(400, 1);
$('#left_arrow,#right_arrow').show();
}, 100);

_xhfcFeatureArea.startAutoAdvance();
}
},


startAutoAdvance:function(){
// _xhfcFeatureArea._xAutoInterval = setInterval ( function(){ _xhfcFeatureArea.getNextFeature(); _xhfcFeatureArea.updateArrowInfo(); }, _xhfcFeatureArea._nAutoTimer );
},

stopAutoAdvance:function(){
clearInterval(_xhfcFeatureArea._xAutoInterval);
},

autoScrollToContent:function(){
//_xhfcFeatureArea.adjustImages();
$('#header').height(480)
$.scrollTo(480);
},


adjustImages:function(p_bInit){
// For Nordstrom & Unicast
$('body').children('div[id$=Div2]').hide();

this.getWindowDimensions();
this._nAmountBelowFold = this._nCurrentWindowHeight*.33; //delete this line if _nAmountBelowFold should remain constant

var $l_axImgs = $('#header').find('.image_wrapper').find('img');
var $l_axOverlays = $('#header').find('.hero_overlay');
var $l_axAd1 = $('#feature_ad_holder_1');
var $l_axAd2 = $('#feature_ad_holder_2');

this._nCurrentImageHeight = 480; //parseInt(this._nCurrentWindowHeight-this._nAmountBelowFold); TODO: uncomment this line for dynamic header sizing
if(this._nCurrentWindowHeight <= this._nAmountBelowFold + this._nMinimumFeatureHeight){ 
this._nCurrentImageHeight = parseInt(this._nMinimumFeatureHeight); 
}

$l_axImgs.height(this._nCurrentImageHeight);
if(p_bInit===true){
//$('#header').animate({height: this._nCurrentImageHeight},400);
}
else
$('#header').height(this._nCurrentImageHeight);
this._nCurrentImageWidth = parseInt($l_axImgs.width());


this.adjustImagePositions();
this.adjustArrowPosition(this._nCurrentImageHeight);

if($('#ad_wrapper_1').length > 0){
var l_nAdOffset = $('#ad_wrapper_1').offset().left;
$l_axAd1.css({'height': this._nCurrentImageHeight, 'width':this._nCurrentImageWidth, 'left': l_nAdOffset });
}

if($('#ad_wrapper_2').length > 0){
var l_nAdOffset = $('#ad_wrapper_2').offset().left;
$l_axAd2.css({'height': this._nCurrentImageHeight, 'width':this._nCurrentImageWidth, 'left': l_nAdOffset });
}
},


getWindowDimensions:function(){
this._nCurrentWindowHeight = $(window).height();
this._nCurrentWindowWidth = $(window).width();
},


adjustImagePositions:function(){
var $l_axImgs = $('#header').find('.image_wrapper');

var l_nPositionOne = parseInt(this._nCurrentWindowWidth/2)-(this._nCurrentImageWidth/2);
var l_nPositionZero = l_nPositionOne - this._nCurrentImageWidth;
var l_nPositionTwo = l_nPositionOne + this._nCurrentImageWidth;

$l_axImgs.eq(0).css('left', l_nPositionZero);
$l_axImgs.eq(1).css('left', l_nPositionOne).find('.hero_overlay').hide();
$l_axImgs.eq(2).css('left', l_nPositionTwo-1);

$('.feature_ad_holder').css('left', l_nPositionOne);

$('#logo').css('left',l_nPositionOne);
},


adjustArrowPosition:function(p_nImageHeight){
$('#left_arrow, #right_arrow').css('top', parseInt(p_nImageHeight/2 - 35));
},


setFeatureATag:function(p_nIndex,p_nHeight){
var l_sExtra = '';
if(parseInt(p_nHeight))
l_sExtra += ' style="height:'+p_nHeight+'px"';

var l_xFeatureObj = this._aFeatures[p_nIndex]

return '<a href="'+this._aFeatures[p_nIndex].url+'" ><div class="hero_overlay"></div><img src="'+this._aFeatures[p_nIndex].image_uri+'" '+l_sExtra+' alt="'+this._aFeatures[p_nIndex].title+'"/></a>';
},

getInitialAdHtml:function(p_nIndex, p_nAdNumber){
if(p_nAdNumber == 1)
var l_sAdHtml = this._sAdBackupImage1;
else
var l_sAdHtml = this._sAdBackupImage2;

l_sAdHtml = '<div class="hero_overlay"></div>' + l_sAdHtml;
return l_sAdHtml;
},

setFeatureImages:function(){
$l_axImageWrappers = $('#header').children('.image_wrapper');

if(this.isAd(this._nPrevFeature)){
var l_nAdNumber = this._aFeatures[this._nPrevFeature].ad_number;
var l_sAdHtml = this.getInitialAdHtml(this._nPrevFeature, l_nAdNumber);
$l_axImageWrappers.eq(0).addClass('ad_wrapper').attr('id', 'ad_wrapper_'+l_nAdNumber).html(l_sAdHtml);
}
else{
$l_axImageWrappers.eq(0).html(this.setFeatureATag(this._nPrevFeature));
}

if(this.isAd(this._nCurrentFeature)){
var l_nAdNumber = this._aFeatures[this._nCurrentFeature].ad_number;
var l_sAdHtml = this.getInitialAdHtml(this._nCurrentFeature, l_nAdNumber);
$l_axImageWrappers.eq(1).addClass('ad_wrapper').attr('id', 'ad_wrapper_'+l_nAdNumber).html(l_sAdHtml);
}
else{
$l_axImageWrappers.eq(1).html(this.setFeatureATag(this._nCurrentFeature));
}

if(this.isAd(this._nNextFeature)){
var l_nAdNumber = this._aFeatures[this._nNextFeature].ad_number;
var l_sAdHtml = this.getInitialAdHtml(this._nNextFeature, l_nAdNumber);
$l_axImageWrappers.eq(2).addClass('ad_wrapper').attr('id', 'ad_wrapper_'+l_nAdNumber).html(l_sAdHtml);
}
else{
$l_axImageWrappers.eq(2).html(this.setFeatureATag(this._nNextFeature));
}

//this.switchHighlighted();
},

getFeatureHtml:function(p_nIndex, p_nPosition){
p_nPosition = parseInt(p_nPosition);
if(this.isAd(p_nIndex)){
var l_nAdNumber = _xhfcFeatureArea._aFeatures[p_nIndex].ad_number;

if(l_nAdNumber == 1){
var l_sHtml = '<div id="ad_wrapper_'+l_nAdNumber+'" class="image_wrapper ad_wrapper" style="left:'+p_nPosition+'px;">';
l_sHtml +='<div class="hero_overlay"></div>'+this._sAdBackupImage1; 
l_sHtml += '</div>';
}
else if(l_nAdNumber == 2){
var l_sHtml = '<div id="ad_wrapper_'+l_nAdNumber+'" class="image_wrapper ad_wrapper" style="left:'+p_nPosition+'px;">';
l_sHtml +='<div class="hero_overlay"></div>'+this._sAdBackupImage2;
l_sHtml += '</div>';
}
}
else{
var l_sHtml = '<div class="image_wrapper" style="left:'+p_nPosition+'px;">'+this.setFeatureATag(p_nIndex,this._nCurrentImageHeight)+'</div>';
}
return l_sHtml;
},

getPrevFeature:function(){
$('#header').find('.hero_overlay').show();
var l_nPosition = parseInt(this._nCurrentWindowWidth/2 - (this._nCurrentImageWidth*2.5));

var l_sPrevPrevHtml = this.getFeatureHtml(this._nPrevPrevFeature, l_nPosition);
$('#header').find('.image_wrapper').eq(0).before(l_sPrevPrevHtml).find('.hero_overlay').hide();;
 

$l_axImgWrappers = $('#header').find('.image_wrapper'); 

$l_axImgWrappers.each(function(){
var l_nLeftPosition = $(this).offset().left;
var l_nNewPosition = l_nLeftPosition + _xhfcFeatureArea._nCurrentImageWidth;
$(this).animate({'left': l_nNewPosition}, _xhfcFeatureArea._nAnimationTime, 'easeOutExpo');
});
setTimeout(function(){
$l_axImgWrappers.eq(3).remove();
//_xhfcFeatureArea.switchHighlighted();
}, _xhfcFeatureArea._nAnimationTime);

this._nCurrentFeature = this._nPrevFeature;
this.setNextPrev();

if(this.isAd(this._nCurrentFeature)){ 
$('#logo').fadeOut(_xhfcFeatureArea._nAnimationTime*.5, function(){ _xhfcFeatureArea.showSwfAd(_xhfcFeatureArea._aFeatures[_xhfcFeatureArea._nCurrentFeature].ad_number); }); 
}
else{ 
$('#logo').fadeIn(_xhfcFeatureArea._nAnimationTime*.5); 
_xhfcFeatureArea.hideSwfAd();
}

this.alterLogo(this._aFeatures[this._nCurrentFeature].variation);
},


getNextFeature:function(){
$('#header').find('.hero_overlay').show();
var l_nPosition = parseInt(this._nCurrentWindowWidth/2 + (this._nCurrentImageWidth*1.5));

var l_sNextNextHtml = this.getFeatureHtml(this._nNextNextFeature, l_nPosition);
$('#header').find('.image_wrapper').eq(2).after(l_sNextNextHtml);

$l_axImgWrappers = $('#header').find('.image_wrapper');
$l_axImgWrappers.eq(2).width('auto').find('.hero_overlay').hide();

$l_axImgWrappers.each(function(){
var l_nLeftPosition = $(this).offset().left;
var l_nNewPosition = l_nLeftPosition - _xhfcFeatureArea._nCurrentImageWidth;
$(this).animate({'left': l_nNewPosition}, _xhfcFeatureArea._nAnimationTime, 'easeOutExpo');
});
setTimeout(function(){
$l_axImgWrappers.eq(0).remove();
//_xhfcFeatureArea.switchHighlighted();
}, _xhfcFeatureArea._nAnimationTime);

this._nCurrentFeature = this._nNextFeature;
this.setNextPrev();

if(this.isAd(this._nCurrentFeature)){ 
$('#logo').fadeOut(_xhfcFeatureArea._nAnimationTime*.5, function(){ _xhfcFeatureArea.showSwfAd(_xhfcFeatureArea._aFeatures[_xhfcFeatureArea._nCurrentFeature].ad_number); }); 
}
else{ 
$('#logo').fadeIn(_xhfcFeatureArea._nAnimationTime*.5); 
_xhfcFeatureArea.hideSwfAd();
}
this.alterLogo(this._aFeatures[this._nCurrentFeature].variation);
},


isAd:function(p_nFeatureNumber){
if(this._aFeatures[p_nFeatureNumber].ad === true){ 
return true; 
}

return false;
},

hideSwfAd:function(){
$('.feature_ad_holder').hide();
// For Nordstrom & Unicast
$('body').children('div[id$=Div2]').hide();
},

showSwfAd:function(p_nAdNumber){
setTimeout(function(){
var l_sLeft = $('.ad_wrapper').offset().left;
$('#feature_ad_holder_'+p_nAdNumber).show().css({ 'width':_xhfcFeatureArea._nCurrentImageWidth, 'height':_xhfcFeatureArea._nCurrentImageHeight, 'left':l_sLeft+'px' });
// For Nordstrom & Unicast
$('body').children('div[id$=Div2]').show();
}, _xhfcFeatureArea._nAnimationTime*.5);
},


updateArrowInfo:function(){
$('#right_arrow').find('.info').each(function(){
if($(this).attr('data-id')==_xhfcFeatureArea._aFeatures[_xhfcFeatureArea._nNextFeature].id){
$(this).addClass('selected').siblings().removeClass('selected');
}
});

$('#left_arrow').find('.info').each(function(){
if($(this).attr('data-id')==_xhfcFeatureArea._aFeatures[_xhfcFeatureArea._nPrevFeature].id){
$(this).addClass('selected').siblings().removeClass('selected');
}
});
},


setClickHandlers:function(){
$('#left_arrow').data('disabled', false).click(function(){
if($(this).data('disabled') === false){
_xhfcFeatureArea.getPrevFeature();
_xhfcFeatureArea.updateArrowInfo();
_xhfcFeatureArea.tempDisableClick(this);
_xhfcFeatureArea.stopAutoAdvance();
}
});
$('#right_arrow').data('disabled', false).click(function(){
if($(this).data('disabled') === false){
_xhfcFeatureArea.getNextFeature();
_xhfcFeatureArea.updateArrowInfo();
_xhfcFeatureArea.tempDisableClick(this);
_xhfcFeatureArea.stopAutoAdvance();
}
});
},


setHovers:function(){
$('#left_arrow').children('.button').hover(
function(){
$this = $(this);
$this.data('ishover',true);
$this.css('background-image','url(http://hungryforchange.com/image/arrow-left-off.png)');
$this.siblings('.infos_holder').animate({width: 'show'}, 100
,function(){
if($this.data('ishover')!==true)
$this.siblings('.infos_holder').hide();
});
$this.parent('.mf_arrow').addClass('more_zindex');
},
function(){
$(this).data('ishover',false);
$(this).css('background-image','url(http://hungryforchange.com/image/arrow-left-off.png)');
$(this).siblings('.infos_holder').hide();//animate({width: 'toggle'}, 125);
$(this).parent('.mf_arrow').removeClass('more_zindex');
}
);

$('#right_arrow').children('.button').hover(
function(){
$this = $(this);
$this.data('ishover',true);
$this.css('background-image','url(http://hungryforchange.com/image/arrow-right-off.png)');
$this.siblings('.infos_holder').animate({width: 'show'}, 100
,function(){
if($this.data('ishover')!==true)
$this.siblings('.infos_holder').hide();
});
$this.parent('.mf_arrow').addClass('more_zindex');
},
function(){
$(this).data('ishover',false);
$(this).css('background-image','url(http://hungryforchange.com/image/arrow-right-off.png)');
$(this).siblings('.infos_holder').hide();//animate({width: 'toggle'}, 125);
$(this).parent('.mf_arrow').removeClass('more_zindex');
}
);
},


tempDisableClick:function(p_xElement){
$(p_xElement).data('disabled', true);
setTimeout(function(){ $(p_xElement).data('disabled', false); }, _xhfcFeatureArea._nAnimationTime+200);
}


/*switchHighlighted:function(){
$l_axImgWrappers = $('#header').find('.image_wrapper');
$l_axImgWrappers.fadeTo(1,.25).eq(1).fadeTo(75, 1);
},*/
}


$(document).ready(function(){


var topVis = false;

$(window).scroll(function(){
var wo = (window.scrollY) ? window.scrollY : document.documentElement.scrollTop;
if(wo >= 480 ){
$('#placeholder').show();
$("#navigation").addClass('fixed');
topVis = true;
}
else if(wo < 480){
$('#placeholder').hide();
$("#navigation").removeClass('fixed');
topVis = false;
}
});


// SEARCH RESULTS SUBMIT BUTTON

        $("#search_results_search_button").click(function(){$("#search_results_search_form").submit();})

/*$('.hover_enabled_ad').live('mouseover', (function(){
$(this).children()[0].setExpanded(true); //set state inside SWF

var l_nExpandWidth = _xhfcFeatureArea._nCurrentImageWidth * 1.25;
var l_nExpandHeight = _xhfcFeatureArea._nCurrentImageHeight * 1.25;
$(this).parent('.ad_wrapper').addClass('ad_wrapper_expanded').css({'width': l_nExpandWidth, 'height': l_nExpandHeight, 'marginLeft': -l_nExpandWidth/2});
$(this).parent('.ad_wrapper').children('.swf_wrapper').css({'width': l_nExpandWidth, 'height': l_nExpandHeight});
$(this).siblings('.ad_overlay').show();
}));

$('.hover_enabled_ad').live('mouseout', (function(){
$(this).children()[0].setExpanded(false); //set state inside SWF

var l_nRetractWidth = _xhfcFeatureArea._nCurrentImageWidth;
var l_nRetractHeight = _xhfcFeatureArea._nCurrentImageHeight;
$(this).parent('.ad_wrapper').removeClass('ad_wrapper_expanded').css({'width': 'auto', 'height': 'auto', 'marginLeft': 0});
$(this).parent('.ad_wrapper').children('.swf_wrapper').css({'width': l_nRetractWidth, 'height': l_nRetractHeight});
$(this).siblings('.ad_overlay').hide();
}));*/


        if ($('#st_sharethis_custom').length && SHARETHIS != undefined)  {
setTimeout(function(){_xMain.callShareThis();}, 3000);
        }


        if ($('#footer_text_reception').length)   {
             CNP.ecom.request({
                        pid:'footer_text_reception',
                        tgt:'/atg/registry/RepositoryTargeters/VOG/VOG_global_subscriptions',
                        params:{program:'basic'},
                        callafter:{}
                });
        }


        if ($('#footer_module_reception').length)   {
             CNP.ecom.request({
                        pid:'footer_module_reception',
                        tgt:'/atg/registry/RepositoryTargeters/VOG/VOG_global_zRail',
                        params:{program:'basic'},
                        callafter:{}
                });
        }


        if ($('#submenu_reception').length)   {
             CNP.ecom.request({
                        pid:'submenu_reception',
                        tgt:'/atg/registry/RepositoryTargeters/VOG/VOG_global_navBar_subCenter',
                        params:{program:'basic'},
                        callafter:{}
                });
        }

        $(".bracket_arrow_large").mouseover(function(){$(this).children('a').addClass('hoverstate')});
        $(".bracket_arrow_large").mouseout(function(){$(this).children('a').removeClass('hoverstate')});
       

});

function expandAdContainer(p_sDivId){
//console.log('expand '+p_sDivId);
}

function collapseAdContainer(p_sDivId){
//console.log('collapse '+p_sDivId);
}





$(document).ready(function(){
_xMain.init();
});



_xMain = {
init:function(){
_xMain.setInputAutofills();
},

setInputAutofills:function(){
$target =  $('input.autofill')

$target.each(function(){
var l_sRel  = $(this).attr('rel')
var l_sVal  = $(this).val()
if(l_sVal=='') $(this).val(l_sRel)
});

$target.die();

$target.live('click',function(){
var l_sRel  = $(this).attr('rel')
var l_sVal  = $(this).val()
if(l_sVal== l_sRel){
$(this).val('')
}
});
$target.live('blur',function(){
var l_sRel  = $(this).attr('rel')
var l_sVal  = $(this).val()
if(l_sVal== ''){
$(this).val(l_sRel)
}
});

},


setVideoPlayer:function(p_sTargetId, p_nVideoId,p_nWidth,p_nHeight,p_bAutoplay,p_sDartZone,p_bIsVideoPage){

var l_nRatio = 800/450;


var l_nHeight = (parseInt(p_nHeight))? p_nHeight : p_nWidth / l_nRatio 

var l_xFlashVars = {
e:"dev",
video:p_nVideoId,
autoPlay:p_bAutoplay,
dartZone:p_sDartZone,
isVideoPage:p_bIsVideoPage
};
var l_xAttributes = {
id:"video_player_swf",
name:"video_player_swf"
};
var l_xParams = {
wmode: 'transparent',
allowfullscreen: 'true'
};
swfobject.embedSWF(CDN_SERVER+"/image_video_player.swf?r="+ RELEASE_VERSION, p_sTargetId, p_nWidth, l_nHeight, "9.0.0", "/swf/expressInstall.swf", l_xFlashVars, l_xParams, l_xAttributes);


},

callShareThis:function(){
object = SHARETHIS.addEntry({
title:'Sharing from HungryForChange.com',
url:window.location
}, {button:false,onmouseover:false} );

//Tie customized button to ShareThis button functionality.
var l_xShareElement = document.getElementById('st_sharethis_custom');
object.attachButton(l_xShareElement);
},

callOmniture:function(p_nId, p_sPrefix)  {
try{
if(CN!= undefined && CN.stats!= undefined && CN.stats.omniture != undefined  ){
if ((p_nId == null)) {p_nId = 0;}
if ((p_sPrefix == null)) {p_sPrefix = 'slide';}
var l_sSlideId = p_sPrefix+p_nId;
CN.stats.omniture.setPaginationValue(l_sSlideId).trackAjaxPage();
}
}catch(e){

}

}



}


$(document).ready(function(){
_xLightboxes.init();
});

_xLightboxes ={

_bIsLightboxPage:false, // for use with user.js
_nLastAsset : 0,
_nLastAssetFailsafe : 0,
_xLastButton:null,
_bUIDisplayed : false,
_bUILoading : false,
_nThisLightbox:0,
_nThisLightboxTotal:0,
_nCurrentDetailAsset:0,

_sUIAssetTitle:'',
_sUIAssetDesc:'',

init:function(){
$('body').append('<div id="lb_holder" class="lb_holder"></div>');


$(window).resize(function(e){
if(_xLightboxes._bUIDisplayed)
_xLightboxes.placeUI(_xLightboxes._xLastButton);
});


},

logUserIn:function(){
if (_xLightboxes._nLastAsset){
_xLightboxes._nLastAssetFailsafe = _xLightboxes._nLastAsset
_xLightboxes._nLastAsset = 0
}
$('#lb_holder').hide()
_xLightboxes._bUIDisplayed = true
},
logUserOut:function(){
if (_xLightboxes._nLastAsset){
_xLightboxes._nLastAssetFailsafe = _xLightboxes._nLastAsset
_xLightboxes._nLastAsset = 0
}
//$('#lb_holder').hide()
_xLightboxes._bUIDisplayed = false
},

showUIforGallery:function(p_xThis){
var l_nId = $('#gallery_center').attr('rel');
var l_sTitle = $.trim($('#lightbox_title').html());
var l_sDesc = $.trim($('#lightbox_desc').html());
_xLightboxes.openUI(l_nId,p_xThis,l_sTitle,l_sDesc);
},

openUI:function(p_nId,p_xThis,p_sTitle,p_sDescription){

_xLightboxes.placeUI(p_xThis);

if(  _xLightboxes._nLastAsset == p_nId ){ 
$('#lb_holder' ).show()
}else{
if(!p_sTitle)
p_sTitle = $.trim($('.defaultttile').html());

_xLightboxes._sUIAssetTitle = p_sTitle;
_xLightboxes._sUIAssetDesc = p_sDescription;
_xLightboxes._nLastAsset = p_nId;
_xLightboxes._xLastButton = p_xThis
_xLightboxes.openUIAjax();
}
},

placeUI:function(p_xObj){
if(!p_xObj) return;
var l_aPosition = $(p_xObj).offset();
var l_nThisWidth = $(p_xObj).width();

$('#lb_holder').css('top',parseInt(l_aPosition.top)).css('left',parseInt(l_aPosition.left)+l_nThisWidth);
},

openUIAjax:function(){

var l_nThisAsset = _xLightboxes._nLastAsset
if(!l_nThisAsset)
l_nThisAsset = _xLightboxes._nLastAssetFailsafe

if(_xLightboxes._bUILoading) return;
_xLightboxes._bUILoading = true;
$('#lb_holder' ).hide()

BaseAjax._xArgs.data = "a=LightboxOpenUI";
BaseAjax._xArgs.data += "&asset_id="+l_nThisAsset;

BaseAjax._xArgs.returnDiv = '#lb_holder';
BaseAjax._xArgs.callBack = _xLightboxes.openUIajaxCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
},

openUIajaxCallback:function(){
_xLightboxes._bUILoading = false;
$('#lb_holder' ).show()
_xLightboxes._bUIDisplayed = true
},

closeUI:function(){
$('#lb_holder' ).hide()
_xLightboxes._bUIDisplayed = false
},

registerClickFromUI:function(){
$('#lb_holder' ).hide()
_xLightboxes._bUIDisplayed = false
_xTruebox.makePopup('registerform', false);

},
signinFromUI:function(){
$("#lb_holder").find(".loginerrormsg").empty();

var l_sPassword = $('#lb_password').val();
var l_sUsername = $('#lb_username').val();

var l_bEmailValid = HungryLoginJS.prototype.validateEmail(l_sUsername);
var l_bPasswordValid = l_sPassword != null && l_sPassword.length > 0;

if (!l_bEmailValid) {
$("#lb_holder").find(".loginerrormsg").append("Please enter a valid email.<br />");
} 
if (!l_bPasswordValid) {
$("#lb_holder").find(".loginerrormsg").append("Please enter a valid password.<br />");
} 

if(l_bEmailValid && l_bPasswordValid){
if(_xLightboxes._bUILoading) return;
_xLightboxes._bUILoading = true;
loginJS.login(l_sUsername,l_sPassword,_xLightboxes.signinFromUICallback);
}
},

signinFromUICallback:function(p_xUser){
_xLightboxes._bUILoading = false;

if(p_xUser===false){
$("#lb_holder").find(".loginerrormsg").html("Invalid credentials. Please try again.");
$("#lb_password").val('');
return;
}else{
_xLightboxes.openUIAjax()
}

},


saveNewLightboxFromDropdown:function(){

var l_sName = $.trim($('#lightbox_name').val())
var l_sDesc = $.trim($('#lightbox_description').val())

if(!l_sName) return null;

BaseAjax._xArgs.data = "a=LightboxSaveNewFromDropdown";
BaseAjax._xArgs.data += "&lightbox_name="+escape(l_sName);
BaseAjax._xArgs.data += "&lightbox_desc="+escape(l_sDesc);

BaseAjax._xArgs.callBack = _xLightboxes.saveLightboxFromDropdownCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();


},

saveLightboxFromDropdownCallback:function(){
var l_nNewId = parseInt(BaseAjax.returnVar);
if(l_nNewId){
window.location = '/my/lightboxes/'+l_nNewId+'/';
}
},

saveLightboxFromUI:function(){

var l_nNewName = $.trim( $('#newlightboxname').val())
if(! l_nNewName  ) return;

if(_xLightboxes._bUILoading) return;
_xLightboxes._bUILoading = true;


BaseAjax._xArgs.data = "a=LightboxSaveFromUI";
BaseAjax._xArgs.data += "&asset_id="+_xLightboxes._nLastAsset;
BaseAjax._xArgs.data += "&lightbox_name="+escape(l_nNewName);
BaseAjax._xArgs.data += "&asset_title="+escape(_xLightboxes._sUIAssetTitle);
BaseAjax._xArgs.data += "&asset_desc="+escape(_xLightboxes._sUIAssetDesc);

BaseAjax._xArgs.callBack = _xLightboxes.saveLightboxFromUICallback;
BaseAjax._xArgs.returnDiv = '#lb_holder';
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

},
saveLightboxFromUICallback:function(){

_xLightboxes._bUILoading = false;

},
changeSelectArea:function(p_xThis,p_bIsThumbnail){
var l_nNewId = $(p_xThis).val();
window.location = '/my/lightboxes/'+l_nNewId+'/thumbnails/';
},

makeThisLightboxPublic:function(){

BaseAjax._xArgs.data = "a=LightboxMakePublicPrivate";
BaseAjax._xArgs.data += "&id="+_xLightboxes._nThisLightbox;
BaseAjax._xArgs.data += "&makepublic=1";
BaseAjax._xArgs.callBack = _xLightboxes.makeThisLightboxPublicCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

},
makeThisLightboxPublicCallback:function(){
$('#lb_public').hide();
$('#lb_private').show();
},

makeThisLightboxPrivate:function(){

BaseAjax._xArgs.data = "a=LightboxMakePublicPrivate";
BaseAjax._xArgs.data += "&id="+_xLightboxes._nThisLightbox;
BaseAjax._xArgs.data += "&makepublic=0";
BaseAjax._xArgs.callBack = _xLightboxes.makeThisLightboxPrivateCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
},
makeThisLightboxPrivateCallback:function(){
$('#lb_public').show();
$('#lb_private').hide();
},

editThisLightbox:function(){
$('#lightbox_select_area').hide();
$('#lightbox_edit_area').show();

},

deleteThisLightbox:function(){

if( confirm('Are you sure you want to delete this Lightbox?') ){

BaseAjax._xArgs.data = "a=LightboxDelete";
BaseAjax._xArgs.data += "&id="+_xLightboxes._nThisLightbox;

BaseAjax._xArgs.callBack = _xLightboxes.deleteThisLightboxCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
}
},

deleteThisLightboxCallback:function(){
window.location = '/my/lightboxes/';
},

saveLightboxEditFields:function(){

var l_sName = $.trim($('#lightbox_edit_name').val())
var l_sDesc = $.trim($('#lightbox_edit_description').val())


BaseAjax._xArgs.data = "a=LightboxSaveFromEdit";
BaseAjax._xArgs.data += "&lightbox_name="+escape(l_sName);
BaseAjax._xArgs.data += "&lightbox_desc="+escape(l_sDesc);
BaseAjax._xArgs.data += "&id="+_xLightboxes._nThisLightbox;

BaseAjax._xArgs.callBack = _xLightboxes.saveLightboxEditFieldsCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

},
saveLightboxEditFieldsCallback:function(){
window.location = '/my/lightboxes/'+_xLightboxes._nThisLightbox+'/';
},

clickLightboxInOther:function(p_nLightboxId, p_xThis){
if(_xLightboxes._bUILoading) return;
if( $(p_xThis).hasClass('processing') ) return;

$(p_xThis).addClass('processing')
$(p_xThis).toggleClass('lightboxrow_checked');

var l_bAddingAsset = ($(p_xThis).hasClass('lightboxrow_checked'))?'1':'0';

BaseAjax._xArgs.data = "a=LightboxClickRowInUI";
BaseAjax._xArgs.data += "&asset_id="+_xLightboxes._nCurrentDetailAsset;
BaseAjax._xArgs.data += "&lightbox_id="+p_nLightboxId;
BaseAjax._xArgs.data += "&adding_asset="+l_bAddingAsset;

//BaseAjax._xArgs.callBack = function(){_xLightboxes.clickLightboxInUICallback(p_xThis) };
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
},
clickLightboxInUI:function(p_nLightboxId, p_xThis){
if(_xLightboxes._bUILoading) return;
if( $(p_xThis).hasClass('processing') ) return;

$(p_xThis).siblings('.saving').show();
$(p_xThis).siblings('.saved').hide();

$(p_xThis).addClass('processing')
$(p_xThis).toggleClass('lightboxrow_checked');

var l_bAddingAsset = ($(p_xThis).hasClass('lightboxrow_checked'))?'1':'0';

BaseAjax._xArgs.data = "a=LightboxClickRowInUI";
BaseAjax._xArgs.data += "&asset_id="+_xLightboxes._nLastAsset;
BaseAjax._xArgs.data += "&lightbox_id="+p_nLightboxId;
BaseAjax._xArgs.data += "&adding_asset="+l_bAddingAsset;
BaseAjax._xArgs.data += "&asset_title="+escape(_xLightboxes._sUIAssetTitle);
BaseAjax._xArgs.data += "&asset_desc="+escape(_xLightboxes._sUIAssetDesc);

BaseAjax._xArgs.callBack = function(){_xLightboxes.clickLightboxInUICallback(p_xThis) };
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

},
clickLightboxInUICallback:function(p_xThis){
$(p_xThis).siblings('.saving').hide();
$(p_xThis).siblings('.saved').show();
$(p_xThis).removeClass('processing')
setTimeout(function(){$(p_xThis).siblings('.saved').fadeOut(1000);},500);
},



removeThisThumbnailImage:function(p_xThis){

if(confirm('Delete this Image?')){

$(p_xThis).parents('li').remove();
}
},

removeThisThumbnailImageCallback:function(p_nAssetId){

window.location.reload();

},


removeThisDetailImage:function(p_nAssetId,p_bEverywhere){

if(confirm('Delete this Image?')){

BaseAjax._xArgs.data = "a=LightboxRemoveImageFromDetail";
BaseAjax._xArgs.data += "&asset_id="+p_nAssetId;
BaseAjax._xArgs.data += "&lightbox_id="+_xLightboxes._nThisLightbox ;
BaseAjax._xArgs.data += "&removing_everywhere="+p_bEverywhere;

BaseAjax._xArgs.callBack = _xLightboxes.removeThisDetailImageCallback;
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
}
},

removeThisDetailImageCallback:function(){
var l_sLocation = '/my/lightboxes/'+_xLightboxes._nThisLightbox+'/';
window.location= l_sLocation;

},

switchDetailView:function(p_nAssetId){

BaseAjax._xArgs.data = "a=LightboxSwitchDetailAsset";
BaseAjax._xArgs.data += "&asset_id="+p_nAssetId;
BaseAjax._xArgs.data += "&lightbox_id="+_xLightboxes._nThisLightbox ;
BaseAjax._xArgs.data += "&total="+_xLightboxes._nThisLightboxTotal;

BaseAjax._xArgs.returnDiv = "#lightbox_detail_image_view"; 
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
},


paginateSelfLightboxes:function(p_nPage){

BaseAjax._xArgs.data = "a=LightboxPaginateSelfModule";
BaseAjax._xArgs.data += "&page="+p_nPage;
BaseAjax._xArgs.returnDiv = "#user_lightboxes_module";
BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
}



}


_xArticles={

updateCultureBrowserCategory:function(p_nCategoryId){

_xArticles._nCurrentCategory = p_nCategoryId
_xArticles.paginateCultureBrowserCategory(1);

},
paginateCultureBrowserCategory:function(p_nPage){
var l_nCurrentCategory = _xArticles._nCurrentCategory

BaseAjax._xArgs.data = 'a=UpdateCultureBrowser';
if(parseInt(l_nCurrentCategory))
BaseAjax._xArgs.data += '&category='+l_nCurrentCategory;
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#culture_browser';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

}


}


_xGuides={
_nCurrentCategory:0,

updateGuidesBrowserCategory:function(p_nCategoryId){

_xGuides._nCurrentCategory = p_nCategoryId
_xGuides.paginateGuidesBrowser(1);

},
paginateGuidesBrowser:function(p_nPage){
var l_nCurrentCategory = _xGuides._nCurrentCategory

BaseAjax._xArgs.data = 'a=UpdateGuidesBrowser';
if(parseInt(l_nCurrentCategory))
BaseAjax._xArgs.data += '&category='+l_nCurrentCategory;
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#guides_browser';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

}


}


$(document).ready(function(){
_xComments.init();

});


_xComments = {

_bAreCommentsDisplayed : 0,
_nTopComment : 0,
_nItemId : 0,
_nListId : 0,
_sSortOn : '',
_nCurrentReplyId :0,
_bSendingPost :false,
_bRepliesShown:false,
_xUser:null,

init:function(){
if($('#comment_login').length){


_xComments.calcTreeReplies('#topcomment');

}
},

/*************
* 
* Login Stuff
*
*************/

tryLogin:function(){

var l_sPassword = $('#comment_password').val();
var l_sUsername = $('#comment_username').val();

loginJS.login(l_sUsername,l_sPassword,_xComments.tryLoginCallback);

},

tryLoginCallback:function(p_xUser){

if(p_xUser===false){
alert('Incorrect credentials!');
$('#comment_password').val('')
}else{
$('#comment_password').val('')
$('#comment_username').val('');
}

},


logUserIn:function(p_xUser){
$('#comment_login').find('.login_holder').hide();
$('#comment_post').show();
},

logUserOut:function(){
$('#comment_login').find('.login_holder').show();
$('#comment_post').hide();
},



/*************
* 
* Comment Stuff
*
*************/

showTreeReplies:function(p_xThis){
$(p_xThis).parent().siblings('.replies').show();
$(p_xThis).hide();
$(p_xThis).siblings('.comment_button_hidereplies').show();
},

hideTreeReplies:function(p_xThis){
$(p_xThis).parent().siblings('.replies').hide();
$(p_xThis).hide();
$(p_xThis).siblings('.comment_button_showreplies').show();
},


calcTreeReplies:function(p_sWhere){
$(p_sWhere).find('.replies').each(function(){
var l_nTotal = $(this).find('.comment').length
$(this).siblings('.comment_links').find('.replycount').html(l_nTotal)
});
},


setSort:function(p_sSort,p_xThis){
_xComments._sSortOn = p_sSort;
_xComments.paginateDiscussionPage(1)
$(p_xThis).siblings('a').removeClass('current');
$(p_xThis).addClass('current');
},

hideAllDiscussions:function(){
$('#comment_holder').hide()
$('#comment_control').find('.showdiscussions').show();
$('#comment_control').find('.hidediscussions').hide();
$('#comment_control').find('.rightlinks').hide();

$('#comment_control').find('.border').hide();
$('#comment_control').find('.showreplies,.hidereplies').hide();

},

showAllDiscussions:function(){
if(_xComments._bAreCommentsDisplayed){
$('#comment_holder').show();
$('#comment_control').find('.showdiscussions').hide();
$('#comment_control').find('.hidediscussions').show();
$('#comment_control').find('.rightlinks').show();
$('#comment_control').find('.border').show();
if(!_xComments._bRepliesShown)
$('#comment_control').find('.showreplies').show();
else
$('#comment_control').find('.hidereplies').show();

}else{
_xComments._bAreCommentsDisplayed= true
_xComments.paginateDiscussionPage(1);
}
},

showReplies:function(){
$('#comment_control').find('.hidereplies').show()
$('#comment_control').find('.showreplies').hide()
_xComments._bRepliesShown = true
$('#comment_holder').find('.comment_button_showreplies').each(function(){
_xComments.showTreeReplies(this);

})
},
hideReplies:function(){
$('#comment_control').find('.hidereplies').hide()
$('#comment_control').find('.showreplies').show()
_xComments._bRepliesShown = false
$('#comment_holder').find('.comment_button_hidereplies').each(function(){
_xComments.hideTreeReplies(this);

})
},

paginateDiscussionPage:function(p_nPage){

BaseAjax._xArgs.data = 'a=ShowAllDiscussions';

BaseAjax._xArgs.data += '&in_list='+_xComments._nListId;
BaseAjax._xArgs.data += '&in_item='+_xComments._nItemId;

BaseAjax._xArgs.data += '&exclude_id='+_xComments._nTopComment;
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&sort_on='+_xComments._sSortOn;
BaseAjax._xArgs.returnDiv = '#comment_holder';
BaseAjax._xArgs.callBack = _xComments.paginateDiscussionPageCallback;
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

},

paginateDiscussionPageCallback:function(){
$('#comment_control').find('.showdiscussions').hide();
$('#comment_control').find('.hidediscussions').show();
$('#comment_control').find('.border').show();
$('#comment_control').find('.rightlinks').show();
_xComments.calcTreeReplies('#comment_holder');
if(_xComments._bRepliesShown){
$('#comment_holder').find('.comment_button_showreplies').each(function(){
_xComments.showTreeReplies(this);
$('#comment_control').find('.hidereplies').show();
})
}else{
$('#comment_control').find('.showreplies').show();
}
},

sendCommentRoot:function(){
loginJS.isLoggedIn(_xComments.sendCommentRootBody);
},

sendCommentRootBody:function(p_xUser){
if(!p_xUser) return;
if(_xComments._bSendingPost) return false
_xComments._bSendingPost = true

$target = $('#comment_post').find('textarea');

var l_xText = escape($.trim( $target.val()  ))
if(l_xText.length){

BaseAjax._xArgs.data = 'a=PostComment';
BaseAjax._xArgs.data += '&text='+l_xText;
BaseAjax._xArgs.data += '&in_list='+_xComments._nListId;
BaseAjax._xArgs.data += '&in_item='+_xComments._nItemId;
BaseAjax._xArgs.data += '&in_reply_to=0';
BaseAjax._xArgs.data += '&tier=1';
BaseAjax._xArgs.callBack = function(){_xComments.sendCommentRootCallback(_xComments._nCurrentReplyId)};

BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();
}
},

sendCommentRootCallback:function(){

if(parseInt(BaseAjax.returnVar)==0){
alert('Login Credentials Incorrect');
return
}
var l_sHtml = '<div class="responsetext">Your comment has been posted. Please allow 5-10 minutes to be seen.</div>';
$('#comment_post').html(l_sHtml)
_xComments._bSendingPost = false
_xComments._nCurrentReplyId = 0

},

sendCommentVote:function(p_nId){
// TODO Check if they are logged in
BaseAjax._xArgs.data = 'a=VoteComment';
BaseAjax._xArgs.data += '&id='+p_nId;
BaseAjax._xArgs.requestType = "POST"; 
BaseAjax._xArgs.callBack = _xComments.sendCommentVoteCallback; 
BaseAjax.makeAjaxCall();

},
sendCommentReport:function(p_nId){

BaseAjax._xArgs.data = 'a=ReportComment';
BaseAjax._xArgs.data += '&id='+p_nId;
BaseAjax._xArgs.requestType = "POST"; 
BaseAjax.makeAjaxCall();

},


sendCommentVoteCallback:function(){
if(parseInt(BaseAjax.returnVar)==0){
alert('Login Credentials Incorrect');
return
}

},


sendCommentReply:function(){
loginJS.isLoggedIn(_xComments.sendCommentReplyBody);
},

sendCommentReplyBody:function(p_xUser){
if(!p_xUser) return;

if(_xComments._bSendingPost) return false
_xComments._bSendingPost = true
$target = $('#comment_'+_xComments._nCurrentReplyId).find('textarea');

if( $('#comment_'+_xComments._nCurrentReplyId ).hasClass('comment_t1'))
var l_nTier = 2
else
var l_nTier = 3

var l_xText = escape($.trim( $target.val()  ))
if(l_xText.length){

BaseAjax._xArgs.data = 'a=PostComment';
BaseAjax._xArgs.data += '&text='+l_xText;
BaseAjax._xArgs.data += '&in_list='+_xComments._nListId;
BaseAjax._xArgs.data += '&in_item='+_xComments._nItemId;
BaseAjax._xArgs.data += '&in_reply_to='+_xComments._nCurrentReplyId;
BaseAjax._xArgs.data += '&tier='+l_nTier;
BaseAjax._xArgs.callBack = function(){_xComments.sendCommentReplyCallback(_xComments._nCurrentReplyId)};

BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

}
},

sendCommentReplyCallback:function(p_nId){
$target = $('#comment_'+p_nId).find('.comment_reply_holder');
if(BaseAjax.returnVar==0){
alert('Login Credentials Incorrect');
return
}
var l_sHtml = '<div class="responsetext">Your comment has been posted. Please allow 5-10 minutes to be seen.</div>';
$target.html(l_sHtml)
_xComments._bSendingPost = false
_xComments._nCurrentReplyId = 0
},

createCommentReply:function(p_nId){
if(_xComments._bSendingPost) return false
if(_xComments._nCurrentReplyId == p_nId) return false

_xComments._nCurrentReplyId = p_nId

$('#comment_holder,#topcommentholder').find('.comment_reply_holder').empty();

$target = $('#comment_'+p_nId).find('.comment_reply_holder').eq(0);

var l_sHtml = '<textarea></textarea>'+
'<div class="endlink"><table><tr><td>&raquo;</td><td><a href="javascript:;" onclick="_xComments.sendCommentReply()">POST</a></td><td>&laquo;</td></tr></table></div>'

$target.show().html(l_sHtml);
}

}

_xTopics = {

_nTopicId:0,

paginateVideos:function(p_nPage){

var l_nTag = $('#topics_video_module').attr('rel');

BaseAjax._xArgs.data = 'a=TopicsPaginateVideo';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&has_tag='+l_nTag;

BaseAjax._xArgs.returnDiv = '#topics_video_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},

paginateArchiveTopics:function(p_nPage){

var l_nTag = $('#topics_archive_module').attr('rel');
var l_sTitle = $('#topics_archive_module').attr('rev');

BaseAjax._xArgs.data = 'a=TopicsPaginateArchiveTopics';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&has_tag='+l_nTag;
BaseAjax._xArgs.data += '&exclude='+_xTopics._nTopicId;
BaseAjax._xArgs.data += '&title='+l_sTitle;

BaseAjax._xArgs.returnDiv = '#topics_archive_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

},

paginateCollections:function(p_nPage){

var l_nTag = $('#topics_collection_module').attr('rel');
BaseAjax._xArgs.data = 'a=TopicsPaginateCollections';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&with_designer_id='+l_nTag;

BaseAjax._xArgs.returnDiv = '#topics_collection_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
}





}


_xVideos = {

_nCurrentCategory:0,

paginateBrowser:function(p_nPage, p_xThis){

BaseAjax._xArgs.data = 'a=VideosUpdateBrowser';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&category='+_xVideos._nCurrentCategory;

BaseAjax._xArgs.returnDiv = '#video_browser_inner';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

               $.scrollTo('.heading-video-browser', 0, {offset:-100});

},
updateCategory:function(p_nCategory){
_xVideos._nCurrentCategory = p_nCategory

_xVideos.paginateBrowser(1);

}


}

$(document).ready(function(){
_xCarousel.fixTwoItemCarousels();
});


_xCarousel = {

getNext:function(p_sDomPrefix, p_nSlideAmount){
var $image_holder = $('#'+p_sDomPrefix+'_image_holder');
var l_nImageCount = $image_holder.find('img').length;

if(l_nImageCount > 1){
var $first = $image_holder.find('.carousel_item:first');
var $last = $image_holder.find('.carousel_item:last');
var $selected = $image_holder.find('.selected');
var $next = $image_holder.find('.next');
var $prev = $image_holder.find('.prev');

if($next[0] == $last[0]){
var $nextnext = $first;
}
else{
var $nextnext = $next.next();
}

$selected.animate( { 'left': -p_nSlideAmount }, 200, function(){ $selected.attr('style', ''); }).attr('class', 'carousel_item prev');
$next.animate( { 'left': '0' }, 200, function(){ $selected.attr('style', ''); }).attr('class', 'carousel_item selected');
$prev.attr('class', 'carousel_item');
$nextnext.attr('class', 'carousel_item next');
_xMain.callOmniture();

this.getNextInfo(p_sDomPrefix);
}
},

getNextInfo:function(p_sDomPrefix){
var $info_holder = $('#'+p_sDomPrefix+'_info_holder');

var $first = $info_holder.find('.carousel_info:first');
var $last = $info_holder.find('.carousel_info:last');
var $selected = $info_holder.find('.selected');
var $next = $info_holder.find('.next');
var $prev = $info_holder.find('.prev');

if($next[0] == $last[0]){
var $nextnext = $first;
}
else{
var $nextnext = $next.next();
}

$selected.attr('class', 'carousel_info prev');
$next.attr('class', 'carousel_info selected');
$prev.attr('class', 'carousel_info');
$nextnext.attr('class', 'carousel_info next');

},

getPrev:function(p_sDomPrefix, p_nSlideAmount){
var $image_holder = $('#'+p_sDomPrefix+'_image_holder');
var l_nImageCount = $image_holder.find('img').length;

if(l_nImageCount > 1){
var $first = $image_holder.find('.carousel_item:first');
var $last = $image_holder.find('.carousel_item:last');
var $selected = $image_holder.find('.selected');
var $next = $image_holder.find('.next');
var $prev = $image_holder.find('.prev');

if($prev[0] == $first[0]){
var $prevprev = $last;
}
else{
var $prevprev = $prev.prev();
}

$selected.animate( { 'left': p_nSlideAmount }, 200, function(){ $selected.attr('style', ''); }).attr('class', 'carousel_item next');
$prev.animate( { 'left': '0' }, 200, function(){ $selected.attr('style', ''); }).attr('class', 'carousel_item selected');
$next.attr('class', 'carousel_item');
$prevprev.attr('class', 'carousel_item prev');
_xMain.callOmniture();
this.getPrevInfo(p_sDomPrefix);
}
},

getPrevInfo:function(p_sDomPrefix){
var $info_holder = $('#'+p_sDomPrefix+'_info_holder');

var $first = $info_holder.find('.carousel_info:first');
var $last = $info_holder.find('.carousel_info:last');
var $selected = $info_holder.find('.selected');
var $next = $info_holder.find('.next');
var $prev = $info_holder.find('.prev');

if($prev[0] == $first[0]){
var $prevprev = $last;
}
else{
var $prevprev = $prev.prev();
}

$selected.attr('class', 'carousel_info next');
$next.attr('class', 'carousel_info');
$prev.attr('class', 'carousel_info selected');
$prevprev.attr('class', 'carousel_info prev');

},

fixTwoItemCarousels:function(){
$('.carousel_image_holder').each(function(){
var l_sId = $(this).attr('id');
var $image_holder = $('#'+l_sId);
var l_nImageCount = $image_holder.find('img').length;

if(l_nImageCount==2){
var l_sDomPrefix = l_sId.replace('_image_holder', '');
var $info_holder = $('#'+l_sDomPrefix+'_info_holder');

var $selected = $image_holder.find('.selected');
var $next = $image_holder.find('.next');
var $prev = $image_holder.find('.prev');
var $last = $image_holder.find('.carousel_item:last');
var $selectedinfo = $info_holder.find('.carousel_info:first');
var $nextinfo = $info_holder.find('.carousel_info:last');

$next.clone().attr('class', 'carousel_item prev').insertAfter($last);
$selected.clone().attr('class', 'carousel_item').insertAfter($last);

$selectedinfo.clone().attr('class', 'carousel_info').appendTo($info_holder);
$nextinfo.clone().attr('class', 'carousel_info prev').appendTo($info_holder);
}
});
}
}

$(document).ready(function(){
if(_xBestDressed._nCurrentList )
_xBestDressed.init();
});

_xBestDressed = {
_nCurrentVoteImage: 1, 
_nCurrentList:0,

init:function(){
_xBestDressed.setClicks();
_xBestDressed.setHovers();
_xBestDressed.checkCookieForVote();
},


checkCookieForVote:function(){
var l_sCookie = 'votebestdressed_'+_xBestDressed._nCurrentList
if (! $.cookie(l_sCookie) )
$('#vote_look').show();

},


setHovers:function(){
$('#subpage_main').find('.vote_look').hover(function(){
$(this).addClass('vote_look_hover');
},function(){
$(this).removeClass('vote_look_hover');
});
},

setClicks:function(){
$('#subpage_main').find('.subpage_gallery_right').find('.thumbnail').click(function(){
$(this).addClass('selected').siblings('.thumbnail').removeClass('selected');
var l_nId = $(this).attr('data-number');
_xBestDressed.changeSubpageGalleryImage(l_nId);
_xBestDressed._nCurrentVoteImage = l_nId;
                        _xMain.callOmniture(l_nId);
                        

});

},

        

changeSubpageGalleryImage:function(p_nId){
$('#subpage_main').find('.subpage_gallery_image').children('img[data-number='+p_nId+']').show().siblings('img').hide();
$('#subpage_main').find('.subpage_gallery_right').children('.info[data-number='+p_nId+']').show().siblings('.info').hide();
$('#subpage_main').find('.subpage_gallery_image').children('.credit[data-number='+p_nId+']').show().siblings('.credit').hide();
//$('#subpage_main').find('.subpage_gallery_number').attr('class', 'subpage_gallery_number').addClass('sgn'+p_nId);
},

voteForLook:function(){

var l_nItemId = $('#subpage_main').find('.info[data-number='+_xBestDressed._nCurrentVoteImage+']').attr('rel');
$('#vote_look').hide();

BaseAjax._xArgs.data = 'a=TenBestDressedVote';
BaseAjax._xArgs.data += '&item_id='+l_nItemId;
BaseAjax._xArgs.data += '&list_id='+_xBestDressed._nCurrentList;
BaseAjax._xArgs.returnDiv = '#subpage_gallery_vote_overlay';
BaseAjax._xArgs.callBack = _xBestDressed.loadVoteResultsCallback;
BaseAjax._xArgs.requestType = "POST"; 
BaseAjax.makeAjaxCall();

},

loadVoteResults:function(){
BaseAjax._xArgs.data = 'a=TenBestDressedResult';
BaseAjax._xArgs.data += '&list_id='+_xBestDressed._nCurrentList;
BaseAjax._xArgs.returnDiv = '#subpage_gallery_vote_overlay';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax._xArgs.callBack = _xBestDressed.loadVoteResultsCallback;
BaseAjax.makeAjaxCall();
},
loadVoteResultsCallback:function(){
$('#subpage_gallery_vote_overlay').fadeIn('fast');
_xBestDressed.addYourVoteTag()
},

closeVoteOverlay:function(){
$('#subpage_gallery_vote_overlay').hide();
},

addYourVoteTag:function(){
var l_sCookie = 'votebestdressed_'+_xBestDressed._nCurrentList
if($.cookie(l_sCookie)){
$target = $('#entry_'+ $.cookie(l_sCookie) )

$target.addClass('voted_for')

var l_nCount = parseInt($target.find('span').html())
$target.find('span').html(l_nCount+1)
}

}


}

_xFashion = {
_nBrowserModuleType:0,
switchBrowserModule:function(p_nId){

BaseAjax._xArgs.data = 'a=UpdateFashionBrowser';
BaseAjax._xArgs.data += '&page=1';
BaseAjax._xArgs.data += '&moduletype='+p_nId;

BaseAjax._xArgs.returnDiv = '#fashion_browser';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},
paginateBrowserModule:function(p_nPage){

BaseAjax._xArgs.data = 'a=UpdateFashionBrowser';
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&moduletype='+_xFashion._nBrowserModuleType;

BaseAjax._xArgs.returnDiv = '#fashion_browser';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
}
}


$(document).ready(function(){
_xCollections.init();
});

_xCollections={
_sCurrentBrowserSection: 'season',

init:function(){
if(_xCollections._bHasCollectionBucket)
_xCollections.setBucketCarouselClicks();
if(_xCollections._bHasCollectionCarousel)
_xCollections.setCollectionResizes();
},

/*********************
*
* Pagination
*
**********************/

paginateHistory:function(p_nPage){
BaseAjax._xArgs.data = 'a=GetCollectionPaginateHistory';
BaseAjax._xArgs.data += '&with_designer_slug='+_xCollections._sDesignerSlug;
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#collections_history_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},

paginateDetailsPage:function(p_nPage){
_xMain.callOmniture(p_nPage, 'page')
BaseAjax._xArgs.data = 'a=GetCollectionDetailsInner';
BaseAjax._xArgs.data += '&id='+_xCollections._nExternalId;
BaseAjax._xArgs.data += '&designerslug='+_xCollections._sDesignerSlug
BaseAjax._xArgs.data += '&seasonslug='+_xCollections._sSeasonSlug
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#details_main';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},


paginateCandidsPage:function(p_nPage){
_xMain.callOmniture(p_nPage, 'page')
BaseAjax._xArgs.data = 'a=GetCollectionCandidsInner';
BaseAjax._xArgs.data += '&id='+_xCollections._nExternalId;
BaseAjax._xArgs.data += '&designerslug='+_xCollections._sDesignerSlug
BaseAjax._xArgs.data += '&seasonslug='+_xCollections._sSeasonSlug
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#candids_main';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},


paginateRunwayPage:function(p_nPage){

                _xMain.callOmniture(p_nPage, 'page')
BaseAjax._xArgs.data = 'a=GetCollectionRunwayInner';
BaseAjax._xArgs.data += '&id='+_xCollections._nExternalId;
BaseAjax._xArgs.data += '&designerslug='+_xCollections._sDesignerSlug
BaseAjax._xArgs.data += '&seasonslug='+_xCollections._sSeasonSlug
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#runway_main';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

                
},






/**********************
*
*Carousel Ad Stuff
*
**********************/

_bHasAd:false,
_xAdPollInterval : false,
_nAdPollTime:500,
_nAdWidth:0,
_nAdPosition : 0,
_nPollCount:0,


pollForAd:function(){ 
var l_xPollReturn = _xCollections.pollForAdReal('collections_ad_holder');
if(l_xPollReturn){
clearInterval(_xCollections._xAdPollInterval);
_xCollections._nAdWidth = parseInt(l_xPollReturn._sWidth);
_xCollections.prepAdForCarousel()
// if 1 second of polling pass, give it up for lost
} else if(_xCollections._nPollCount++==3){
clearInterval(_xCollections._xAdPollInterval);
_xCollections._nAdWidth = 0;
_xCollections.prepAdForCarousel()
}
},

pollForAdReal:function(p_sDivId){
var $ad_holder = $('#'+p_sDivId);

var $l_axNoScripts = $ad_holder.find('noscript');
var $l_axAnchorTags = $ad_holder.find('a');

var $l_xReturn = {};
var l_bReturn = false;

if($l_axNoScripts.length>1){
var $l_xNoScript;
$l_axNoScripts.each(function(){
if(!$(this).hasClass('original_noscript')){
$l_xNoScript = $(this);
}
});


var $l_axObjects = $ad_holder.find('object');
var $l_axEmbeds = $ad_holder.find('embed');

if($l_axObjects.length){
$l_xReturn._sWidth = $l_axObjects.attr('width');
}
else if($l_axEmbeds.length){
$l_xReturn._sWidth = $l_axEmbeds.attr('width');
}
return $l_xReturn;
}
else if($l_axAnchorTags.length){
$l_xReturn._sImg =  $l_axAnchorTags.eq(0).html();
$l_xReturn._sWidth =  $l_axAnchorTags.find('img').attr('width');
return $l_xReturn;
}

return false;
},

prepAdForCarousel:function(){
//console.log(_xParties._sAdBackupImage);
if(_xCollections._nAdWidth > 1){
_xCollections._bHasAd = true;
if(_xCollections._nAdWidth==300){
$('#cf_images_shifter').find('.ad_entry').addClass('small_ad_holder');
}else{
$('#cf_images_shifter').find('.ad_entry').addClass('big_ad_holder');
}

$('#cf_images_shifter').find('.ad_entry').width(_xCollections._nAdWidth);

}else{
$('#cf_images_shifter').find('.ad_entry').hide();
}
_xCollections.snapToCorrectCollectionSlide()
$('#parties_block_overlay').fadeOut(200);

},

/*********************
*
* Carousel
*
**********************/

_nCurrentCarouselSlide:0,
_bIsCollectionCarouselAnimating:false,
_bIsPreview:false,

setCollectionResizes:function(){
$(window).resize(function(e){
_xCollections.snapToCorrectCollectionSlide()
});
_xCollections.pollForAd();
},

jumpToNextCollectionSlide:function(){
_xCollections.jumpToCollectionCarousel(1);
},
jumpToPrevCollectionSlide:function(){
_xCollections.jumpToCollectionCarousel(-1);
},


jumpToCollectionCarousel:function(p_nTarget){
        if(!_xCollections._bIsCollectionCarouselAnimating){
_xCollections._bIsCollectionCarouselAnimating = true

$current = $('#cf_images_shifter').find('.homebase[data-number='+_xCollections._nCurrentCarouselSlide+']')
var l_nRealTarget = parseInt(p_nTarget+ parseInt($current.attr('rel')) )


//console.log(p_nTarget);
//console.log(_xCollections._nCurrentCarouselSlide);
//console.log(_xCollections._nAdPosition);
//console.log(l_nRealTarget);
if(!_xCollections._bHasAd){
if( p_nTarget > 0 && _xCollections._nCurrentCarouselSlide+1 == _xCollections._nAdPosition  ){
l_nRealTarget++;
}
if( p_nTarget < 0 && (_xCollections._nCurrentCarouselSlide-1 == _xCollections._nAdPosition || _xCollections._nCurrentCarouselSlide == 0) ){ 
l_nRealTarget--;
}
}
//console.log(l_nRealTarget);

var $target = $('#cf_images_shifter').find('.entry[rel='+l_nRealTarget+']')

if($target.hasClass('ad_entry') ){
$('#cf_top_infobar_inner').find('.count').css('visibility','hidden');
}else{
$('#cf_top_infobar_inner').find('.count').css('visibility','visible');
}


var l_nTargetDataNumber = parseInt($target.attr('data-number'));

var l_aPosition = $current.position();
var l_nOldLeftOffset = l_aPosition.left
l_aPosition = $target.position();
var l_nLeftOffset = l_aPosition.left

var l_nOffsetDifference = l_nLeftOffset-l_nOldLeftOffset

$('#cf_images_shifter').animate({left:'-='+ l_nOffsetDifference},_xCollections._nBucketCarouselSpeed,function(){ 

_xCollections.jumpToCollectionCarouselCallback(l_nTargetDataNumber)
})
_xMain.callOmniture(l_nTargetDataNumber, 'collectionscarousel')
_xCollections.checkForAd($target);


if(_xCollections._bIsPreview)
$('#cf_images_shifter').find('.entry[data-number='+l_nTargetDataNumber+']').find('.txt_holder').hide();
}
},

jumpToCollectionCarouselCallback:function(p_nTargetNumber){
_xCollections._bIsCollectionCarouselAnimating = false
_xCollections._nCurrentCarouselSlide = p_nTargetNumber
_xCollections.snapToCorrectCollectionSlide()
if(_xCollections._bHasCollectionBucket)
$('#cf_top_infobar').find('.count span').html(p_nTargetNumber+1- ((p_nTargetNumber+1 > _xCollections._nAdPosition)?1:0))
else{
$('#cf_top_infobar_inner').find('.rotating_sidebar').hide()
$('#cf_top_infobar_inner').find('.rotating_sidebar[data-number='+p_nTargetNumber+']').fadeIn(200)
}

},

snapToCorrectCollectionSlide:function(){

var l_aOffset = $('#cf_top_infobar_inner').offset();
var l_nRealOffset = l_aOffset.left + $('#cf_top_infobar_inner').outerWidth();

var $target = $('#cf_images_shifter').find('.entry.homebase[data-number='+_xCollections._nCurrentCarouselSlide+']')

var l_aPosition = $target.position();
var l_nLeft = parseInt(l_aPosition.left - l_nRealOffset)

if(_xCollections._bIsPreview ){
$('#cf_images_shifter').find('.entry').find('.txt_holder').show(); 
$('#cf_images_shifter').find('.entry[data-number='+_xCollections._nCurrentCarouselSlide+']').find('.txt_holder').hide(); 
}

try {$('#cf_images_shifter').css('left','-'+l_nLeft+'px')} catch(e){};
},

checkForAd:function($selected_item){
if($selected_item.hasClass('ad_entry')){
var $ad_container;
$('.homebase').each(function(){
if($(this).hasClass('ad_entry')){ $ad_container = $(this); } 
});
setTimeout(function(){
var l_xPosition = $ad_container.offset();
$('#collections_carousel_ad').css({'top': l_xPosition.top+113, 'left': l_xPosition.left+20}).show();
}, _xCollections._nBucketCarouselSpeed);
}
else{ $('#collections_carousel_ad').hide(); }
},



/*********************
*
* Bucket Stuff
*
**********************/

_nBucketCarouselSpeed:400,
_nCurrentBucketCarouselTarget:0,
_bIsBucketCarouselAnimating:false,

setBucketCarouselClicks:function(){

$(".bracket_arrow").mouseover(function(){$(this).children('a').addClass('hoverstate')});
$(".bracket_arrow").mouseout(function(){$(this).children('a').removeClass('hoverstate')});
_xCollections._nCurrentBucketCarouselTarget=$('#cf_collections_shifter').find('.entry.homebase').eq(0).attr('rel');
$('#cf_collections_shifter').find('.entry').click(function(){
var l_nNewTarget = $(this).attr('rel');
_xCollections.jumpToBucketCarousel(l_nNewTarget)
});

},

jumpToNextBucketCarousel:function(){
_xCollections.jumpToBucketCarousel(parseInt(_xCollections._nCurrentBucketCarouselTarget)+1);
},
jumpToPrevBucketCarousel:function(){
_xCollections.jumpToBucketCarousel(parseInt(_xCollections._nCurrentBucketCarouselTarget)-1)
},

jumpToBucketCarousel:function(p_nNewTarget){
if(!_xCollections._bIsBucketCarouselAnimating){
            _xCollections._bIsBucketCarouselAnimating = true
_xCollections._bIsCollectionCarouselAnimating = true

//$current = $('#cf_collections_shifter').find('.entry[rel='+_xCollections._nCurrentBucketCarouselTarget+']')
var $target = $('#cf_collections_shifter').find('div.entry[rel='+p_nNewTarget+']')

var l_aPosition = $target.position();
var l_nLeftOffset = l_aPosition.left

$('#cf_collections_shifter').animate({left:-l_nLeftOffset},_xCollections._nBucketCarouselSpeed,function(){_xCollections.jumpToBucketCarouselCallback($target)})
}
},

jumpToBucketCarouselCallback:function($target){
if(!$target.hasClass('homebase')){
var l_nDataNumber = $target.attr('data-number');
$target = $('#cf_collections_shifter').find('.homebase[data-number='+l_nDataNumber+']')
var l_aPosition = $target.position();
var l_nLeftOffset = parseInt(l_aPosition.left)
$('#cf_collections_shifter').css('left','-'+l_nLeftOffset+'px')
}
_xCollections._nCurrentBucketCarouselTarget = $target.attr('rel')
var l_nNewCarousel = $target.attr('rev')

BaseAjax._xArgs.data = 'a=GetCollectionBucketDetail';
BaseAjax._xArgs.data += '&id='+l_nNewCarousel;
BaseAjax._xArgs.callBack = _xCollections.getCollectionBucketDetailCallback;
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();

$('#collections_carousel_ad').hide();

},

getCollectionBucketDetailCallback:function(){
_xCollections._bHasAd = false
eval('var l_aData = '+BaseAjax.returnVar);;
$('#cf_top_infobar_inner').html(l_aData[0])
$('#cf_images_shifter_holder').html(l_aData[1])
_xCollections._nCurrentCarouselSlide = 0;
_xCollections._bIsBucketCarouselAnimating = false
_xCollections._bIsCollectionCarouselAnimating = false
_xCollections.snapToCorrectCollectionSlide()

},



/*********************
*
* Browser Stuff
*
**********************/


openCollectionsBrowser:function(){
if(!$('#collections_browser').length)
$('body').append('<div id="collections_browser"></div>');

BaseAjax._xArgs.data = 'a=GetCollectionBrowserInit';
BaseAjax._xArgs.callBack = _xCollections.openCollectionsBrowserCallback;
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax._xArgs.returnDiv = '#collections_browser';
BaseAjax.makeAjaxCall();
},
openCollectionsBrowserCallback:function(){
$('#collections_browser').fadeIn(200, _xCollections.showBrowserAd);
$('#collections_browser').css('top',$(document).scrollTop()+50);
_xCollections.initJscrollPane('#designer_list_view .browser_list_view');
},

closeCollectionsBrowser:function(){
$('#collections_browser').fadeOut(200);
_xCollections.resetCollectionsBrowser();
},
resetCollectionsBrowser:function(){
$('#season_section').addClass('selected').siblings('.section').removeClass('selected');
$('#season_list_view').show().siblings().hide();
_xCollections._sCurrentBrowserSection = 'season';
$('#collections_browser_ad').hide();
},
initJscrollPane:function(l_sSelector){
setTimeout(function(){$(l_sSelector).jScrollPane({scrollbarWidth: 10, scrollbarMargin: 20, animateTo: false, showArrows: true});},100);
},
switchSection:function(l_sSection){
$('#'+l_sSection+'_section').addClass('selected').siblings('.section').removeClass('selected');
$('#'+l_sSection+'_list_view').show().siblings().hide();
_xCollections.initJscrollPane('#'+l_sSection+'_list_view .browser_list_view');
_xCollections._sCurrentBrowserSection = l_sSection;
},
openCollectionView:function(p_nType,p_nId){

BaseAjax._xArgs.data = 'a=GetCollectionBrowserDrilldown';
BaseAjax._xArgs.data += '&type='+p_nType;
BaseAjax._xArgs.data += '&id='+p_nId;
BaseAjax._xArgs.callBack = _xCollections.openCollectionViewCallback;
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax._xArgs.returnDiv = '#collection_view';
BaseAjax.makeAjaxCall();

},
openCollectionViewCallback:function(){
$('#collection_view').show().siblings().hide();
_xCollections.initJscrollPane('#collection_view_inner');
},
closeCollectionView:function(){
_xCollections.switchSection(_xCollections._sCurrentBrowserSection);
},
scrollToLetter:function(p_xDomElement, p_sSection){
var l_sLetter = $(p_xDomElement).text().toLowerCase();
if (l_sLetter == '#')   {l_sLetter = 'pound';}

switch(p_sSection) {
case 'designer':
var l_nScrollAmount = $('#designer_list_view').find('.anchor_'+l_sLetter).position().top;
$('#designer_list_view').find('.browser_list_view')[0].scrollTo(l_nScrollAmount);
break;

case 'collections':
var l_nScrollAmount = $('#collection_view_inner').find('.big_'+l_sLetter).position().top;
$('#collection_view_inner')[0].scrollTo(l_nScrollAmount);
break;
}
},

showBrowserAd:function(){
var l_xOffset = $('#collections_browser').offset();
$('#collections_browser_ad').css({'top': l_xOffset.top+360, 'left': l_xOffset.left+20 }).show();
}






}

_xPromotions = {

_nCurrentType:0,
_nCurrentSlot:1,
_nCurrentIndex:0,
_aAvailableTiers:null,

updatePromotionsBrowserType:function(p_nType){


_xPromotions._nCurrentType = p_nType
_xPromotions.paginatePromotionsBrowser(1);


},

paginatePromotionsBrowser:function(p_nPage){

BaseAjax._xArgs.data = 'a=PromotionsUpdateBrowser';

BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.data += '&type='+_xPromotions._nCurrentType;

BaseAjax._xArgs.returnDiv = '#promo_browser';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();


},

initPromotionsHeadData:function(p_aAvailableTiers){
if (p_aAvailableTiers == null) {p_aAvailableTiers = new Array(1,2,3)}
_xPromotions._aAvailableTiers = p_aAvailableTiers;
_xPromotions._nCurrentIndex = 0;
_xPromotions.getPromotionsHeadData();
},


getPromotionsHeadData:function(p_nUserIndex){
if (p_nUserIndex != null){_xPromotions._nCurrentIndex = p_nUserIndex}
_xPromotions._nCurrentSlot = _xPromotions._aAvailableTiers[_xPromotions._nCurrentIndex];
BaseAjax._xArgs.data = 'a=GetPromotionsHeadData';
BaseAjax._xArgs.data += '&featured_slot='+_xPromotions._nCurrentSlot;
BaseAjax._xArgs.returnDiv = '#promotions_main';
BaseAjax._xArgs.requestType = "GET";
BaseAjax._xArgs.callBack =function(){_xPromotions.getPromotionsHeadDataCallback();};
BaseAjax._xArgs.failureCallBack =function(){_xPromotions.getPromotionsHeadFailure();};
BaseAjax.makeAjaxCall();
},

getPromotionsHeadDataCallback:function(){
_xPromotions._nCurrentIndex++;
if (_xPromotions._nCurrentIndex >= _xPromotions._aAvailableTiers.length){_xPromotions._nCurrentIndex = 0}
//if there is only one avaible tier, don't call the function again!
if(_xPromotions._aAvailableTiers.length > 1) {
setTimeout(function(){_xPromotions.getPromotionsHeadData();},7000);
}
},


getPromotionsHeadFailure:function(){
//save the index of the failed slot before adjusting
var l_nRemoveIndex = _xPromotions._nCurrentIndex;
//get the next value before removing the current one!
_xPromotions.indexAdjustment();
var l_nextSlot = _xPromotions._aAvailableTiers[_xPromotions._nCurrentIndex];

//remove the failed slot
_xPromotions.removeFromArray(l_nRemoveIndex);

//use the nextSlot value to find the currentIndex
_xPromotions._nCurrentIndex = _xPromotions._aAvailableTiers.indexOf(l_nextSlot);

//show me the currentIndex!
_xPromotions.getPromotionsHeadData();

},

indexAdjustment:function(){
_xPromotions._nCurrentIndex++;
if (_xPromotions._nCurrentIndex >= _xPromotions._aAvailableTiers.length){_xPromotions._nCurrentIndex = 0}

},

removeFromArray:function(p_nIndexToRemove){
_xPromotions._aAvailableTiers.splice(p_nIndexToRemove, 1); // Remove it if really found!

}
















}

var HungryAccountJS = function () {
};


HungryAccountJS.prototype.save = function () {
// @TODO - validate
$("#account-form").submit();
};


HungryAccountJS.prototype.changePassword = function () {
var l_sOldPassword = $("#password_old").val();
var l_sNewPassword = $("#password").val();
var l_sNewPasswordConfirm= $("#password_confirm").val();

if (l_sNewPassword == null || l_sNewPassword.length < 6 || l_sNewPasswordConfirm == null || l_sNewPasswordConfirm.length < 6) {
alert('Passwords must be at least 6 characters');
return false;
}

if (l_sNewPassword != l_sNewPasswordConfirm) {
alert("Passwords do not match");
return false;
}

$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=ChangePassword&password_old='+ escape(l_sOldPassword) +'&password='+ escape(l_sNewPassword) +'&password_confirm='+ escape(l_sNewPasswordConfirm),
success:function (p_sResponse) { accountJS.changePasswordSuccess(p_sResponse); },
error:function (p_sResponse) { accountJS.changePasswordError(p_sResponse); }
});
};
HungryAccountJS.prototype.changePasswordSuccess = function (p_sResponse) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
if (!l_xResponse['success']) {
alert('An unknown error occurred during your request.  Please make sure you provided the correct credentials.');
} else {
alert('Your password has been changed.');
}
accountJS.resetChangePasswordForm();
};
HungryAccountJS.prototype.changePasswordError = function (p_sResponse) {
alert('An unknown error occurred during your request.  Please try again later.');
accountJS.resetChangePasswordForm();
};
HungryAccountJS.prototype.resetChangePasswordForm = function () {
$('#new_password_form').slideUp(250, function(){ $('#password_wrapper').show(); });
$("#password_old").val('');
$("#password").val('');
$("#password_confirm").val('');
};


accountJS = new HungryAccountJS();

var HungryUserPagesJS = function () {
};


HungryUserPagesJS.prototype.pageRecentCommentsPublic = function (p_nPage) {
l_sDisplayName = _xUserLightbox._sCurrentUsername;
$.ajax({
type:'GET',
url:'/ajax/ajax.php',
data:'a=UserProfileCommentsPublic&user='+ escape(l_sDisplayName) +'&page='+ p_nPage,
success:function (p_sResponse) { userPagesJS.pageRecentCommentsPublicSuccess(p_sResponse); },
error:function (p_sResponse) { userPagesJS.pageRecentCommentsPublicError(p_sResponse); }
});
};
HungryUserPagesJS.prototype.pageRecentCommentsPublicSuccess = function (p_sResponse) {
$("#user_comments_module").html(p_sResponse);
};
HungryUserPagesJS.prototype.pageRecentCommentsPublicError = function (p_sResponse) {
$("#user_comments_module").html(p_sResponse);
};


HungryUserPagesJS.prototype.pageRecentComments = function (p_nPage) {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=UserProfileComments&page='+ p_nPage,
success:function (p_sResponse) { userPagesJS.pageRecentCommentsSuccess(p_sResponse); },
error:function (p_sResponse) { userPagesJS.pageRecentCommentsError(p_sResponse); }
});
};
HungryUserPagesJS.prototype.pageRecentCommentsSuccess = function (p_sResponse) {
$("#user_comments_module").html(p_sResponse);
};
HungryUserPagesJS.prototype.pageRecentCommentsError = function (p_sResponse) {
$("#user_comments_module").html(p_sResponse);
};


HungryUserPagesJS.prototype.pageFavoriteArticles = function (p_nPage) {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=UserFavoriteArticles&page='+ p_nPage,
success:function (p_sResponse) { userPagesJS.pageFavoriteArticlesSuccess(p_sResponse); },
error:function (p_sResponse) { userPagesJS.pageFavoriteArticlesError(p_sResponse); }
});
};
HungryUserPagesJS.prototype.pageFavoriteArticlesSuccess = function (p_sResponse) {
$("#fav_articles_module").html(p_sResponse);
};
HungryUserPagesJS.prototype.pageFavoriteArticlesError = function (p_sResponse) {
$("#fav_articles_module").html(p_sResponse);
};


HungryUserPagesJS.prototype.pageFavoriteVideos = function (p_nPage) {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=UserFavoriteVideos&page='+ p_nPage,
success:function (p_sResponse) { userPagesJS.pageFavoriteVideosSuccess(p_sResponse); },
error:function (p_sResponse) { userPagesJS.pageFavoriteVideosError(p_sResponse); }
});
};
HungryUserPagesJS.prototype.pageFavoriteVideosSuccess = function (p_sResponse) {
$("#fav_videos_module").html(p_sResponse);
};
HungryUserPagesJS.prototype.pageFavoriteVideosError = function (p_sResponse) {
$("#fav_videos_module").html(p_sResponse);
};


HungryUserPagesJS.prototype.newsletterSubscribeFromForm = function (p_nId) {
// prep values
var l_sEmail = $("#email").val();

// perform subscription
this.newsletterSubscribe(l_sEmail, [p_nId], this.newsletterSubscribeFromFormCallback);
};
HungryUserPagesJS.prototype.newsletterSubscribeFromFormCallback = function (p_bSuccess, p_asNewsletterIds) {
// @TODO - better error message
if (!p_bSuccess) {
alert("An unknown error occurred.  Please try again.");
return;
}

// make unsubscribe / subscribe sections visible
for (i=0; i<p_asNewsletterIds.length; i++) {
l_nTempId = p_asNewsletterIds[i];
$("#subscribe_"+ l_nTempId).css("display", "none");
$("#unsubscribe_"+ l_nTempId).show("slow");
}
};


HungryUserPagesJS.prototype.newsletterSubscribe = function (p_sEmail, p_asNewsletterIds, p_xCallback) {
var l_sNewsletterIdsString = p_asNewsletterIds.join(',');

$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=PerformNewsletterSubscribe&u='+ escape(p_sEmail) +'&newsletters='+ l_sNewsletterIdsString,
success:function (p_sResponse) { userPagesJS.newsletterSubscribeSuccess(p_sResponse, p_xCallback); },
error:function (p_sResponse) { userPagesJS.newsletterSubscribeError(p_sResponse, p_xCallback); }
});
};
HungryUserPagesJS.prototype.newsletterSubscribeSuccess = function (p_sResponse, p_xCallback) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
p_xCallback(l_xResponse['success'], l_xResponse['ids']);
};
HungryUserPagesJS.prototype.newsletterSubscribeError = function (p_sResponse, p_xCallback) {
p_xCallback(false, []);
};


HungryUserPagesJS.prototype.newsletterUnsubscribeFromForm = function (p_nId) {
// prep values
var l_sEmail = $("#email").val();

// perform subscription
this.newsletterUnsubscribe(l_sEmail, [p_nId], this.newsletterUnsubscribeFromFormCallback);
};
HungryUserPagesJS.prototype.newsletterUnsubscribeFromFormCallback = function (p_bSuccess, p_asNewsletterIds) {
// @TODO - better error message
if (!p_bSuccess) {
alert("An unknown error occurred.  Please try again.");
return;
}

// make unsubscribe / subscribe sections visible
for (i=0; i<p_asNewsletterIds.length; i++) {
l_nTempId = p_asNewsletterIds[i];
$("#subscribe_check_"+ l_nTempId).removeAttr("checked");
$("#unsubscribe_"+ l_nTempId).css("display", "none");
$("#subscribe_"+ l_nTempId).show("slow");
}
};


HungryUserPagesJS.prototype.newsletterUnsubscribe = function (p_sEmail, p_asNewsletterIds, p_xCallback) {
var l_sNewsletterIdsString = p_asNewsletterIds.join(',');

$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=PerformNewsletterUnsubscribe&u='+ escape(p_sEmail) +'&newsletters='+ l_sNewsletterIdsString,
success:function (p_sResponse) { userPagesJS.newsletterUnsubscribeSuccess(p_sResponse, p_xCallback); },
error:function (p_sResponse) { userPagesJS.newsletterUnsubscribeError(p_sResponse, p_xCallback); }
});
};
HungryUserPagesJS.prototype.newsletterUnsubscribeSuccess = function (p_sResponse, p_xCallback) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
p_xCallback(l_xResponse['success'], l_xResponse['ids']);
};
HungryUserPagesJS.prototype.newsletterUnsubscribeError = function (p_sResponse, p_xCallback) {
p_xCallback(false, []);
};


HungryUserPagesJS.prototype.profileImageChooseClick = function () {
$("#user_profile_image_upload_button").hide();
$("#user_profile_image_upload_iframe").slideDown('slow');
};
HungryUserPagesJS.prototype.profileImageCancelled = function () {
$("#user_profile_image_upload_button").slideDown('slow');
$("#user_profile_image_upload_iframe").hide();
};
HungryUserPagesJS.prototype.profileImageSuccess = function () {
$("#user_profile_image_upload_button").slideDown('slow');
$("#user_profile_image_upload_iframe").hide();

$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=UpdateAccountProfilePic',
success:function (p_sResponse) { userPagesJS.profileImageUpdateSuccess(p_sResponse); },
error:function (p_sResponse) { userPagesJS.profileImageUpdateError(p_sResponse); }
});
};
HungryUserPagesJS.prototype.profileImageUpdateSuccess = function (p_sResponse) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
if (!l_xResponse['success']) {
alert("An unknown error occurred during your request.  Please try again in a few minutes.");
return;
}

$("#profile_image_tag").hide();
$("#profile_image_tag").attr("src", l_xResponse['profile_asset_uri']);
$("#profile_image_tag").slideDown('slow');
};
HungryUserPagesJS.prototype.profileImageUpdateError = function (p_sResponse) {
alert("An unknown error occurred during your request.  Please try again in a few minutes.");
};


HungryUserPagesJS.prototype.submitPasswordResetForm = function () {
var l_bValid = true;

var l_sPassword= $("#reset-password").val();
var l_sPasswordConfirm= $("#reset-password-new").val();
var l_sPasswordError= '';
var l_sPasswordConfirmError= '';

// check for empty values
var l_bEmpty = l_sPassword == null || l_sPassword.length == 0 || l_sPasswordConfirm == null || l_sPasswordConfirm.length == 0;
if (l_bEmpty) {
l_bValid= false;
l_sPasswordError= 'Password required';
}

// check passwords match
var l_bMismatch = !l_bEmpty && l_sPassword != l_sPasswordConfirm;
if (l_bMismatch) {
l_bValid= false;
l_sPasswordConfirmError= 'Passwords do match';
}

// check for password length
if (!l_bEmpty && !l_bMismatch && l_sPassword.length < 6) {
l_bValid= false;
l_sPasswordError= 'Password must be at least 6 characters';
}

// update for validation
$("#reset-password-wrapper").removeClass(l_bValid ? "error" : "valid").addClass(l_bValid ? "valid" : "error");
$("#reset-password-error").html(l_sPasswordError);
$("#reset-password-new-wrapper").removeClass(l_bValid ? "error" : "valid").addClass(l_bValid ? "valid" : "error");
$("#reset-password-new-error").html(l_sPasswordConfirmError);

// submit only if valid
if (l_bValid) {
document['reset-password-form'].submit();
}
};




userPagesJS = new HungryUserPagesJS();



var HungryLoginJS = function () {
};


HungryLoginJS.prototype.isLoggedIn = function (p_xCallback, p_bSecure) {
if (p_bSecure == true) {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=IsLoggedIn',
success:function (p_sResponse) { loginJS.isLoggedInSuccess(p_sResponse, p_xCallback); },
error:function (p_sResponse) { loginJS.isLoggedInError(p_sResponse, p_xCallback); }
});
} else {
var l_sName= 'Hungry_user_clear';
var l_sCookie= ""+ document.cookie;
var l_nIndex= l_sCookie.indexOf(l_sName);
if (l_nIndex == -1) {
loginJS.logoutGlobal();
if (p_xCallback) {
p_xCallback(false);
}
return;
}

var l_nIndex2 = l_sCookie.indexOf(';', l_nIndex);
if (l_nIndex2 == -1) {
l_nIndex2 = l_sCookie.length; 
}
l_sValue= l_sCookie.substring(l_nIndex + l_sName.length + 1, l_nIndex2);
l_xUser= $.evalJSON(Base64.decode(unescape(l_sValue)));
loginJS.loginGlobal(l_xUser);
if (p_xCallback) {
p_xCallback(l_xUser);
}
}
};
HungryLoginJS.prototype.isLoggedInSuccess = function (p_sResponse, p_xCallback) {
l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
if (l_xResponse['loggedIn'] === false) {
if(p_xCallback!=undefined){
p_xCallback(false);
}
} else {
if(p_xCallback!=undefined){
p_xCallback(l_xResponse['user']);
}
}

};
HungryLoginJS.prototype.isLoggedInError = function (p_sResponse, p_xCallback) {
if(p_xCallback!=undefined){
p_xCallback(false);
}
};


HungryLoginJS.prototype.logout = function () {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=PerformLogout',
success:function (p_sResponse) { loginJS.logoutSuccess(p_sResponse); },
error:function (p_sResponse) { loginJS.logoutError(p_sResponse); }
});
};
HungryLoginJS.prototype.logoutSuccess = function (p_sResponse) {
loginJS.logoutGlobal();
};
HungryLoginJS.prototype.logoutError = function (p_sResponse) {

};


HungryLoginJS.prototype.loginFromOverlay = function () {
// clear any error message
$("#login_error_message").html("");

var l_sEmail= $("#login-email").val();
var l_bEmailValid= this.validateEmail(l_sEmail);
if (!l_bEmailValid) {
$("#login-email-wrapper").removeClass("valid").addClass("error");
$("#login-email-error").html("Please enter a valid email");
} else {
$("#login-email-wrapper").removeClass("error").addClass("valid");
$("#login-email-error").html("");
}

var l_sPassword= $("#login-password").val();
var l_bPasswordValid= l_sPassword != null && l_sPassword.length > 0;
if (!l_bPasswordValid) {
$("#login-password-wrapper").removeClass("valid").addClass("error");
$("#login-password-error").html("Please enter a valid email");
} else {
$("#login-password-wrapper").removeClass("error").addClass("valid");
$("#login-password-error").html("");
}

if (l_bEmailValid && l_bPasswordValid) {
this.login(l_sEmail, l_sPassword, this.loginFromOverlayCallback);
}
};
HungryLoginJS.prototype.loginFromOverlayCallback = function (p_xUser) {
if (p_xUser === false) {
$("#login_error_message").html("Invalid credentials.  Please try again.");
$("#login-password").val('');
return;
}
};


HungryLoginJS.prototype.login = function (p_sEmail, p_sPassword, p_xCallback) {
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=PerformLogin&u='+ escape(p_sEmail) +'&p='+ escape(p_sPassword),
success:function (p_sResponse) { loginJS.loginSuccess(p_sResponse, p_xCallback); },
error:function (p_sResponse) { loginJS.loginError(p_sResponse, p_xCallback); }
});
};
HungryLoginJS.prototype.loginSuccess = function (p_sResponse, p_xCallback) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
if (l_xResponse['success'] === false) {
loginJS.logoutGlobal();
if(p_xCallback != undefined){
p_xCallback(false);
}
} else {
loginJS.loginGlobal(l_xResponse['user']);
if(p_xCallback != undefined){
p_xCallback(l_xResponse['user']);
}
}

};
HungryLoginJS.prototype.loginError = function (p_sResponse, p_xCallback) {
loginJS.logoutGlobal();
if(p_xCallback != undefined){
p_xCallback(false);
}
};



HungryLoginJS.prototype.forgotPasswordFromOverlay = function () {
var l_bValid = this.validateForgotPasswordFromOverlay();
if (!l_bValid) {
$("#email-wrapper").removeClass('valid').addClass('error');
$("#email-error").html('Invalid email');
return false;
}

var l_sEmail = $("#login-email").val();
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:'a=PerformForgotPassword&u='+ l_sEmail,
success:function (p_sResponse) { /* fire and forget */ },
error:function (p_sResponse) { /* fire and forget */ }
});
loginJS.forgotPasswordFromOverlaySuccess("eyJzdWNjZXNzIjp0cnVlfQ==");
};
HungryLoginJS.prototype.forgotPasswordFromOverlaySuccess = function (p_sResponse) {
var l_xResponse = $.evalJSON(Base64.decode(p_sResponse));
if (!l_xResponse['success']) {
// @TODO - better error message
alert('An unknown error occurred.  Please try again later.');
return;
}

$('#login_form').find('.login_col').hide();
$('#forgot_thanks').show();
};
HungryLoginJS.prototype.forgotPasswordFromOverlayError = function (p_sResponse) {
// @TODO - better error message
alert('An unknown error occurred.  Please try again later.');
};
HungryLoginJS.prototype.validateForgotPasswordFromOverlay = function () {
return this.validateEmail($("#login-email").val());
};


HungryLoginJS.prototype.validateEmail = function (p_sEmail) {
var l_xEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
return l_xEmail.test(p_sEmail);
};



/********************************
*
*Global Login Logout Functions
*
*********************************/

var loginLogoutInit = function(p_xUser){
if(p_xUser){
loginJS.loginGlobal(p_xUser);
}else{
loginJS.logoutGlobal();
}
}

HungryLoginJS.prototype.loginGlobal=function(p_xUser){
_xComments.logUserIn();
_xLightboxes.logUserIn();
$('#navigation').find('.nt1').hide(); //login button
$('#navigation').find('.nt2').hide(); //register button
$('#navigation').find('.nt4').show(); //user button
$("#self_lightbox_div").show();
_xTruebox.closePopup();

$('#nav_displayname,#comment_username_display').html(p_xUser['display_name']);

if(p_xUser.profile_asset_uri){
var l_sUri = CDN_SERVER+'/files/filecheck/'+p_xUser.profile_asset_uri+'_profile_pic_60.jpg';
$('.self_pic_60').attr('src',l_sUri)

var l_sUri = CDN_SERVER+'/files/filecheck/'+p_xUser.profile_asset_uri+'_profile_pic_60_dark.jpg';
$('.self_pic_60_dark').attr('src',l_sUri)

}else{
var l_sUri = CDN_SERVER+'/image/user/default_user_image.gif';
$('.self_pic_60').attr('src',l_sUri)
$('.self_pic_60_dark').attr('src',l_sUri)
}

};
HungryLoginJS.prototype.logoutGlobal=function(){
_xComments.logUserOut();
_xLightboxes.logUserOut();
$('#navigation').find('.nt1').show(); //login button
$('#navigation').find('.nt2').show(); //register button
$('#navigation').find('.nt4').hide() //user button
$("#self_lightbox_div").hide();

// refresh if in account sections
if (document._bIsUserpage===true) {
document.location = "/";
}
};

loginJS = new HungryLoginJS();
$(document).ready(function(){
loginJS.isLoggedIn(loginLogoutInit);
})


$(document).ready(function(){
_xNavigation.init();
});

_xNavigation = {
_bSubscribeOpen: false,
_bSearchOpen: false,
_bUserDropdownOpen: false,
_xSubscribeTimeout: null,
_nSubTimeoutLength: 10000,

init:function(){
this.setEventHandlers();
},

setEventHandlers:function(){
$('#n2, #n3, #n4, #n5, #n6, #n7').hoverIntent({
over: function(){
var $p_xThis = $(this)
$(this).addClass('hover')
$(this).find('.gray_tab').show();
$(this).find('.submenu').height('auto').slideDown(350);

if (_xNavigation._bSubscribeOpen){
clearTimeout(_xNavigation._xSubscribeTimeout);
$('#subscribe_popup').fadeOut(100);
_xNavigation._bSubscribeOpen = false;
}
},
out: function(){
$(this).removeClass('hover')
$(this).find('.gray_tab').hide();
$(this).find('.submenu').stop().hide();
},
interval: 50
});


$('#n1').children('span').hoverIntent(
function(){
clearTimeout(_xNavigation._xSubscribeTimeout);
if(_xNavigation._bSubscribeOpen == false){
$('#subscribe_popup').fadeIn(200);
_xNavigation._bSubscribeOpen = true;
}
},
function(){ 
clearTimeout(_xNavigation._xSubscribeTimeout); 
_xNavigation._xSubscribeTimeout=setTimeout("_xNavigation.subscribeTimeout()",_xNavigation._nSubTimeoutLength);
}
);


$('#subscribe_popup').mouseover(function(){clearTimeout(_xNavigation._xSubscribeTimeout);})
$('#subscribe_popup').mouseout(function(){clearTimeout(_xNavigation._xSubscribeTimeout);_xNavigation._xSubscribeTimeout=setTimeout("_xNavigation.subscribeTimeout()",_xNavigation._nSubTimeoutLength);})
$('#subscribe_popup').find('.close').live('click',function(){ clearTimeout(_xNavigation._xSubscribeTimeout); $('#subscribe_popup').fadeOut(100); _xNavigation._bSubscribeOpen = false });

$('#n9').hover(
function(){ $('#lightbox_tooltip').show(); },
function(){ $('#lightbox_tooltip').hide(); }
);

$('#navigation').find('.nt3').children('a').click(function(){
if(_xNavigation._bSearchOpen == false){
$('#main_search').animate({ 'width': 'show' }, 200);
$('#navigation').find('.nt3').animate({ 'width': 224 }, 150, function(){ $('#main_search').focus(); });
_xNavigation._bSearchOpen = true;
}
else{
                $(this).siblings('form').submit();//TODO: Trigger Search
}
});

//$('#main_search').focusout(function(){
//$('#main_search').animate({ 'width': 'hide' }, 200);
//$('#navigation').find('.nav-topbar').animate({ 'width': 201 }, 200 );
//
//_xNavigation._bSearchOpen = false;
//});

$('#navigation').find('.nt4').children('a').click(function(){
if(_xNavigation._bUserDropdownOpen == false){
$('#user_dropdown').slideDown(250, 'easeOutExpo');
_xNavigation._bUserDropdownOpen = true;
}
else{
$('#user_dropdown').slideUp(100);
_xNavigation._bUserDropdownOpen = false;
}
});

$('#user_logout').click(loginJS.logout);
},

        subscribeTimeout:function() {
$('#subscribe_popup').hide();
_xNavigation._bSubscribeOpen = false;
        }



}

var HungryRegistrationJS = function () {
this.enabled= true;
this.unitedStatesCanada= true;
this.requiredText = ['first_name', 'last_name', 'display_name', 'email', 'password', 'password_confirm', 'zip'];
this.requiredSelect= ['country'];
this.enableFields= ['first_name', 'last_name', 'display_name', 'email', 'password', 'password_confirm',
   'zip', 'country', 'not_in_us_or_ca', 'optin', 'optin_no', 'address_1', 'city',
   'state', 'subscribe_zip', 'subscribe_387', 'tac_agree'];
};


HungryRegistrationJS.prototype.toggleUnitedStatesCanada = function () {
this.setUnitedStates(!this.unitedStatesCanada);
};
HungryRegistrationJS.prototype.setUnitedStates = function (p_bUnitedStatesCanada) {
// set the state
this.unitedStatesCanada = p_bUnitedStatesCanada;

// set zip visible based on selection
$("#zip_wrapper").css("display", this.unitedStatesCanada ? "block" : "none");
$("#country_wrapper").css("display", this.unitedStatesCanada ? "none" : "block");
$("#subscribe_city_state").css("display", this.unitedStatesCanada ? "block" : "none");
};


HungryRegistrationJS.prototype.registerUserValidate = function () {
// start valid
var ret_bValid = true;

// loop variables
var i= 0;
var l_sTempFieldName= null;
var l_xTempField = null;
var l_xTempWrapper= null;
var l_xTempError= null;
var l_sTempValue= null;

// check required fields
for (i=0; i<this.requiredText.length; i++) {
l_sTempFieldName= this.requiredText[i];
l_xTempField = $("#"+ l_sTempFieldName);
l_xTempWrapper= $("#"+ l_sTempFieldName +"_wrapper");
l_xTempError= $("#"+ l_sTempFieldName +"_error");
l_sTempValue= l_xTempField.val();
if (l_sTempValue == null || l_sTempValue == '') {
// exclude zip when it's not the US
if (!this.unitedStatesCanada && l_sTempFieldName == 'zip') {
continue;
}

// otherwise, check all fields
ret_bValid = false;
l_xTempWrapper.removeClass('valid').addClass('error');
l_xTempError.html('Required');
} else {
l_xTempWrapper.removeClass('error').addClass('valid');
l_xTempError.html('');
}
}

// check required selects
for (i=0; i<this.requiredSelect.length; i++) {
l_sTempFieldName= this.requiredSelect[i];
l_xTempField = $("#"+ l_sTempFieldName);
l_xTempWrapper= $("#"+ l_sTempFieldName +"_wrapper");
l_xTempError= $("#"+ l_sTempFieldName +"_error");
l_nTempIndex= l_xTempField.attr('selectedIndex');
if (l_nTempIndex <= 0) {
// exclude country when it's the US
if (this.unitedStatesCanada && l_sTempFieldName == 'country') {
continue;
}

// otherwise, check all fields
ret_bValid = false;
l_xTempWrapper.removeClass('valid').addClass('error');
} else {
l_xTempWrapper.removeClass('error').addClass('valid');
}
}

// check zip
var l_sZip = $("#zip").val();
if (this.unitedStatesCanada && l_sZip && ((l_sZip.length == 5 && isNaN(parseInt(l_sZip))) || l_sZip.length != 5)) {
ret_bValid = false;
$("#zip_wrapper").removeClass('valid').addClass('error');
$("#zip_confirm_wrapper").removeClass('valid').addClass('error');
$("#zip_error").html('Invalid zip');
}

// check passwords match
var l_sPassword= $("#password").val();
var l_sPasswordConfirm= $("#password_confirm").val();
var l_bPasswordsMatch= l_sPassword.length > 0 && l_sPassword == l_sPasswordConfirm;
if (l_bPasswordsMatch) {
$("#password_wrapper").removeClass('error').addClass('valid');
$("#password_confirm_wrapper").removeClass('error').addClass('valid');
$("#password_confirm_error").html('');
} else {
ret_bValid = false;
if (l_sPasswordConfirm.length > 0) {
$("#password_wrapper").removeClass('valid').addClass('error');
$("#password_confirm_wrapper").removeClass('valid').addClass('error');
$("#password_confirm_error").html('Passwords do not match');
}
}

// check password length (if they match)
if (l_bPasswordsMatch) {
if (l_sPassword.length >= 6) {
$("#password_wrapper").removeClass('error').addClass('valid');
$("#password_error").html('');
} else {
ret_bValid = false;
$("#password_wrapper").removeClass('valid').addClass('error');
$("#password_error").html('Password length must be at least 6 characters');
}
}

// check country select
if (!this.unitedStatesCanada) {
if ($("#country").attr("selectedIndex") == 0) {
ret_bValid = false;
$("#country_wrapper").removeClass('valid').addClass('error');
$("#country_error").html('Required');
} else {
$("#country_wrapper").removeClass('error').addClass('valid');
$("#country_error").html('');
}
}

// if opt in selected, check subscription address / city / state / zip
var l_bOptInSelected = $("input[name=oppId]:radio:checked").val() == 1600066;
if (l_bOptInSelected) {
var l_asSubscriptionFields = ['address_1', 'city', 'subscribe_zip'];

// check subscription required fields
for (i=0; i<l_asSubscriptionFields.length; i++) {
l_sTempFieldName= l_asSubscriptionFields[i];
l_xTempField = $("#"+ l_sTempFieldName);
l_xTempWrapper= $("#"+ l_sTempFieldName +"_wrapper");
l_xTempError= $("#"+ l_sTempFieldName +"_error");
l_sTempValue= l_xTempField.val();
if (l_sTempValue == null || l_sTempValue == '') {
// exclude zip when it's not the US
if (!this.unitedStatesCanada && l_sTempFieldName == 'subscribe_zip') {
continue;
}

// otherwise, check all fields
ret_bValid = false;
l_xTempWrapper.removeClass('valid').addClass('error');
l_xTempError.html('Required');
} else {
l_xTempWrapper.removeClass('error').addClass('valid');
l_xTempError.html('');
}
}
}

// return validation result
return ret_bValid;
};


HungryRegistrationJS.prototype.registerUser = function () {
// only if we're enabled
if (!this.enabled) {
return;
}

// validate form
l_bValid = this.registerUserValidate();
if (l_bValid === false) {
alert("There are errors with your information. please check the fields marked with an X.");
this.setEnabled(true);
return;
}

// check TAC checked (only if valid to prevent dual error messages)
if ($("#tac_agree:checked").val() == null) {
alert("You must agree to the Terms & Conditions in order to register");
this.setEnabled(true);
return;
}

// @NOTE - get serialized form BEFORE disabling b/c disabled fields are excluded
var l_sData = $("#register_form").serialize();
this.setEnabled(false);
        _xMain.callOmniture('registersuccess')
// make the call AFTER disabling
$.ajax({
type:'POST',
url:'/ajax/ajax.php',
data:l_sData,
success:function (p_sResponse) { registrationJS.registerUserSuccess(p_sResponse); },
error:function (p_sResponse) { registrationJS.registerUserError(p_sResponse); }
});
};
HungryRegistrationJS.prototype.registerUserSuccess = function (p_sResponse) {
// re-enable form
this.setEnabled(true);

// process response
var l_xData= $.evalJSON(Base64.decode(p_sResponse));
var l_bSuccess= l_xData['success'];
var l_sMessage= l_xData['message'];
var l_sOpenUrl= l_xData['subscribeURL'];
if (l_bSuccess) {
$("#register_form_contents").css("display", "none");
$("#register_form_thanks").css("display", "inline");
$.scrollTo("#register_form_thanks", 500, {offset: -300});

if (l_sOpenUrl && l_sOpenUrl.indexOf('http://') == 0) {
window.open(l_sOpenUrl, 'subscription_window');
}
} else {
var l_sInvalidField= null;
var l_nCode= l_xData['code'];
var l_nSubCode= l_xData['sub_code'];
var l_sComboCode= l_nCode +"-"+ l_nSubCode;
switch (l_sComboCode) {
case '200-600':l_sInvalidField = 'email';break;
case '400-100':l_sInvalidField = 'email';break;
case '400-611':l_sInvalidField = 'display_name';break;
case '400-612':l_sInvalidField = 'password';break;
case '400-613':l_sInvalidField = 'email';break;
case '409-650':l_sInvalidField = 'email';break;
case '1001-1001':l_sInvalidField = 'display_name';break;
} 
if (l_sInvalidField != null) {
$("#"+ l_sInvalidField +"_wrapper").removeClass('valid').addClass('error');
$("#"+ l_sInvalidField +"_error").html(l_sMessage);
}
alert("ERROR: "+ l_sMessage);
}
};
HungryRegistrationJS.prototype.registerUserError = function (p_sResponse) {
// re-enable form
this.setEnabled(true);

// @TODO - process error
alert(p_sResponse);
};


HungryRegistrationJS.prototype.setEnabled = function (p_bEnabled) {
this.enabled = p_bEnabled;

// loop variables
var i= 0;
var l_xTempElement= null;

// required text
for (i=0; i<this.enableFields.length; i++) {
l_xTempElement = $("#"+ this.enableFields[i]);
if (this.enabled) {
l_xTempElement.removeAttr("disabled");
} else {
l_xTempElement.attr("disabled", "disabled");
}
}

$("#register_submit").css("display", this.enabled ? "block" : "none");
$("#register_submit_processing").css("display", this.enabled ? "none" : "block");
};


registrationJS = new HungryRegistrationJS();

$(document).ready(function(){
$('#footer').find('.bf2').click(function(){
_xFooter.openSisterSites(); 
});

$('#sister_sites').mouseleave(function(){ $('#sister_sites').hide(); });

        if ($('.buttons_holder').length) {_xFooter.balanceShare();};

});

_xFooter = {

        _sTypeReference:null,
        _nId:null,
openSisterSites:function(){
$('#sister_sites').fadeIn(400);
$('#sister_sites').find('ul').jScrollPane({scrollbarWidth: 9, scrollbarMargin: 20, animateTo: true });
},

        showArchivedPressReleases:function()    {
                if ($('#press_bottom div.press_archive').is(':visible')) {
                $('#press_bottom a.archive_toggle span').text('for');
                } else {
                $('#press_bottom a.archive_toggle span').text('to hide');
                }

                $('#press_bottom div.press_archive').slideToggle('slow');

        },

        addToFavoritesGateway:function(p_sTypeReference, p_nId)    {
                _xFooter._sTypeReference = p_sTypeReference;
                _xFooter._nId = p_nId;
                loginJS.isLoggedIn(_xFooter.addToFavorites);
        },

        addToFavorites:function(p_xUser)    {

                //p_xUser = new Array();
                //p_xUser["id"] = 25;
                if (p_xUser === false) {
                    alert('Please login first to add your favorites');
                    return;
                }
                //retrieve the variables to show
                var l_sTypeReference = _xFooter._sTypeReference;
                var l_nId = _xFooter._nId;

                //reset the varaibles
                _xFooter._sTypeReference = null;
                _xFooter._nId = null;
            
                BaseAjax._xArgs.data = 'a=AddToFavorites';
                BaseAjax._xArgs.data += '&typereference='+ l_sTypeReference;
                BaseAjax._xArgs.data += '&id='+ l_nId;


                BaseAjax._xArgs.returnDiv = '#share_test';
                //BaseAjax._xArgs.callBack =function(){_xGallery.showThumbnailsCallback(p_nThumbPage)};
                BaseAjax._xArgs.requestType = "GET";
                BaseAjax.makeAjaxCall(); 

        },

        balanceShare:function()  {

                var l_nButtonsHolderWidth = $('.buttons_holder').width();
                var l_nBalanceWidth = $('.buttons_holder .balance').width();
                var l_nDiff = (l_nButtonsHolderWidth - l_nBalanceWidth) / 2;
                $('.buttons_holder .balance').css('margin-left', l_nDiff + "px").show();
        }

}

$(document).ready(function(){

if(_xLightboxes._bIsLightboxPage == true)
_xUserLightbox.init();
   
$('#user_pw_update').click(function(){
$('#password_wrapper').hide();
$('#new_password_form').slideDown();
});

$('#user_account_cancelpw').click(function(){
$('#new_password_form').slideUp(250, function(){ $('#password_wrapper').show(); });
});



});

_xUserLightbox = {
_sCurrentUsername : '',
_bCreateLightboxOpen: false,
init:function(){
this.setEventHandlers();
this.createSortableLightbox();
},
paginatePublicLightboxes:function(p_nPage){

BaseAjax._xArgs.data= 'a=LightboxesPublicPaginate';
BaseAjax._xArgs.data+='&accountname='+ escape(_xUserLightbox._sCurrentUsername);
BaseAjax._xArgs.data+='&page='+p_nPage;
BaseAjax._xArgs.returnDiv = '#user_lightboxes_module';

BaseAjax.makeAjaxCall();

},
setEventHandlers:function(){
$('#lightbox_links').children('.createlink').click(function(){
if(_xUserLightbox._bCreateLightboxOpen == false) {
$('#lightbox_create').slideDown(1000, 'easeOutExpo');
_xUserLightbox._bCreateLightboxOpen = true;
$(this).children('span').text('Cancel New Lightbox');
$('#lightbox_name').val('')
$('#lightbox_description').val('Enter some details about your lightbox here.');
}
else{
$('#lightbox_create').slideUp(300);
_xUserLightbox._bCreateLightboxOpen = false;
$(this).children('span').text("Create New Lightbox");
}
});

$('#sortable_lightbox, #horizontal_images_wrapper, #public_lightbox_images').children('li').hover(
function(){ $(this).children('.overlay').fadeIn('50'); },
function(){ $(this).children('.overlay').hide(); }
);

$('#lightbox_image_view').find('.addlink').click(function(){
$(this).children('.add_popup').fadeIn(250);
//$(this).find('ul').jScrollPane();
});

$('#lightbox_image_view').find('.addlink').mouseleave(function(){
$(this).children('.add_popup').fadeOut(100);
});

},

createSortableLightbox:function(){
$('#sortable_lightbox').sortable({scroll: false, stop: 
function(){ 
$('#sortable_lightbox').find('.overlay').hide();   
//_xUserLightbox.resortImagesInThumbnail();
} 
});
},

cancelResortImagesInThumbnail:function(){

var l_sLocation = '/my/lightboxes/'+_xLightboxes._nThisLightbox+'/';
window.location= l_sLocation;

},

resortImagesInThumbnail:function(){
var l_sOrder = '';
var l_nCount = 0
$('#sortable_lightbox').find('img.asset').each(function(){
l_sOrder+= ((!l_nCount++)?'':',')+$(this).attr('rel')

})

BaseAjax._xArgs.data= 'a=LightboxResortThumbnails';
BaseAjax._xArgs.data+='&lightbox_id='+_xLightboxes._nThisLightbox;
BaseAjax._xArgs.data+='&sort_order='+l_sOrder;
BaseAjax._xArgs.callBack = _xUserLightbox.resortImagesInThumbnailCallback;

BaseAjax._xArgs.requestType = "POST"; 

BaseAjax.makeAjaxCall();

//console.log(l_sOrder);


},

resortImagesInThumbnailCallback:function(){
var l_sLocation = '/my/lightboxes/'+_xLightboxes._nThisLightbox+'/';
window.location= l_sLocation;
}
}

$(document).ready(function(){
_xTruebox.init();
})

_xTruebox ={

init:function(){
this.makeTruebox();
//this.setClicks();
},

makeTruebox:function(){
$('body').append('<div class="truebox_overlay" id="truebox_overlay"></div><div id="truebox" class="truebox"></div>');
},

setClicks:function(){
$('#truebox_overlay').live('click',function(){
_xTruebox.closePopup();
});
},

unsetClicks:function(){
$('#truebox_overlay').unbind('click');
},

makePopup:function(p_sAction, p_bIsAlert){
this.makePopupOverlay(p_bIsAlert);
$('#truebox').empty().show().css('top',  $(document).scrollTop()+100  );

switch(p_sAction){
case 'loginform':
   this.makeLoginForm();
break;
case 'registerform':
   this.makeRegisterForm();
break;
case 'forgotpassword':
   this.makeForgotPasswordForm();
break;

}

},


makePopupOverlay:function(p_bIsAlert){
if (p_bIsAlert) {
this.unsetClicks();
} else {
this.setClicks();
}
var l_nWindowHeight = $(window).height();
var l_nBodyHeight = $('.holder').height();
var l_nTheHeight = (l_nWindowHeight > l_nBodyHeight)?l_nWindowHeight:l_nBodyHeight;
if(document.isIE)
$('#truebox_overlay').show().height( l_nTheHeight + 200 );
else
$('#truebox_overlay').fadeIn(200).height( l_nTheHeight + 200 );

},

closePopup : function(){
$('#truebox').attr('class','truebox png');
//don't empty div, incase user will be "stress testing" this feature - we don't want to AJAX server on every click
//emptying div for now as truebox overlays are conflicting.
$('#truebox').empty().hide();
$('#truebox_overlay').empty().hide();
},

makeLoginForm : function(){
$('#truebox').addClass('login_form_truebox');

BaseAjax._xArgs.data = 'a=GetLoginForm';
BaseAjax._xArgs.returnDiv = '#truebox';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},

makeRegisterForm : function(){
                _xMain.callOmniture('register')
                var l_sTempPageName = s.pageName;
                s.pageName = "register";
                $('#truebox').addClass('register_form_truebox');

BaseAjax._xArgs.data = 'a=GetRegisterForm';
BaseAjax._xArgs.returnDiv = '#truebox';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
},

makeForgotPasswordForm : function(){
$('#truebox').addClass('login_form_truebox');

BaseAjax._xArgs.data = 'a=GetForgotPasswordForm';
BaseAjax._xArgs.returnDiv = '#truebox';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall();
}
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
 
input = Base64._utf8_encode(input);
 
while (i < input.length) {
 
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
 
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
 
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
 
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
}
 
return output;
},
 
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
 
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
while (i < input.length) {
 
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
 
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
 
output = output + String.fromCharCode(chr1);
 
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
 
}
 
output = Base64._utf8_decode(output);
 
return output;
 
},
 
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
 
for (var n = 0; n < string.length; n++) {
 
var c = string.charCodeAt(n);
 
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
 
}
 
return utftext;
},
 
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
 
while ( i < utftext.length ) {
 
c = utftext.charCodeAt(i);
 
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
 
}
 
return string;
}
 
}

_xTwitter = {


        init:function(){

},

        callTwitter:function(p_sSearchString)  {
            //explode by commas
            var l_aSearchItems = p_sSearchString.split(",");
            var l_nArrayLength = l_aSearchItems.length;
            var l_aBreakString = "";
            var l_sSearchString = "";

            for (i=0; i < l_nArrayLength; i++) {

                if (i > 0) {l_sSearchString += "+OR+";}
                //evaluate l_aSearchItems[i]
                var l_sTerm = l_aSearchItems[i];
                var l_sCharacterEval = l_sTerm.substring(0,1);
                //get rid of spaces
                while (l_sCharacterEval == " ") {
                    l_sTerm = l_sTerm.substr(1);
                    l_sCharacterEval = l_sTerm.substring(0,1);
                }

                switch (l_sCharacterEval)  {
                    case "@":
                        l_sTerm = l_sTerm.substring(1);
                        l_sTerm = "from:"+l_sTerm;
                        break;
                    case "#":
                        l_sTerm = l_sTerm.substring(1);
                        l_sTerm = "%23"+l_sTerm;
                        break;
                }

                //encapsulate if there are multiple words
                if (l_sTerm.indexOf(" ") != -1)   {l_sTerm = '"'+l_sTerm+'"';}
                l_sSearchString += l_sTerm;
            }

            var l_nTwitterCount = 40;
            //Callback function name
            var callback_name = "_xTwitter.twitterCallback";
            //Return type (json or xml)
            var return_type = "json";
            //Adds script tags to the head/body tag

            var twitterapiurl = "http://search.twitter.com/search.json?q=" + l_sSearchString + "&rpp=" + l_nTwitterCount +"&callback=?";

            $.getJSON(twitterapiurl,function(ob){_xTwitter.formatTweets(ob);});

        
        },


      formatTweets:function(data) {
            var tweetlist = new Array();

            var newlist = new Array();
            $(data.results).each(function(el){
                newlist.push(this);
            });
            tweetlist = newlist.concat(tweetlist);
            var l_sTweets = '';
            for(var i=0;i < tweetlist.length;i++) {
                var tweet = tweetlist[i];

                if( tweet.text != undefined ) {
                    var tweetdate = _xTwitter.returnDate(tweet);
                    var tweettext = tweet.text.toString().replace( /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$1">$1</a>' ).replace( /(^|\s)@(\w+)/, '<a href="http://www.twitter.com/$2">@$2</a>' ).replace( /[#]+[A-Za-z0-9-_]+/ig, function(t) {var tag = t.replace("#","%23");return t.link("http://search.twitter.com/search?q="+tag);} );
                    l_sTweets += "<div class=\"tweet\"><p class=\"text\"><strong>" + tweet.from_user + "</strong> - " + tweettext + "</p><p class=\"timestamp\">" + tweetdate + "</p></div>"
                }
            }
            $( "#tweet_holder" ).append(l_sTweets);
    },


  returnDate:function(p_xTweet)   {
            var months = new Array(13);
            months[0]  = "January";
            months[1]  = "February";
            months[2]  = "March";
            months[3]  = "April";
            months[4]  = "May";
            months[5]  = "June";
            months[6]  = "July";
            months[7]  = "August";
            months[8]  = "September";
            months[9]  = "October";
            months[10] = "November";
            months[11] = "December";

            var l_sManipulateMe = p_xTweet.created_at;

            var date = new Date(l_sManipulateMe.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));
            var hour        = date.getHours();
            var minute      = date.getMinutes();
            var second      = date.getSeconds();
            var monthnumber = date.getMonth();
            var monthname   = months[monthnumber];
            var monthday    = date.getDate();
            var year        = date.getFullYear();

            var ap = "AM";
            if (hour   > 11) {ap = "PM";}
            if (hour   > 12) {hour = hour - 12;}
            if (hour   == 0) {hour = 12;}
            if (minute < 10) { minute = "0" + minute; }

            var tweetdate = hour + ":" + minute + " " + ap + " | " + monthname + " " + monthday + ", " + year;

            return tweetdate
        },


        twitterCallback:function(data) {

            var l_sTweets = '';
            //Loop through the data from twitter
            $.each( data, function( i, tweet ) {
                //Make sure the text isn't undefined
                if( tweet.text != undefined ) {
                    var tweetdate = _xTwitter.returnDate(tweet);
                    var text = tweet.text.toString().replace( /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$1">$1</a>' ).replace( /(^|\s)@(\w+)/, '<a href="http://www.twitter.com/$2">@$2</a>' ).replace( /[#]+[A-Za-z0-9-_]+/ig, function(t) {var tag = t.replace("#","%23");return t.link("http://search.twitter.com/search?q="+tag);} );
                    l_sTweets += "<div class=\"tweet\"><p class=\"text\"><strong>" + tweet.user.name + "</strong> - " + text + "</p><p class=\"timestamp\">" + tweetdate + "</p></div>"
                }
            });
            $( "#tweet_holder" ).append(l_sTweets);

        },

        scrollUp:function()  {
            var l_nNewAmount = $('#tweet_holder').scrollTop() - 300;
            $('#tweet_holder').animate({scrollTop : l_nNewAmount},1000);
            
        },


        scrollDown:function()  {
            var l_nNewAmount = $('#tweet_holder').scrollTop() + 300;
            $('#tweet_holder').animate({scrollTop : l_nNewAmount},1000);
        }




}

$(document).ready(function(){
$('#agg_more').click(function(){
$('#agg_dropdown').slideToggle(600, 'easeOutExpo');
$(this).toggleClass('selected');
});



var l_nHeightForIframe = $(window).height() - 106;
$('#agg_iframe').height(l_nHeightForIframe);
});


_xAggregator = {

    getAggregatorIframeDropdown:function(p_nPage){

            BaseAjax._xArgs.data = 'a=GetAggregatorIframeDropdown';
BaseAjax._xArgs.data += '&page='+p_nPage;
BaseAjax._xArgs.requestType = "GET";
//BaseAjax._xArgs.callBack = _xComments.sendCommentVoteCallback;
                BaseAjax._xArgs.returnDiv = '#agg_dropdown';
BaseAjax.makeAjaxCall();

        
    }

    
}

_xArchive = {
        getHungryDailyArchive: function(p_nMonth, p_nYear) {
/*
                if (!$('.archive_reception').length) {

                        $('#archive_module').wrap('<span class="archive_reception">');
                } */

                
                var l_bIsAjax = true;

                BaseAjax._xArgs.data = 'a=GetHungryDailyArchive';
                BaseAjax._xArgs.data += '&month='+p_nMonth;
                BaseAjax._xArgs.data += '&year='+p_nYear;
                BaseAjax._xArgs.data += '&isajax='+l_bIsAjax;
                BaseAjax._xArgs.returnDiv = '#archive_module';
                BaseAjax._xArgs.requestType = "GET";
                BaseAjax.makeAjaxCall(); 
               
        }

        



}



_xDatebook = {

        adjustColumnThreeAndFour:function()    {
            var l_nChildren =  $('.db_col.col_4').children();
            var l_nChildCount = $('.db_col.col_4').children().length;
            var l_nNonDateItemsHeight = 0;

            //get the height of the nondate items
            l_nChildren.each(function(index){
                if (index < 2){
                    l_nNonDateItemsHeight += $(this).height();
                }
            })

            //get the height of col 3
            var $l_nColThreeHeight = $('.db_col.col_3').height();

            //if the height of column three is less than the first two elements
            //of column four, and there are elements to migrate, put them over on column three
            if ($l_nColThreeHeight < l_nNonDateItemsHeight && l_nChildCount > 2)  {
                l_nChildren.each(function(index){
                    if (index >= 2)  {
                        $(this).appendTo('.db_col.col_3');
                    }
                });

            }
            
        }
}

_xhfcDaily = {
_nAnim: 250,

getPrevSlide:function(p_xDomElement){
var $slide_holder = $(p_xDomElement).parent().siblings('.slide_holder');
var $first = $slide_holder.find('.slide:first');
var $last = $slide_holder.find('.slide:last');
var $selected = $slide_holder.find('.selected');
var $next = $slide_holder.find('.next');
var $prev = $slide_holder.find('.prev');

if($prev[0] == $first[0]){
var $prevprev = $last;
}
else{
var $prevprev = $prev.prev();
}

$selected.fadeOut(_xhfcDaily._nAnim).attr('class', 'slide next');
$prev.fadeIn(_xhfcDaily._nAnim).attr('class', 'slide selected');
$next.attr('class', 'slide');
$prevprev.attr('class', 'slide prev');

var l_nNumber = $prev.attr('data-count');
$(p_xDomElement).siblings('.count').children('span').text(l_nNumber);
},

getNextSlide:function(p_xDomElement){
var $slide_holder = $(p_xDomElement).parent().siblings('.slide_holder');
var $first = $slide_holder.find('.slide:first');
var $last = $slide_holder.find('.slide:last');
var $selected = $slide_holder.find('.selected');
var $next = $slide_holder.find('.next');
var $prev = $slide_holder.find('.prev');

if($next[0] == $last[0]){
var $nextnext = $first;
}
else{
var $nextnext = $next.next();
}

$selected.fadeOut(_xhfcDaily._nAnim).attr('class', 'slide prev');
$next.fadeIn(_xhfcDaily._nAnim).attr('class', 'slide selected');
$prev.attr('class', 'slide');
$nextnext.attr('class', 'slide next');

var l_nNumber = $next.attr('data-count');
$(p_xDomElement).siblings('.count').children('span').text(l_nNumber);
}
}

var HungryContactJS = function () {
this.requiredFields = ["my_name", "my_email", "my_subject_textarea"];
};


HungryContactJS.prototype.contact = function () {
var l_bValid = this.contactValidate();
if (l_bValid) {
document['contact_form'].submit();
}
};


HungryContactJS.prototype.contactValidate = function () {
// start valid
var ret_bValid = true;

// check required fields
var l_sTempValue = null;
for (i=0; i<this.requiredFields.length; i++) {
l_sTempFieldName= this.requiredFields[i];
l_sTempValue= $("#"+ l_sTempFieldName).val();

if (l_sTempValue == null || l_sTempValue.length == 0) {
ret_bValid = false;
$("#"+ l_sTempFieldName +"_wrapper").removeClass("valid").addClass("error");
$("#"+ l_sTempFieldName +"_error").html('Required');
} else {
$("#"+ l_sTempFieldName +"_wrapper").removeClass("error").addClass("valid");
$("#"+ l_sTempFieldName +"_error").html('');
}
}

// report results
if (!ret_bValid) {
alert("Please check all fields marked with an 'X'.");
}
return ret_bValid;
};


contactJS = new HungryContactJS();

$(document).ready(function(){
_xGallery.init();

});



_xGallery = {
        _nSidebarWidth:0,
        _bPlayMode:false,
        _xPlayTimeout:null,
        _sGalleryHash:null,
        _nGalleryType:null,
        _sGalleryId:null,
        _bInit:false,
        _nThumbReturnPage:1,
        _nReturnPage:1,
        _CategoryReturnPage:1,
        _sCollectionType:null,
        _nGalleryReturnPage:null,
        _aPath : null,
        _nItemValue : null,
        _sLastPage : null,
        _sScrollTop:null,
        init:function(){
             _xGallery.insertOverlay();
                //two things can happen. A URL, which leads to an auto matic launch
                //if not that, check for gallery anchor length
                //document.isPhotoDetail = true;
                //if ($('.gallery_anchor').length)    {_xGallery.insertOverlay();}
                if ($.browser.msie && parseInt($.browser.version) == 7){}
                else {_xGallery.initHistory();}


                $('#gallery_right ul#controls li a#play').live('click', function(event){event.preventDefault();});

$(window).resize(function(e){
if($('#featured_gallery_image').length)
_xGallery.checkGallerySizeAndRescale();
});

        },
        initHistory:function(){
$.historyInit(_xGallery.detectChangeAddress);

},


        grabAddressData:function(hash){
hash = hash.replace(/^.*#/, '');
var l_aPathNames= hash.split('/');
l_sSwitch = l_aPathNames[1];
//close it if the user has gone all the way back
if (l_sSwitch === undefined && $('#gallery').length)   {_xGallery.closeDialog();}
_xGallery._sScrollTop = $(window).scrollTop();

//get the scrollToplocation


/* example hashes
#/gallery/<slug>/<page>/
#/lightbox/<username>/<id>/<page>/
#/collection/<type>/<season-slug>/<designer-slug>/<page>/
#/guide/<id>/<page>/

*/
// qualify agains the four types
if(l_sSwitch=='gallery' || l_sSwitch=='lightbox' || l_sSwitch=='guide' ||l_sSwitch=='collection'){
switch (l_sSwitch)  {
case 'gallery':
// check the slug and the page
if (l_aPathNames[2] != undefined &&  isNaN(l_aPathNames[2]) && !isNaN(l_aPathNames[3])) {
if (_xGallery._bInit == false) {
_xGallery._nGalleryType = 1
_xGallery._sGalleryId = l_aPathNames[2];
_xGallery._nGalleryPage = l_aPathNames[3];
_xGallery._bInit = true;
}

_xGallery.hashGalleryOpen(l_aPathNames[3]);
}

break;
case 'lightbox':
if ( !isNaN(l_aPathNames[2]) && !isNaN(l_aPathNames[3])) {
if (_xGallery._bInit == false) {
_xGallery._nGalleryType = 2;
_xGallery._sGalleryId = l_aPathNames[2];
_xGallery._nGalleryPage = l_aPathNames[3];
_xGallery._bInit = true;
}
_xGallery.hashGalleryOpen(l_aPathNames[3]);

}

break;
case 'collection':
if (l_aPathNames[2] != undefined &&  isNaN(l_aPathNames[2]) && isNaN(l_aPathNames[3]) && isNaN(l_aPathNames[4]) && !isNaN(l_aPathNames[5])) {
if (_xGallery._bInit == false) {
_xGallery._nGalleryType = 3;
_xGallery._sCollectionType = l_aPathNames[2];
_xGallery._sGalleryId = l_aPathNames[3];
_xGallery._sDesigner = l_aPathNames[4];
_xGallery._nGalleryPage = l_aPathNames[5];
_xGallery._bInit = true;
}
_xGallery.hashGalleryOpen(l_aPathNames[5]);

}
break;
case 'guide':
if (l_aPathNames[2] != undefined &&  !isNaN(l_aPathNames[2]) && !isNaN(l_aPathNames[3])) {
if (_xGallery._bInit == false) {
_xGallery._nGalleryType = 4
_xGallery._sGalleryId = l_aPathNames[2];
_xGallery._nGalleryPage = l_aPathNames[3];
_xGallery._bInit = true;
}

_xGallery.hashGalleryOpen(l_aPathNames[3]);
}

break;
}
//what is required to start the xGallery here

}
else{
this._aPath = null
//this._nItemValue = null
}


},

detectChangeAddress:function(hash){
_xGallery.grabAddressData(hash);

},

        goToGalleryFromThumbs:function(p_nGalleryPage, p_nThumbReturnPage)    {
                if (p_nThumbReturnPage === undefined)
{_xGallery._nThumbReturnPage = 1}
else
{_xGallery._nThumbReturnPage = p_nThumbReturnPage}
                _xGallery.goToGalleryItem(p_nGalleryPage);
        },

        goToGalleryFromCategory:function(p_nGalleryPage, p_nCatReturnPage)  {
                if (p_nCatReturnPage === undefined) {_xGallery._nCatReturnPage = 1} else {_xGallery._nCatReturnPage = p_nCatReturnPage}
                _xGallery.goToGalleryItem(p_nGalleryPage);
        },

        historyLoadRefresh:function(p_sUrl)   {
            _xGallery._bInit = false;
            _xGallery.historyLoad(p_sUrl);
        },


        historyLoad:function(p_sUrl){
                if ($.browser.msie && parseInt($.browser.version) == 7){
                    var newhash = '#' + p_sUrl;
                    _xGallery.grabAddressData(p_sUrl);
                }else
                $.historyLoad(p_sUrl)
        },

goToGalleryItem:function(p_nGalleryPage, p_bEnablePlayMode){
                if (p_bEnablePlayMode != true)  {
                    _xGallery.stopPlayMode();}

                switch (_xGallery._nGalleryType)  {
                    case 1:
                        l_sUrl = '/gallery/' + _xGallery._sGalleryId + '/' + p_nGalleryPage;
                        break;
                    case 2:
                        l_sUrl = '/lightbox/' + _xGallery._sGalleryId + '/' + p_nGalleryPage;
                        break;
                    case 3:
                        l_sUrl = '/collection/' + _xGallery._sCollectionType + '/' + _xGallery._sGalleryId + '/' + _xGallery._sDesigner + '/' + p_nGalleryPage;
                        break;

                    case 4:
                        l_sUrl = '/guide/' + _xGallery._sGalleryId + '/' + p_nGalleryPage;
                        break;

                }

            _xGallery.historyLoad(l_sUrl);
},

        galleryReset:function(p_sUrl)    {
            _xGallery._bInit = false;
            $("#overlay").fadeOut('fast', function() {

                    $("#overlay").remove();
                    _xGallery.historyLoad(p_sUrl);
                })
        },
        insertOverlay:function(){
if (!$('#overlay').length) {
var overlay =  "<div id=\"overlay\"><div id=\"blanket\">\n\</div><div id=\"reception\"></div></div>";
$('body').prepend(overlay);
}
},
        hashGalleryOpen:function(p_nGalleryPage){
                        _xMain.callOmniture(p_nGalleryPage, 'gallery');
BaseAjax._xArgs.data = 'a=OpenGallery';
BaseAjax._xArgs.data += '&type='+_xGallery._nGalleryType;
BaseAjax._xArgs.data += '&id='+_xGallery._sGalleryId;
BaseAjax._xArgs.data += '&page='+p_nGalleryPage;

if (_xGallery._nGalleryType == 3)    {
BaseAjax._xArgs.data += '&collectiontype='+_xGallery._sCollectionType;
BaseAjax._xArgs.data += '&designer='+_xGallery._sDesigner;
}

BaseAjax._xArgs.returnDiv = '#reception';
BaseAjax._xArgs.callBack =function(){_xGallery.hashGalleryOpenCallback(p_nGalleryPage, true)};

BaseAjax._xArgs.requestType = "GET";
$("#overlay").fadeIn(250, function(){
BaseAjax.makeAjaxCall();
});

        },
        hashGalleryOpenCallback:function(p_nGalleryPage, p_isInit) {
var l_nIntPage = parseInt(p_nGalleryPage);
var l_nNextPage = l_nIntPage + 1;
var l_nPreviousPage = l_nIntPage -1;
if (p_isInit == true) {_xGallery._nListTotal = parseInt($('#gallery span#total').text());}


//map the arrow keys
_xGallery.mapGalleryKeys(l_nPreviousPage, l_nNextPage);

if (l_nIntPage == _xGallery._nListTotal) {_xGallery._bPlayMode = false}
if ( _xGallery._bPlayMode == true)   {
$('#gallery_right ul#controls li a#play').addClass('playing');
}

$('#gallery_right div#advertisements iframe').each(function(index) {$(this).attr('src', $(this).attr('src'));});

//l_oMainImage.load(function(){
_xGallery.checkGallerySizeAndRescale();
                                var l_oMainImage = $('#featured_gallery_image');

                                $(".gallery").fadeIn('slow', function(){
l_oMainImage.fadeIn('slow');
if ( _xGallery._bPlayMode == true)   {
$('#gallery_right ul#controls li a#play').addClass('playing');
_xGallery._xPlayTimeout = setTimeout(function(){_xGallery.goToGalleryItem(l_nNextPage, true); l_nNextPage = null}, 5000);
}
                      setTimeout(function(){_xGallery.shareThis();}, 3000);
  

})
//});
        },


        showThumbnails:function(p_nThumbPage, p_nReturnPage){
_xMain.callOmniture('thumbnails', 'gallery');
var l_bViewAll = false

// Method to view all
if(p_nThumbPage===true){
l_bViewAll = true
}else{
// PHP defines the Thumbpage for Gallery images
if (p_nThumbPage === undefined)
{p_nThumbPage = 1}
// if it comes in undefined, or not a number, set this function's return page to the object'
}
if (p_nReturnPage === undefined || isNaN(p_nReturnPage))
{p_nReturnPage = _xGallery._nReturnPage}
else
{_xGallery._nReturnPage = p_nReturnPage}

// turn off play mode
_xGallery.stopPlayMode();

BaseAjax._xArgs.data = 'a=ShowThumbnails';
if(l_bViewAll){
BaseAjax._xArgs.data += '&viewall=1';
}else{
BaseAjax._xArgs.data += '&page='+ p_nThumbPage;
}
BaseAjax._xArgs.data += '&returnpage='+ p_nReturnPage;
BaseAjax._xArgs.data += '&id='+ _xGallery._sGalleryId;
BaseAjax._xArgs.data += '&type='+ _xGallery._nGalleryType;

if (_xGallery._nGalleryType == 3)    {
BaseAjax._xArgs.data += '&collectiontype='+_xGallery._sCollectionType;
BaseAjax._xArgs.data += '&designer='+_xGallery._sDesigner;
}

BaseAjax._xArgs.returnDiv = '#reception';
BaseAjax._xArgs.callBack =function(){_xGallery.showThumbnailsCallback(p_nThumbPage)};
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall();

        },

        showThumbnailsCallback: function(p_nThumbPage)  {
_xGallery._nThumbReturnPage = p_nThumbPage;
$('.gallery_thumbnail_browser').fadeIn('slow');
        },

        showCategories:function(p_nCategoryPage, p_nGalleryReturnPage){
_xGallery.stopPlayMode();


if (p_nCategoryPage === undefined){p_nCategoryPage = 1;}
if (p_nGalleryReturnPage === undefined || isNaN(p_nGalleryReturnPage)) {p_nGalleryReturnPage = _xGallery._nGalleryReturnPage;} else {_xGallery._nGalleryReturnPage = p_nGalleryReturnPage}

BaseAjax._xArgs.data = 'a=ShowCategories';
BaseAjax._xArgs.data += '&id='+ _xGallery._sGalleryId;
BaseAjax._xArgs.data += '&categorypage='+ p_nCategoryPage;
BaseAjax._xArgs.data += '&galleryreturnpage='+ p_nGalleryReturnPage;
BaseAjax._xArgs.data += '&listtotal='+ _xGallery._nListTotal;
BaseAjax._xArgs.returnDiv = '#reception';
BaseAjax._xArgs.callBack =function(){_xGallery.showCategoriesCallback(p_nCategoryPage)};
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall();

        },

        showCategoriesCallback: function(p_nCategoryPage)  {
                _xGallery._nCategoryReturnPage = p_nCategoryPage;
                $('.gallery_category_browser').fadeIn('slow');
        },


        getCollectionsGallery:function(p_nImageToShow, p_nGalleryReturnPage){
_xGallery.stopPlayMode();

            $('#reception').empty().prepend('<div class="gallery_collection_class" >&nbsp;</div>');

BaseAjax._xArgs.data = 'a=GetCollectionsGallery';
BaseAjax._xArgs.data += '&season='+_xGallery._sGalleryId;
BaseAjax._xArgs.data += '&collectiontype='+_xGallery._sCollectionType;
BaseAjax._xArgs.data += '&imagetoshow='+ p_nImageToShow;
BaseAjax._xArgs.data += '&galleryreturnpage='+ p_nGalleryReturnPage;
BaseAjax._xArgs.callBack = function() {_xGallery.getCollectionsGalleryCallback();}
BaseAjax._xArgs.requestType = "GET";
BaseAjax._xArgs.returnDiv = '.gallery_collection_class';
BaseAjax.makeAjaxCall();
},

getCollectionsGalleryCallback:function(){

$('#gallery_collections').show().css('visibility', 'hidden');
_xGallery.initJscrollPane('.browser_list_view');

        },
        initJscrollPane:function(l_sSelector){
setTimeout(function(){
$(l_sSelector).jScrollPane({scrollbarWidth: 10, scrollbarMargin: 20, animateTo: true, showArrows: false});
$('#gallery_collections').hide().css('visibility', 'visible').fadeIn(200);
},100);
},
        startPlayMode:function(p_nGalleryPage)    {
//return false if already playing
if (_xGallery._bPlayMode == true){return false;}
if ($('#gallery_right ul#controls li a#play.stop_play').length) {p_nGalleryPage = 1}
_xGallery._bPlayMode = true;
_xGallery.goToGalleryItem(p_nGalleryPage, true);
        },
        stopPlayMode:function()    {
clearTimeout(_xGallery._xPlayTimeout);
_xGallery._bPlayMode = false;
        },


        toggleDetails:function() {


                        $('.details').children().children().removeClass('active');
                        if (_xGallery._sLastPage != null) {
                                _xGallery.goToGalleryItem(_xGallery._sLastPage);
                                _xGallery._sLastPage = null;
                        }

        },

        shareThis:function()    {

            var l_nOffsetTop = $('#gallery_share').offset().top - 150;
            object = SHARETHIS.addEntry({
title:'Hungry Gallery',
url:window.location
}, {button:false, offsetTop:l_nOffsetTop,onmouseover:false} );


//document.write('');
//Tie customized button to ShareThis button functionality.
var element = document.getElementById('gallery_share');
object.attachButton(element);

        },


        showOffset:function()   {

            alert($('#gallery_share').offset().top);

        },

        showDetail:function(p_xEl, p_sImageSrc, p_sLastPage, p_nWidth, p_nHeight) {

_xGallery._sLastPage = p_sLastPage;


$(p_xEl).siblings().children("img").removeClass("active");
$(p_xEl).children("img").addClass("active");

// make sure the center is visible for loading overlay
$('#gallery_center').css('visibility', 'visible');

BaseAjax._xArgs.data = 'a=ShowDetail';
BaseAjax._xArgs.data += '&imagesrc='+p_sImageSrc;
BaseAjax._xArgs.data += '&width='+p_nWidth;
BaseAjax._xArgs.data += '&height='+p_nHeight;
BaseAjax._xArgs.returnDiv = '#gallery_center';
BaseAjax._xArgs.callBack =function(){_xGallery.showDetailCallBack();}
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall();

        },
        showDetailCallBack:function()   {
l_oMainImage = $('#featured_gallery_image');

//wait until image is loaded before triggering visibility
// note: we dont ahve to anymore because the height width is in rel/rev
//        l_oMainImage.load(function(){
_xGallery.checkGallerySizeAndRescale();
l_oMainImage.css('visibility', 'visible').css('display', 'none').fadeIn('slow');
//        })

        },

        checkGallerySizeAndRescale:function(){
if (!this._nSidebarWidth.length) {this._nSidebarWidth = $('#gallery_left').width() + $('#gallery_right').width();}
available_width = $(window).width() - this._nSidebarWidth ;
l_oNewImageInfo = _xGallery.scaleImage($('#featured_gallery_image'), available_width, $('#overlay').height());
//update the gallery width to accomodate the new image size + sidebars
try  {
                            l_nNewWidth = this._nSidebarWidth + l_oNewImageInfo.width;
                            $('#gallery').width(l_nNewWidth);
                            x = l_oNewImageInfo.width;
                            // make the parent the same width for css to work
                            $('#gallery_center').width(x);
                            //resize the actual image
                            $('#featured_gallery_image').css('top',l_oNewImageInfo.offset.y);
                            $('#featured_gallery_image').height(l_oNewImageInfo.height);
                            $('#featured_gallery_image').width(l_oNewImageInfo.width);
                    } catch(e){}
       },

        scaleImage:function(p_oImage, p_nDestWidth, p_nDestHeight) {
// switched to rel and rev so we dont need to use onload
var thumbNail = _xGallery.calculateImageSize({
srcWidth: parseInt(p_oImage.attr('rel')),
srcHeight: parseInt(p_oImage.attr('rev')),
destWidth: p_nDestWidth,
destHeight: p_nDestHeight,
method: "fit"
});
return thumbNail;
        },

        calculateImageSize: function(p_xOptions) {
// declare some local variables
var ratioX, ratioY, scale, newWidth, newHeight;
// Check to make sure all the required variables were sent and pass validation
if (typeof p_xOptions.srcWidth !== "number" || typeof p_xOptions.srcHeight !== "number" || typeof p_xOptions.destWidth !== "number" || typeof p_xOptions.destHeight !== "number" || typeof p_xOptions.method !== "string") {
return;
}

// Grab scale ratios
ratioX = p_xOptions.destWidth / p_xOptions.srcWidth;
ratioY = p_xOptions.destHeight / p_xOptions.srcHeight;
// Determine which algorithm to use
if (p_xOptions.method === "fit") {
scale = ratioX < ratioY ? ratioX: ratioY;
} else if (p_xOptions.method === "fill") {
scale = ratioX > ratioY ? ratioX: ratioY;
}
// Set new dimensions
newWidth = parseInt(p_xOptions.srcWidth * scale, 10);
newHeight = parseInt(p_xOptions.srcHeight * scale, 10);
// Return the new dimensions, plus the offsets, and if the destination box
// is smaller or equal to the source image dimensions
return {
width: newWidth,
height: newHeight,
offset: {
x: parseInt((p_xOptions.destWidth - newWidth) / 2, 10),
y: parseInt((p_xOptions.destHeight - newHeight) / 2, 10)
},
fits: (p_xOptions.srcWidth >= p_xOptions.destWidth && p_xOptions.srcHeight >= p_xOptions.destHeight)
};
},
       //map party carousel
        mapGalleryKeys:function(p_nPreviousPage, p_nNextPage)  {
                    $(document).unbind("keydown");
                    $(document).keydown(function(e){
                        if (e.keyCode == 37) {
                            if (p_nPreviousPage !=0) _xGallery.goToGalleryItem(p_nPreviousPage);
                           return false;
                        }

                        if (e.keyCode == 39) {
                           if (p_nNextPage <= _xGallery._nListTotal) _xGallery.goToGalleryItem(p_nNextPage);
                           return false;
                        }
                    });

        },

        closeDialogNew:function(){

_xGallery.historyLoad('');
_xGallery.closeDialog();

},

        closeDialog:function(){
$(window).scrollTop(_xGallery._sScrollTop);
_xGallery._bInit=false;
_xGallery.stopPlayMode();
if (_xParties._bIsDetail)  {_xParties.mapPartyKeys();};
                        $("#overlay")
.fadeOut('fast', function() {
$("#gallery").remove();
});

}


}

       
