/*!
 * jQuery JavaScript Library v1.4.1
 * 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: Mon Jan 25 19:43:33 2010 -0500
 */
(function(z,v){function la(){if(!c.isReady){try{r.documentElement.doScroll("left")}catch(a){setTimeout(la,1);return}c.ready()}}function Ma(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,i){var j=a.length;if(typeof b==="object"){for(var n in b)X(a,n,b[n],f,e,d);return a}if(d!==v){f=!i&&f&&c.isFunction(d);for(n=0;n<j;n++)e(a[n],b,f?d.call(a[n],n,e(a[n],b)):d,i);return a}return j?
e(a[0],b):null}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function ma(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function na(a){var b,d=[],f=[],e=arguments,i,j,n,o,m,s,x=c.extend({},c.data(this,"events").live);if(!(a.button&&a.type==="click")){for(o in x){j=x[o];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete x[o]}i=c(a.target).closest(f,
a.currentTarget);m=0;for(s=i.length;m<s;m++)for(o in x){j=x[o];n=i[m].elem;f=null;if(i[m].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==n)d.push({elem:n,fn:j})}}m=0;for(s=d.length;m<s;m++){i=d[m];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}}function oa(a,b){return"live."+(a?a+".":"")+b.replace(/\./g,"`").replace(/ /g,"&")}function pa(a){return!a||!a.parentNode||a.parentNode.nodeType===
11}function qa(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 i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ra(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0&&(c.support.checkClone||!sa.test(a[0]))){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:r;f=b.createDocumentFragment();
c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(ta.concat.apply([],ta.slice(0,b)),function(){d[this]=a});return d}function ua(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)},Na=z.jQuery,Oa=z.$,r=z.document,S,Pa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Qa=/^.[^:#\[\.,]*$/,Ra=/\S/,Sa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Ta=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,O=navigator.userAgent,
va=false,P=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,Q=Array.prototype.slice,wa=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(typeof a==="string")if((d=Pa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:r;if(a=Ta.exec(a))if(c.isPlainObject(b)){a=[r.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ra([d[1]],
[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=r.getElementById(d[2])){if(b.id!==d[2])return S.find(a);this.length=1;this[0]=b}this.context=r;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=r;a=r.getElementsByTagName(a)}else return!b||b.jquery?(b||S).find(a):c(b).find(a);else if(c.isFunction(a))return S.ready(a);if(a.selector!==v){this.selector=a.selector;this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,
this)},selector:"",jquery:"1.4.1",length:0,size:function(){return this.length},toArray:function(){return Q.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length=0;ba.apply(this,a);return this},each:function(a,b){return c.each(this,
a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(r,c);else P&&P.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(Q.apply(this,arguments),"slice",Q.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,i,j,n;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(i in e){j=a[i];n=e[i];if(a!==n)if(f&&n&&(c.isPlainObject(n)||c.isArray(n))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(n)?[]:{};a[i]=c.extend(f,j,n)}else if(n!==v)a[i]=n}return a};c.extend({noConflict:function(a){z.$=
Oa;if(a)z.jQuery=Na;return c},isReady:false,ready:function(){if(!c.isReady){if(!r.body)return setTimeout(c.ready,13);c.isReady=true;if(P){for(var a,b=0;a=P[b++];)a.call(r,c);P=null}c.fn.triggerHandler&&c(r).triggerHandler("ready")}},bindReady:function(){if(!va){va=true;if(r.readyState==="complete")return c.ready();if(r.addEventListener){r.addEventListener("DOMContentLoaded",L,false);z.addEventListener("load",c.ready,false)}else if(r.attachEvent){r.attachEvent("onreadystatechange",L);z.attachEvent("onload",
c.ready);var a=false;try{a=z.frameElement==null}catch(b){}r.documentElement.doScroll&&a&&la()}}},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===v||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;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 z.JSON&&z.JSON.parse?z.JSON.parse(a):(new Function("return "+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Ra.test(a)){var b=r.getElementsByTagName("head")[0]||
r.documentElement,d=r.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(r.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,i=a.length,j=i===v||c.isFunction(a);if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=
a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Sa,"")},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]!==
v;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,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=v}else if(b&&!c.isFunction(b)){d=b;b=v}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:{}});O=c.uaMatch(O);if(O.browser){c.browser[O.browser]=true;c.browser.version=O.version}if(c.browser.webkit)c.browser.safari=true;if(wa)c.inArray=function(a,b){return wa.call(b,a)};S=c(r);if(r.addEventListener)L=function(){r.removeEventListener("DOMContentLoaded",
L,false);c.ready()};else if(r.attachEvent)L=function(){if(r.readyState==="complete"){r.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=r.documentElement,b=r.createElement("script"),d=r.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("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support=
{leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:r.createElement("select").appendChild(r.createElement("option")).selected,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};
b.type="text/javascript";try{b.appendChild(r.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b,a.firstChild);if(z[f]){c.support.scriptEval=true;delete z[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function n(){c.support.noCloneEvent=false;d.detachEvent("onclick",n)});d.cloneNode(true).fireEvent("onclick")}d=r.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=r.createDocumentFragment();a.appendChild(d.firstChild);
c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var n=r.createElement("div");n.style.width=n.style.paddingLeft="1px";r.body.appendChild(n);c.boxModel=c.support.boxModel=n.offsetWidth===2;r.body.removeChild(n).style.display="none"});a=function(n){var o=r.createElement("div");n="on"+n;var m=n in o;if(!m){o.setAttribute(n,"return;");m=typeof o[n]==="function"}return m};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=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(),Ua=0,xa={},Va={};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==z?xa:a;var f=a[G],e=c.cache;if(!b&&!f)return null;f||(f=++Ua);if(typeof b==="object"){a[G]=f;e=e[f]=c.extend(true,
{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Va:(e[f]={});if(d!==v){a[G]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa: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{try{delete a[G]}catch(i){a.removeAttribute&&a.removeAttribute(G)}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===v){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===v&&this.length)f=c.data(this[0],a);return f===v&&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===v)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 ya=/[\n\t]/g,ca=/\s+/,Wa=/\r/g,Xa=/href|src|style/,Ya=/(button|input)/i,Za=/(button|input|object|select|textarea)/i,$a=/^(a|area)$/i,za=/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(o){var m=
c(this);m.addClass(a.call(this,o,m.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 i=" "+e.className+" ",j=0,n=b.length;j<n;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+=" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=c(this);m.removeClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string"||a===v)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 i=(" "+e.className+" ").replace(ya," "),j=0,n=b.length;j<n;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}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 i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),n=b,o=
a.split(ca);e=o[i++];){n=f?n:!j.hasClass(e);j[n?"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(ya," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===v){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 i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(za.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Wa,"")}return v}var n=c.isFunction(a);return this.each(function(o){var m=c(this),s=a;if(this.nodeType===1){if(n)s=a.call(this,o,m.val());
if(typeof s==="number")s+="";if(c.isArray(s)&&za.test(this.type))this.checked=c.inArray(m.val(),s)>=0;else if(c.nodeName(this,"select")){var x=c.makeArray(s);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),x)>=0});if(!x.length)this.selectedIndex=-1}else this.value=s}})}});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 v;if(f&&b in c.attrFn)return c(a)[b](d);
f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==v;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Xa.test(b);if(b in a&&f&&!i){if(e){b==="type"&&Ya.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:Za.test(a.nodeName)||$a.test(a.nodeName)&&a.href?0:v;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&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?v:a}return c.style(a,b,d)}});var ab=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!==z&&!a.frameElement)a=z;if(!d.guid)d.guid=c.guid++;if(f!==v){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=
function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):v};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var n,o=0;n=b[o++];){var m=n.split(".");n=m.shift();if(o>1){d=c.proxy(d);if(f!==v)d.data=f}d.type=m.slice(0).sort().join(".");var s=e[n],x=this.special[n]||{};if(!s){s=e[n]={};if(!x.setup||x.setup.call(a,f,m,d)===false)if(a.addEventListener)a.addEventListener(n,i,false);else a.attachEvent&&a.attachEvent("on"+n,i)}if(x.add)if((m=x.add.call(a,
d,f,m,s))&&c.isFunction(m)){m.guid=m.guid||d.guid;m.data=m.data||d.data;m.type=m.type||d.type;d=m}s[d.guid]=d;this.global[n]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===v||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/);for(var n=0;i=b[n++];){var o=i.split(".");i=o.shift();var m=!o.length,s=c.map(o.slice(0).sort(),ab);s=new RegExp("(^|\\.)"+
s.join("\\.(?:.*\\.)?")+"(\\.|$)");var x=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var A in f[i])if(m||s.test(f[i][A].type))delete f[i][A];x.remove&&x.remove.call(a,o,j);for(e in f[i])break;if(!e){if(!x.teardown||x.teardown.call(a,o)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(A=c.data(a,"handle"))A.elem=null;c.removeData(a,
"events");c.removeData(a,"handle")}}}},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();this.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 v;a.result=v;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(i){}if(!a.isPropagationStopped()&&f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){d=a.target;var j;if(!(c.nodeName(d,"a")&&e==="click")&&!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){try{if(d[e]){if(j=d["on"+e])d["on"+e]=null;this.triggered=true;d[e]()}}catch(n){}if(j)d["on"+e]=j;this.triggered=false}}},handle:function(a){var b,
d;a=arguments[0]=c.event.fix(a||z.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==v){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||r;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=r.documentElement;d=r.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!==v)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,b){c.extend(a,b||{});a.guid+=b.selector+b.live;b.liveProxy=a;c.event.add(this,b.live,na,b)},remove:function(a){if(a.length){var b=
0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],na)}},special:{}},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}}}};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 Aa=function(a){for(var b=
a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ba=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?Ba:Aa,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ba:Aa)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return ma("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return ma("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,
"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var da=/textarea|input|select/i;function Ca(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}function ea(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Ca(d);if(a.type!=="focusout"||
d.type!=="radio")c.data(d,"_change_data",e);if(!(f===v||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}}c.event.special.change={filters:{focusout:ea,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ea.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 ea.call(this,a)},beforeactivate:function(a){a=
a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Ca(a))}},setup:function(a,b,d){for(var f in T)c.event.add(this,f+".specialChange."+d.guid,T[f]);return da.test(this.nodeName)},remove:function(a,b){for(var d in T)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),T[d]);return da.test(this.nodeName)}};var T=c.event.special.change.filters}r.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 i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){e=f;f=v}var j=b==="one"?c.proxy(e,function(n){c(this).unbind(n,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,
b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},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)}});c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e){var i,j=0;if(c.isFunction(f)){e=f;f=v}for(d=(d||"").split(/\s+/);(i=d[j++])!=null;){i=i==="focus"?"focusin":i==="blur"?"focusout":i==="hover"?d.push("mouseleave")&&"mouseenter":i;b==="live"?c(this.context).bind(oa(i,this.selector),{data:f,selector:this.selector,
live:i},e):c(this.context).unbind(oa(i,this.selector),e?{guid:e.guid+this.selector+i}:null)}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});z.attachEvent&&!z.addEventListener&&z.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="",k,l=0;g[l];l++){k=g[l];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===k){y=l[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=k;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}l[q]=y}}}function d(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===
k){y=l[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=k;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(o.filter(h,[t]).length>0){y=t;break}}t=t[g]}l[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,i=Object.prototype.toString,j=false,n=true;[0,0].sort(function(){n=false;return 0});var o=function(g,h,k,l){k=k||[];var q=h=h||r;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||
typeof g!=="string")return k;for(var p=[],u,t,y,R,H=true,M=w(h),I=g;(f.exec(""),u=f.exec(I))!==null;){I=u[3];p.push(u[1]);if(u[2]){R=u[3];break}}if(p.length>1&&s.exec(g))if(p.length===2&&m.relative[p[0]])t=fa(p[0]+p[1],h);else for(t=m.relative[p[0]]?[h]:o(p.shift(),h);p.length;){g=p.shift();if(m.relative[g])g+=p.shift();t=fa(g,t)}else{if(!l&&p.length>1&&h.nodeType===9&&!M&&m.match.ID.test(p[0])&&!m.match.ID.test(p[p.length-1])){u=o.find(p.shift(),h,M);h=u.expr?o.filter(u.expr,u.set)[0]:u.set[0]}if(h){u=
l?{expr:p.pop(),set:A(l)}:o.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=u.expr?o.filter(u.expr,u.set):u.set;if(p.length>0)y=A(t);else H=false;for(;p.length;){var D=p.pop();u=D;if(m.relative[D])u=p.pop();else D="";if(u==null)u=h;m.relative[D](y,u,M)}}else y=[]}y||(y=t);y||o.error(D||g);if(i.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])))k.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&
y[g].nodeType===1&&k.push(t[g]);else k.push.apply(k,y);else A(y,k);if(R){o(R,q,k,l);o.uniqueSort(k)}return k};o.uniqueSort=function(g){if(C){j=n;g.sort(C);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};o.matches=function(g,h){return o(g,null,null,h)};o.find=function(g,h,k){var l,q;if(!g)return[];for(var p=0,u=m.order.length;p<u;p++){var t=m.order[p];if(q=m.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");l=m.find[t](q,
h,k);if(l!=null){g=g.replace(m.match[t],"");break}}}}l||(l=h.getElementsByTagName("*"));return{set:l,expr:g}};o.filter=function(g,h,k,l){for(var q=g,p=[],u=h,t,y,R=h&&h[0]&&w(h[0]);g&&h.length;){for(var H in m.filter)if((t=m.leftMatch[H].exec(g))!=null&&t[2]){var M=m.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(u===p)p=[];if(m.preFilter[H])if(t=m.preFilter[H](t,u,k,p,l,R)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=u[U])!=null;U++)if(D){I=M(D,t,U,u);var Da=
l^!!I;if(k&&I!=null)if(Da)y=true;else u[U]=false;else if(Da){p.push(D);y=true}}if(I!==v){k||(u=p);g=g.replace(m.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)o.error(g);else break;q=g}return u};o.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var m=o.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 k=typeof h==="string",l=k&&!/\W/.test(h);k=k&&!l;if(l)h=h.toLowerCase();l=0;for(var q=g.length,
p;l<q;l++)if(p=g[l]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[l]=k||p&&p.nodeName.toLowerCase()===h?p||false:p===h}k&&o.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var l=0,q=g.length;l<q;l++){var p=g[l];if(p){k=p.parentNode;g[l]=k.nodeName.toLowerCase()===h?k:false}}}else{l=0;for(q=g.length;l<q;l++)if(p=g[l])g[l]=k?p.parentNode:p.parentNode===h;k&&o.filter(h,g,true)}},"":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=
h=h.toLowerCase();q=b}q("parentNode",h,l,g,p,k)},"~":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,l,g,p,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[];h=h.getElementsByName(g[1]);for(var l=0,q=h.length;l<q;l++)h[l].getAttribute("name")===g[1]&&k.push(h[l]);return k.length===0?null:k}},
TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,l,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var u;(u=h[p])!=null;p++)if(u)if(q^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||l.push(u);else if(k)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,k,l,q,p){h=g[1].replace(/\\/g,"");if(!p&&m.attrMap[h])g[1]=m.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,l,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=o(g[3],null,null,h);else{g=o.filter(g[3],h,k,true^q);k||l.push.apply(l,g);return false}else if(m.match.POS.test(g[0])||m.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,k){return!!o(k[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,k,l){return h===l.length-1},even:function(g,h){return h%2===
0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,l){var q=h[1],p=m.filters[q];if(p)return p(g,k,h,l);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=h[3];k=0;for(l=h.length;k<l;k++)if(h[k]===g)return false;return true}else o.error("Syntax error, unrecognized expression: "+
q)},CHILD:function(g,h){var k=h[1],l=g;switch(k){case "only":case "first":for(;l=l.previousSibling;)if(l.nodeType===1)return false;if(k==="first")return true;l=g;case "last":for(;l=l.nextSibling;)if(l.nodeType===1)return false;return true;case "nth":k=h[2];var q=h[3];if(k===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var u=0;for(l=p.firstChild;l;l=l.nextSibling)if(l.nodeType===1)l.nodeIndex=++u;p.sizcache=h}g=g.nodeIndex-q;return k===0?g===0:g%k===0&&g/k>=
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 k=h[1];g=m.attrHandle[k]?m.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var l=h[2];h=h[4];return g==null?l==="!=":l==="="?k===h:l==="*="?k.indexOf(h)>=0:l==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:l==="!="?k!==h:l==="^="?
k.indexOf(h)===0:l==="$="?k.substr(k.length-h.length)===h:l==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,l){var q=m.setFilters[h[2]];if(q)return q(g,k,h,l)}}},s=m.match.POS;for(var x in m.match){m.match[x]=new RegExp(m.match[x].source+/(?![^\[]*\])(?![^\(]*\))/.source);m.leftMatch[x]=new RegExp(/(^(?:.|\r|\n)*?)/.source+m.match[x].source.replace(/\\(\d+)/g,function(g,h){return"\\"+(h-0+1)}))}var A=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(r.documentElement.childNodes,0)}catch(B){A=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,l=g.length;k<l;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var C;if(r.documentElement.compareDocumentPosition)C=function(g,h){if(!g.compareDocumentPosition||!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===
h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in r.documentElement)C=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(r.createRange)C=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),l=h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);l.setStart(h,0);l.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,
l);if(g===0)j=true;return g};(function(){var g=r.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=r.documentElement;k.insertBefore(g,k.firstChild);if(r.getElementById(h)){m.find.ID=function(l,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(l[1]))?q.id===l[1]||typeof q.getAttributeNode!=="undefined"&&q.getAttributeNode("id").nodeValue===l[1]?[q]:v:[]};m.filter.ID=function(l,q){var p=typeof l.getAttributeNode!=="undefined"&&l.getAttributeNode("id");
return l.nodeType===1&&p&&p.nodeValue===q}}k.removeChild(g);k=g=null})();(function(){var g=r.createElement("div");g.appendChild(r.createComment(""));if(g.getElementsByTagName("*").length>0)m.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var l=0;k[l];l++)k[l].nodeType===1&&h.push(k[l]);k=h}return k};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")m.attrHandle.href=function(h){return h.getAttribute("href",
2)};g=null})();r.querySelectorAll&&function(){var g=o,h=r.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){o=function(l,q,p,u){q=q||r;if(!u&&q.nodeType===9&&!w(q))try{return A(q.querySelectorAll(l),p)}catch(t){}return g(l,q,p,u)};for(var k in g)o[k]=g[k];h=null}}();(function(){var g=r.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){m.order.splice(1,0,"CLASS");m.find.CLASS=function(h,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(h[1])};g=null}}})();var E=r.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g,h){return g!==h&&(g.contains?g.contains(h):true)},w=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},fa=function(g,h){var k=[],
l="",q;for(h=h.nodeType?[h]:h;q=m.match.PSEUDO.exec(g);){l+=q[0];g=g.replace(m.match.PSEUDO,"")}g=m.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)o(g,h[q],k);return o.filter(l,k)};c.find=o;c.expr=o.selectors;c.expr[":"]=c.expr.filters;c.unique=o.uniqueSort;c.getText=a;c.isXMLDoc=w;c.contains=E})();var bb=/Until$/,cb=/^(?:parents|prevUntil|prevAll)/,db=/,/;Q=Array.prototype.slice;var Ea=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,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(Qa.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 i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,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(Ea(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ea(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,i={},j;if(f&&a.length){e=0;for(var n=a.length;e<n;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>
-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var o=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(m,s){for(;s&&s.ownerDocument&&s!==b;){if(o?o.index(s)>-1:c(s).is(a))return s;s=s.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(pa(a[0])||pa(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);bb.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||db.test(f))&&cb.test(a))e=e.reverse();return this.pushStack(e,a,Q.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===v||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 Fa=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ga=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,sa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ia=function(a,b,d){return eb.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!==v)return this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(a));return c.getText(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}},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(Fa,"").replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){qa(this,b);qa(this.find("*"),b.find("*"))}return b},html:function(a){if(a===v)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Fa,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(Ha.exec(a)||
["",""])[1].toLowerCase()]){a=a.replace(Ga,Ia);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 i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):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))});else 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(s){return c.nodeName(s,"table")?s.getElementsByTagName("tbody")[0]||s.appendChild(s.ownerDocument.createElement("tbody")):s}var e,i,j=a[0],n=[];if(!c.support.checkClone&&arguments.length===3&&typeof j===
"string"&&sa.test(j))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(j))return this.each(function(s){var x=c(this);a[0]=j.call(this,s,b?x.html():v);x.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ra(a,this,n);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var o=0,m=this.length;o<m;o++)d.call(b?f(this[o],i):this[o],e.cacheable||this.length>1||o>0?e.fragment.cloneNode(true):e.fragment)}n&&c.each(n,
Ma)}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);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){c.cleanData(this.getElementsByTagName("*"));c.cleanData([this])}this.parentNode&&
this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&c.cleanData(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}},function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||r;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||r;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j===
"string"){j=j.replace(Ga,Ia);var n=(Ha.exec(j)||["",""])[1].toLowerCase(),o=F[n]||F._default,m=o[0];i=b.createElement("div");for(i.innerHTML=o[1]+j+o[2];m--;)i=i.lastChild;if(!c.support.tbody){m=fb.test(j);n=n==="table"&&!m?i.firstChild&&i.firstChild.childNodes:o[1]==="<table>"&&!m?i.childNodes:[];for(o=n.length-1;o>=0;--o)c.nodeName(n[o],"tbody")&&!n[o].childNodes.length&&n[o].parentNode.removeChild(n[o])}!c.support.leadingWhitespace&&V.test(j)&&i.insertBefore(b.createTextNode(V.exec(j)[0]),i.firstChild);
j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()==="text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e},cleanData:function(a){for(var b=0,d;(d=a[b])!=null;b++){c.event.remove(d);c.removeData(d)}}});var hb=/z-?index|font-?weight|opacity|zoom|line-?height/i,
Ja=/alpha\([^)]*\)/,Ka=/opacity=([^)]*)/,ga=/float/i,ha=/-([a-z])/ig,ib=/([A-Z])/g,jb=/^-?\d+(?:px)?$/i,kb=/^-?\d/,lb={position:"absolute",visibility:"hidden",display:"block"},mb=["Left","Right"],nb=["Top","Bottom"],ob=r.defaultView&&r.defaultView.getComputedStyle,La=c.support.cssFloat?"cssFloat":"styleFloat",ia=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===v)return c.curCSS(d,f);if(typeof e==="number"&&!hb.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 v;if((b==="width"||b==="height")&&parseFloat(d)<0)d=v;var f=a.style||a,e=d!==v;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=Ja.test(a)?a.replace(Ja,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ka.exec(f.filter)[1])/100+"":""}if(ga.test(b))b=La;b=b.replace(ha,ia);if(e)f[b]=d;return f[b]},css:function(a,
b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?mb:nb;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,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?j():c.swap(a,lb,j);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=Ka.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ga.test(b))b=La;if(!d&&e&&e[b])f=e[b];else if(ob){if(ga.test(b))b="float";b=b.replace(ib,"-$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(ha,ia);f=a.currentStyle[b]||a.currentStyle[d];if(!jb.test(f)&&kb.test(f)){b=e.left;var i=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=i}}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 pb=
J(),qb=/<script(.|\s)*?\/script>/gi,rb=/select|textarea/i,sb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ja=/\?/,tb=/(\?|&)_=.*?(&|$)/,ub=/^(\w+:)?\/\/([^\/?#]+)/,vb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(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 i=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(j,n){if(n==="success"||n==="notmodified")i.html(e?c("<div />").append(j.responseText.replace(qb,"")).find(e):j.responseText);d&&i.each(d,[j.responseText,n,j])}});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||rb.test(this.nodeName)||sb.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:z.XMLHttpRequest&&(z.location.protocol!=="file:"||!z.ActiveXObject)?function(){return new z.XMLHttpRequest}:
function(){try{return new z.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(o,n,j,w);e.global&&f("ajaxSuccess",[w,e])}function d(){e.complete&&e.complete.call(o,w,j);e.global&&f("ajaxComplete",[w,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),i,j,n,o=a&&a.context||e,m=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(m==="GET")N.test(e.url)||(e.url+=(ja.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))){i=e.jsonpCallback||"jsonp"+pb++;if(e.data)e.data=(e.data+"").replace(N,"="+i+"$1");e.url=e.url.replace(N,"="+i+"$1");e.dataType="script";z[i]=z[i]||function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&m==="GET"){var s=J(),x=e.url.replace(tb,"$1_="+s+"$2");e.url=x+(x===e.url?(ja.test(e.url)?"&":"?")+"_="+s:"")}if(e.data&&m==="GET")e.url+=(ja.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&
c.event.trigger("ajaxStart");s=(s=ub.exec(e.url))&&(s[1]&&s[1]!==location.protocol||s[2]!==location.host);if(e.dataType==="script"&&m==="GET"&&s){var A=r.getElementsByTagName("head")[0]||r.documentElement,B=r.createElement("script");B.src=e.url;if(e.scriptCharset)B.charset=e.scriptCharset;if(!i){var C=false;B.onload=B.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;b();d();B.onload=B.onreadystatechange=null;A&&B.parentNode&&
A.removeChild(B)}}}A.insertBefore(B,A.firstChild);return v}var E=false,w=e.xhr();if(w){e.username?w.open(m,e.url,e.async,e.username,e.password):w.open(m,e.url,e.async);try{if(e.data||a&&a.contentType)w.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&w.setRequestHeader("If-None-Match",c.etag[e.url])}s||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",
e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(fa){}if(e.beforeSend&&e.beforeSend.call(o,w,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");w.abort();return false}e.global&&f("ajaxSend",[w,e]);var g=w.onreadystatechange=function(q){if(!w||w.readyState===0||q==="abort"){E||d();E=true;if(w)w.onreadystatechange=c.noop}else if(!E&&w&&(w.readyState===4||q==="timeout")){E=true;w.onreadystatechange=c.noop;j=q==="timeout"?"timeout":!c.httpSuccess(w)?
"error":e.ifModified&&c.httpNotModified(w,e.url)?"notmodified":"success";var p;if(j==="success")try{n=c.httpData(w,e.dataType,e)}catch(u){j="parsererror";p=u}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,w,j,p);d();q==="timeout"&&w.abort();if(e.async)w=null}};try{var h=w.abort;w.abort=function(){w&&h.call(w);g("abort")}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){w&&!E&&g("timeout")},e.timeout);try{w.send(m==="POST"||m==="PUT"||m==="DELETE"?e.data:null)}catch(l){c.handleError(e,
w,null,l);d()}e.async||g();return w}},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(j,n){if(c.isArray(n))c.each(n,
function(o,m){b?f(j,m):d(j+"["+(typeof m==="object"||c.isArray(m)?o:"")+"]",m)});else!b&&n!=null&&typeof n==="object"?c.each(n,function(o,m){d(j+"["+o+"]",m)}):f(j,n)}function f(j,n){n=c.isFunction(n)?n():n;e[e.length]=encodeURIComponent(j)+"="+encodeURIComponent(n)}var e=[];if(b===v)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var i in a)d(i,a[i]);return e.join("&").replace(vb,"+")}});var ka={},wb=/toggle|show|hide/,xb=/^([+-]=)?([\d+-.]+)(.*)$/,
W,ta=[["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(ka[d])f=ka[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();
ka[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 i=c.extend({},e),j,n=this.nodeType===1&&c(this).is(":hidden"),
o=this;for(j in a){var m=j.replace(ha,ia);if(j!==m){a[m]=a[j];delete a[j];j=m}if(a[j]==="hide"&&n||a[j]==="show"&&!n)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(s,x){var A=new c.fx(o,i,s);if(wb.test(x))A[x==="toggle"?n?"show":"hide":x](a);
else{var B=xb.exec(x),C=A.cur(true)||0;if(B){x=parseFloat(B[2]);var E=B[3]||"px";if(E!=="px"){o.style[s]=(x||1)+E;C=(x||1)/A.cur(true)*C;o.style[s]=C+E}if(B[1])x=(B[1]==="-="?-1:1)*x+C;A.custom(C,x,E)}else A.custom(C,x,"")}});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(i){return e.step(i)}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 r.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(s){c.offset.setOffset(this,a,s)});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,i,j=e.documentElement,n=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var o=b.offsetTop,m=b.offsetLeft;(b=b.parentNode)&&b!==n&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;o-=b.scrollTop;m-=b.scrollLeft;if(b===d){o+=b.offsetTop;m+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){o+=parseFloat(i.borderTopWidth)||
0;m+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){o+=parseFloat(i.borderTopWidth)||0;m+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){o+=n.offsetTop;m+=n.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){o+=Math.max(j.scrollTop,n.scrollTop);m+=Math.max(j.scrollLeft,n.scrollLeft)}return{top:o,left:m}};c.offset={initialize:function(){var a=r.body,b=r.createElement("div"),
d,f,e,i=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!==i;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(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left-
e.left+j};"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||r.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],i;if(!e)return null;if(f!==v)return this.each(function(){if(i=ua(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=ua(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.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(i){var j=c(this);j[d](f.call(this,i,j[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===v?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});z.jQuery=z.$=c})(window);


/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);

/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 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.
 *
 * $LastChangedDate: 2007-12-14 23:57:10 -0600 (Fri, 14 Dec 2007) $
 * $Rev: 4163 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */
(function($){$.event.special.mousewheel={setup:function(){var handler=$.event.special.mousewheel.handler;if($.browser.mozilla)$(this).bind('mousemove.mousewheel',function(event){$.data(this,'mwcursorposdata',{pageX:event.pageX,pageY:event.pageY,clientX:event.clientX,clientY:event.clientY});});if(this.addEventListener)this.addEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),handler,false);else
this.onmousewheel=handler;},teardown:function(){var handler=$.event.special.mousewheel.handler;$(this).unbind('mousemove.mousewheel');if(this.removeEventListener)this.removeEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),handler,false);else
this.onmousewheel=function(){};$.removeData(this,'mwcursorposdata');},handler:function(event){var args=Array.prototype.slice.call(arguments,1);event=$.event.fix(event||window.event);$.extend(event,$.data(this,'mwcursorposdata')||{});var delta=0,returnValue=true;if(event.wheelDelta)delta=event.wheelDelta/120;if(event.detail)delta=-event.detail/3;if($.browser.opera)delta=-event.wheelDelta;event.data=event.data||{};event.type="mousewheel";args.unshift(delta);args.unshift(event);return $.event.handle.apply(this,args);}};$.fn.extend({mousewheel:function(fn){return fn?this.bind("mousewheel",fn):this.trigger("mousewheel");},unmousewheel:function(fn){return this.unbind("mousewheel",fn);}});})(jQuery);

/**
 * jQuery.ScrollTo
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.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.
 * Date: 2/19/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * Tested with jQuery 1.2.1. On FF 2.0.0.11, IE 6, Opera 9.22 and Safari 3 beta. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.3.3
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *  The different options for target are:
 *- A number position (will be applied to all axes).
 *- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *- A jQuery/DOM element ( logically, child of the element to scroll )
 *- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object} settings Hash of settings, optional.
 * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 * @option {Number} duration The OVERALL length of the animation.
 * @option {String} easing The easing method for the animation.
 * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 * @option {Function} onAfter Function to be called after the scrolling ends. 
 * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example $('div').scrollTo( 340 );
 *
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *alert('scrolled!!');   
 *}});
 *
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { offset:-20 } );
 *
 * Notes:
 *  - jQuery.scrollTo will make the whole window scroll, it accepts the same arguments as jQuery.fn.scrollTo.
 *- If you are interested in animated anchor navigation, check http://jquery.com/plugins/project/LocalScroll.
 *- The options margin, offset and over are ignored, if the target is not a jQuery object or a DOM element.
 *- The option 'queue' won't be taken into account, if only 1 axis is given.
 */
;(function( $ ){

var $scrollTo = $.scrollTo = function( target, duration, settings ){
$scrollTo.window().scrollTo( target, duration, settings );
};

$scrollTo.defaults = {
axis:'y',
duration:1
};

//returns the element that needs to be animated to scroll the window
$scrollTo.window = function(){
return $( $.browser.safari ? 'body' : 'html' );
};

$.fn.scrollTo = function( target, duration, settings ){
if( typeof duration == 'object' ){
settings = duration;
duration = 0;
}
settings = $.extend( {}, $scrollTo.defaults, settings );
duration = duration || settings.speed || settings.duration;//speed is still recognized for backwards compatibility
settings.queue = settings.queue && settings.axis.length > 1;//make sure the settings are given right
if( settings.queue )
duration /= 2;//let's keep the overall speed, the same.
settings.offset = both( settings.offset );
settings.over = both( settings.over );

return this.each(function(){
var elem = this, $elem = $(elem),
t = target, toff, attr = {},
win = $elem.is('html,body');
switch( typeof t ){
case 'number'://will pass the regex
case 'string':
if( /^([+-]=)?\d+(px)?$/.test(t) ){
t = both( t );
break;//we are done
}
t = $(t,this);// relative selector, no break!
case 'object':
if( t.is || t.style )//DOM/jQuery
toff = (t = $(t)).offset();//get the real position of the target 
}
$.each( settings.axis.split(''), function( i, axis ){
var Pos= axis == 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
act = elem[key],
Dim = axis == 'x' ? 'Width' : 'Height',
dim = Dim.toLowerCase();

if( toff ){//jQuery/DOM
attr[key] = toff[pos] + ( win ? 0 : act - $elem.offset()[pos] );

if( settings.margin ){//if it's a dom element, reduce the margin
attr[key] -= parseInt(t.css('margin'+Pos)) || 0;
attr[key] -= parseInt(t.css('border'+Pos+'Width')) || 0;
}

attr[key] += settings.offset[pos] || 0;//add/deduct the offset

if( settings.over[pos] )//scroll to a fraction of its width/height
attr[key] += t[dim]() * settings.over[pos];
}else
attr[key] = t[pos];//remove the unnecesary 'px'

if( /^\d+$/.test(attr[key]) )//number or 'number'
attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );//check the limits

if( !i && settings.queue ){//queueing each axis is required
if( act != attr[key] )//don't waste time animating, if there's no need.
animate( settings.onAfterFirst );//intermediate animation
delete attr[key];//don't animate this axis again in the next iteration.
}
});
animate( settings.onAfter );

function animate( callback ){
$elem.animate( attr, duration, settings.easing, callback && function(){
callback.call(this, target);
});
};
function max( Dim ){
var el = win ? $.browser.opera ? document.body : document.documentElement : elem;
return el['scroll'+Dim] - el['client'+Dim];
};
});
};

function both( val ){
return typeof val == 'object' ? val : { top:val, left:val };
};

})( jQuery );

/* 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: jScrollPane.js 87 2009-10-12 10:44:17Z kelvin.luck $
 */

/**
 * 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
 * @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;

if ($(this).parent().is('.jScrollPaneContainer')) {
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();
var $container = $('<div></div>')
.attr({'className':'jScrollPaneContainer'})
.css(
{
'height':paneHeight+'px', 
'width':paneWidth+'px'
}
);
if (settings.enableKeyboardNavigation) {
$container.attr(
'tabindex', 
settings.tabIndex
);
}
$this.wrap($container);
// 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;

if (percentInView < .99) {
var $container = $this.parent();
$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);
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") {
$e = $(pos, $this);
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;

while ($e[0] != $this[0]) {
eleTop += $e.position().top;
$e = $e.offsetParent();
}

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 (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
};

// 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);

/*
 * 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);
}
}
});




/**
 * 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;
    }
};

(function(){var a=this;var c=a._;var b=a._={};if(typeof exports!=="undefined"){b=exports}b.VERSION="0.3.3";b.each=function(n,k,j){var f=0;try{if(n.forEach){n.forEach(k,j)}else{if(n.length){for(var h=0,d=n.length;h<d;h++){k.call(j,n[h],h,n)}}else{if(n.each){n.each(function(e){k.call(j,e,f++,n)})}else{for(var g in n){if(Object.prototype.hasOwnProperty.call(n,g)){k.call(j,n[g],g,n)}}}}}}catch(m){if(m!="__break__"){throw m}}return n};b.map=function(g,f,e){if(g&&g.map){return g.map(f,e)}var d=[];b.each(g,function(k,h,j){d.push(f.call(e,k,h,j))});return d};b.reduce=function(g,d,f,e){if(g&&g.reduce){return g.reduce(b.bind(f,e),d)}b.each(g,function(k,h,j){d=f.call(e,d,k,h,j)});return d};b.reduceRight=function(g,d,f,e){if(g&&g.reduceRight){return g.reduceRight(b.bind(f,e),d)}var h=b.clone(b.toArray(g)).reverse();b.each(h,function(k,j){d=f.call(e,d,k,j,g)});return d};b.detect=function(g,f,e){var d;b.each(g,function(k,h,j){if(f.call(e,k,h,j)){d=k;throw"__break__"}});return d};b.select=function(g,f,e){if(g.filter){return g.filter(f,e)}var d=[];b.each(g,function(k,h,j){f.call(e,k,h,j)&&d.push(k)});return d};b.reject=function(g,f,e){var d=[];b.each(g,function(k,h,j){!f.call(e,k,h,j)&&d.push(k)});return d};b.all=function(g,f,e){f=f||b.identity;if(g.every){return g.every(f,e)}var d=true;b.each(g,function(k,h,j){if(!(d=d&&f.call(e,k,h,j))){throw"__break__"}});return d};b.any=function(g,f,e){f=f||b.identity;if(g.some){return g.some(f,e)}var d=false;b.each(g,function(k,h,j){if(d=f.call(e,k,h,j)){throw"__break__"}});return d};b.include=function(f,e){if(b.isArray(f)){return b.indexOf(f,e)!=-1}var d=false;b.each(f,function(g){if(d=g===e){throw"__break__"}});return d};b.invoke=function(e,f){var d=b.toArray(arguments).slice(2);return b.map(e,function(g){return(f?g[f]:g).apply(g,d)})};b.pluck=function(e,d){return b.map(e,function(f){return f[d]})};b.max=function(g,f,e){if(!f&&b.isArray(g)){return Math.max.apply(Math,g)}var d={computed:-Infinity};b.each(g,function(m,h,k){var j=f?f.call(e,m,h,k):m;j>=d.computed&&(d={value:m,computed:j})});return d.value};b.min=function(g,f,e){if(!f&&b.isArray(g)){return Math.min.apply(Math,g)}var d={computed:Infinity};b.each(g,function(m,h,k){var j=f?f.call(e,m,h,k):m;j<d.computed&&(d={value:m,computed:j})});return d.value};b.sortBy=function(f,e,d){return b.pluck(b.map(f,function(j,g,h){return{value:j,criteria:e.call(d,j,g,h)}}).sort(function(k,j){var h=k.criteria,g=j.criteria;return h<g?-1:h>g?1:0}),"value")};b.sortedIndex=function(j,h,f){f=f||b.identity;var d=0,g=j.length;while(d<g){var e=(d+g)>>1;f(j[e])<f(h)?d=e+1:g=e}return d};b.toArray=function(d){if(!d){return[]}if(b.isArray(d)){return d}return b.map(d,function(e){return e})};b.size=function(d){return b.toArray(d).length};b.first=function(d){return d[0]};b.last=function(d){return d[d.length-1]};b.compact=function(d){return b.select(d,function(e){return !!e})};b.flatten=function(d){return b.reduce(d,[],function(e,f){if(b.isArray(f)){return e.concat(b.flatten(f))}e.push(f);return e})};b.without=function(e){var d=e.slice.call(arguments,0);return b.select(e,function(f){return !b.include(d,f)})};b.uniq=function(e,d){return b.reduce(e,[],function(f,h,g){if(0==g||(d?b.last(f)!=h:!b.include(f,h))){f.push(h)}return f})};b.intersect=function(e){var d=b.toArray(arguments).slice(1);return b.select(b.uniq(e),function(f){return b.all(d,function(g){return b.indexOf(g,f)>=0})})};b.zip=function(){var d=b.toArray(arguments);var g=b.max(b.pluck(d,"length"));var f=new Array(g);for(var e=0;e<g;e++){f[e]=b.pluck(d,String(e))}return f};b.indexOf=function(e,d){if(e.indexOf){return e.indexOf(d)}for(i=0,l=e.length;i<l;i++){if(e[i]===d){return i}}return -1};b.lastIndexOf=function(f,e){if(f.lastIndexOf){return f.lastIndexOf(e)}var d=f.length;while(d--){if(f[d]===e){return d}}return -1};b.bind=function(f,e){if(!e){return f}var d=b.toArray(arguments).slice(2);return function(){var g=d.concat(b.toArray(arguments));return f.apply(e,g)}};b.bindAll=function(){var d=b.toArray(arguments);var e=d.pop();b.each(d,function(f){e[f]=b.bind(e[f],e)})};b.delay=function(e,f){var d=b.toArray(arguments).slice(2);return setTimeout(function(){return e.apply(e,d)},f)};b.defer=function(d){return b.delay.apply(b,[d,1].concat(b.toArray(arguments).slice(1)))};b.wrap=function(d,e){return function(){var f=[d].concat(b.toArray(arguments));return e.apply(e,f)}};b.compose=function(){var d=b.toArray(arguments);return function(){for(var e=d.length-1;e>=0;e--){arguments=[d[e].apply(this,arguments)]}return arguments[0]}};b.keys=function(d){return b.map(d,function(f,e){return e})};b.values=function(d){return b.map(d,b.identity)};b.extend=function(d,f){for(var e in f){d[e]=f[e]}return d};b.clone=function(d){if(b.isArray(d)){return d.slice(0)}return b.extend({},d)};b.isEqual=function(e,d){if(e===d){return true}var h=typeof(e),k=typeof(d);if(h!=k){return false}if(e==d){return true}if(e.isEqual){return e.isEqual(d)}if(h!=="object"){return false}var f=b.keys(e),j=b.keys(d);if(f.length!=j.length){return false}for(var g in e){if(!b.isEqual(e[g],d[g])){return false}}return true};b.isElement=function(d){return !!(d&&d.nodeType==1)};b.isArray=function(d){return Object.prototype.toString.call(d)=="[object Array]"};b.isFunction=function(d){return Object.prototype.toString.call(d)=="[object Function]"};b.isUndefined=function(d){return typeof d=="undefined"};b.noConflict=function(){a._=c;return this};b.identity=function(d){return d};b.uniqueId=function(d){var e=this._idCounter=(this._idCounter||0)+1;return d?d+e:e};b.template=function(f,e){var d=new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+f.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return e?d(e):d};b.forEach=b.each;b.foldl=b.inject=b.reduce;b.foldr=b.reduceRight;b.filter=b.select;b.every=b.all;b.some=b.any})();

/*! Copyright (c) 2008 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.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {

$.extend($.fn, {
livequery: function(type, fn, fn2) {
var self = this, q;

// Handle different call patterns
if ($.isFunction(type))
fn2 = fn, fn = type, type = undefined;

// See if Live Query already exists
$.each( $.livequery.queries, function(i, query) {
if ( self.selector == query.selector && self.context == query.context &&
type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
// Found the query, exit the each loop
return (q = query) && false;
});

// Create new Live Query if it wasn't found
q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

// Make sure it is running
q.stopped = false;

// Run it immediately for the first time
q.run();

// Contnue the chain
return this;
},

expire: function(type, fn, fn2) {
var self = this;

// Handle different call patterns
if ($.isFunction(type))
fn2 = fn, fn = type, type = undefined;

// Find the Live Query based on arguments and stop it
$.each( $.livequery.queries, function(i, query) {
if ( self.selector == query.selector && self.context == query.context && 
(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
$.livequery.stop(query.id);
});

// Continue the chain
return this;
}
});

$.livequery = function(selector, context, type, fn, fn2) {
this.selector = selector;
this.context  = context || document;
this.type     = type;
this.fn       = fn;
this.fn2      = fn2;
this.elements = [];
this.stopped  = false;

// The id is the index of the Live Query in $.livequery.queries
this.id = $.livequery.queries.push(this)-1;

// Mark the functions for matching later on
fn.$lqguid = fn.$lqguid || $.livequery.guid++;
if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;

// Return the Live Query
return this;
};

$.livequery.prototype = {
stop: function() {
var query = this;

if ( this.type )
// Unbind all bound events
this.elements.unbind(this.type, this.fn);
else if (this.fn2)
// Call the second function for all matched elements
this.elements.each(function(i, el) {
query.fn2.apply(el);
});

// Clear out matched elements
this.elements = [];

// Stop the Live Query from running until restarted
this.stopped = true;
},

run: function() {
// Short-circuit if stopped
if ( this.stopped ) return;
var query = this;

var oEls = this.elements,
els  = $(this.selector, this.context),
nEls = els.not(oEls);

// Set elements to the latest set of matched elements
this.elements = els;

if (this.type) {
// Bind events to newly matched elements
nEls.bind(this.type, this.fn);

// Unbind events to elements no longer matched
if (oEls.length > 0)
$.each(oEls, function(i, el) {
if ( $.inArray(el, els) < 0 )
$.event.remove(el, query.type, query.fn);
});
}
else {
// Call the first function for newly matched elements
nEls.each(function() {
query.fn.apply(this);
});

// Call the second function for elements no longer matched
if ( this.fn2 && oEls.length > 0 )
$.each(oEls, function(i, el) {
if ( $.inArray(el, els) < 0 )
query.fn2.apply(el);
});
}
}
};

$.extend($.livequery, {
guid: 0,
queries: [],
queue: [],
running: false,
timeout: null,

checkQueue: function() {
if ( $.livequery.running && $.livequery.queue.length ) {
var length = $.livequery.queue.length;
// Run each Live Query currently in the queue
while ( length-- )
$.livequery.queries[ $.livequery.queue.shift() ].run();
}
},

pause: function() {
// Don't run anymore Live Queries until restarted
$.livequery.running = false;
},

play: function() {
// Restart Live Queries
$.livequery.running = true;
// Request a run of the Live Queries
$.livequery.run();
},

registerPlugin: function() {
$.each( arguments, function(i,n) {
// Short-circuit if the method doesn't exist
if (!$.fn[n]) return;

// Save a reference to the original method
var old = $.fn[n];

// Create a new method
$.fn[n] = function() {
// Call the original method
var r = old.apply(this, arguments);

// Request a run of the Live Queries
$.livequery.run();

// Return the original methods result
return r;
}
});
},

run: function(id) {
if (id != undefined) {
// Put the particular Live Query in the queue if it doesn't already exist
if ( $.inArray(id, $.livequery.queue) < 0 )
$.livequery.queue.push( id );
}
else
// Put each Live Query in the queue if it doesn't already exist
$.each( $.livequery.queries, function(id) {
if ( $.inArray(id, $.livequery.queue) < 0 )
$.livequery.queue.push( id );
});

// Clear timeout if it already exists
if ($.livequery.timeout) clearTimeout($.livequery.timeout);
// Create a timeout to check the queue and actually run the Live Queries
$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
},

stop: function(id) {
if (id != undefined)
// Stop are particular Live Query
$.livequery.queries[ id ].stop();
else
// Stop all Live Queries
$.each( $.livequery.queries, function(id) {
$.livequery.queries[ id ].stop();
});
}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
// Call the original init and save the result
var r = init.apply(this, arguments);

// Copy over properties if they exist already
if (a && a.selector)
r.context = a.context, r.selector = a.selector;

// Set properties
if ( typeof a == 'string' )
r.context = c || document, r.selector = a;

// Return the result
return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;

})(jQuery);

/**
 * Copyright (c) 2005 - 2009, James Auldridge
 * All rights reserved.
 *
 * Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
 *  http://code.google.com/p/cookies/wiki/License
 *
 */
var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function()
{var cookies=[];var defaultOptions={hoursToLive:null,path:'/',domain:null,secure:false};var resolveOptions=function(options)
{var returnValue;if(typeof options!=='object'||options===null)
{returnValue=defaultOptions;}
else
{returnValue={hoursToLive:(typeof options.hoursToLive==='number'&&options.hoursToLive!==0?options.hoursToLive:defaultOptions.hoursToLive),path:(typeof options.path==='string'&&options.path!==''?options.path:defaultOptions.path),domain:(typeof options.domain==='string'&&options.domain!==''?options.domain:defaultOptions.domain),secure:(typeof options.secure==='boolean'&&options.secure?options.secure:defaultOptions.secure)};}
return returnValue;};var expiresGMTString=function(hoursToLive)
{var dateObject=new Date();dateObject.setTime(dateObject.getTime()+(hoursToLive*60*60*1000));return dateObject.toGMTString();};var assembleOptionsString=function(options)
{options=resolveOptions(options);return((typeof options.hoursToLive==='number'?'; expires='+expiresGMTString(options.hoursToLive):'')+'; path='+options.path+
(typeof options.domain==='string'?'; domain='+options.domain:'')+
(options.secure===true?'; secure':''));};var splitCookies=function()
{cookies={};var pair,name,value,separated=document.cookie.split(';');for(var i=0;i<separated.length;i=i+1)
{pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');value=decodeURIComponent(pair[1]);cookies[name]=value;}
return cookies;};var constructor=function(){};constructor.prototype.get=function(cookieName)
{var returnValue;splitCookies();if(typeof cookieName==='string')
{returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}
else if(typeof cookieName==='object'&&cookieName!==null)
{returnValue={};for(var item in cookieName)
{if(typeof cookies[cookieName[item]]!=='undefined')
{returnValue[cookieName[item]]=cookies[cookieName[item]];}
else
{returnValue[cookieName[item]]=null;}}}
else
{returnValue=cookies;}
return returnValue;};constructor.prototype.filter=function(cookieNameRegExp)
{var returnValue={};splitCookies();if(typeof cookieNameRegExp==='string')
{cookieNameRegExp=new RegExp(cookieNameRegExp);}
for(var cookieName in cookies)
{if(cookieName.match(cookieNameRegExp))
{returnValue[cookieName]=cookies[cookieName];}}
return returnValue;};constructor.prototype.set=function(cookieName,value,options)
{if(typeof value==='undefined'||value===null)
{if(typeof options!=='object'||options===null)
{options={};}
value='';options.hoursToLive=-8760;}
var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options)
{var allCookies={};if(typeof options!=='object'||options===null)
{options={};}
if(typeof cookieName==='boolean'&&cookieName===true)
{allCookies=this.get();}
else if(typeof cookieName==='string')
{allCookies[cookieName]=true;}
for(var name in allCookies)
{if(typeof name==='string'&&name!=='')
{this.set(name,null,options);}}};constructor.prototype.test=function()
{var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue)
{this.del(testName);returnValue=true;}
return returnValue;};constructor.prototype.setOptions=function(options)
{if(typeof options!=='object')
{options=null;}
defaultOptions=resolveOptions(options);};return new constructor();})();(function()
{if(window.jQuery)
{(function($)
{$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options)
{return this.each(function()
{var i,resolvedName=false,resolvedValue=false,name='',value='',nameAttrs=['name','id'],nodeName,inputType;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{nodeName=this.nodeName.toLowerCase();if(nodeName!=='input'&&nodeName!=='textarea'&&nodeName!=='select'&&nodeName!=='img')
{value=$(this).html();resolvedValue=true;}
else
{inputType=$(this).attr('type');if(typeof inputType==='string'&&inputType!=='')
{inputType=inputType.toLowerCase();}
if(inputType!=='radio'&&inputType!=='checkbox')
{value=$(this).val();resolvedValue=true;}}
if(resolvedValue)
{if(typeof value!=='string'||value==='')
{value=null;}
$.cookies.set(name,value,options);}}});},cookieFill:function()
{return this.each(function()
{var i,resolvedName=false,name='',value,nameAttrs=['name','id'],iteration=0,nodeName;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{value=$.cookies.get(name);if(value!==null)
{nodeName=this.nodeName.toLowerCase();if(nodeName==='input'||nodeName==='textarea'||nodeName==='select')
{$(this).val(value);}
else
{$(this).html(value);}}}
iteration=0;});},cookieBind:function(options)
{return this.each(function()
{$(this).cookieFill().change(function()
{$(this).cookify(options);});});}};$.each(extensions,function(i)
{$.fn[i]=this;});})(window.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);

/*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}}}}();

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
if (!document.getElementById) { return; }
this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params = new Object();
this.variables = new Object();
this.attributes = new Array();
if(swf) { this.setAttribute('swf', swf); }
if(id) { this.setAttribute('id', id); }
if(w) { this.setAttribute('width', w); }
if(h) { this.setAttribute('height', h); }
if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
if (!window.opera && document.all && this.installedVer.major > 7) {
// only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (!deconcept.unloadSet) {
deconcept.SWFObjectUtil.prepUnload = function() {
__flash_unloadHandler = function(){};
__flash_savedUnloadHandler = function(){};
if(!deconcept.prepUnloadSet) {
deconcept.prepUnloadSet = true;
window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
}
}
window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
deconcept.unloadSet = true;
}
}
if(c) { this.addParam('bgcolor', c); }
var q = quality ? quality : 'high';
this.addParam('quality', q);
this.setAttribute('useExpressInstall', false);
this.setAttribute('doExpressInstall', false);
var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
this.setAttribute('xiRedirectUrl', xir);
this.setAttribute('redirectUrl', '');
if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
useExpressInstall: function(path) {
this.xiSWFPath = !path ? "expressinstall.swf" : path;
this.setAttribute('useExpressInstall', true);
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
getAttribute: function(name){
return this.attributes[name] || "";
},
addParam: function(name, value){
this.params[name] = value;
},
getParams: function(){
return this.params;
},
addVariable: function(name, value){
this.variables[name] = value;
},
getVariable: function(name){
return this.variables[name] || "";
},
getVariables: function(){
return this.variables;
},
getVariablePairs: function(){
var variablePairs = new Array();
var key;
var variables = this.getVariables();
for(key in variables){
variablePairs[variablePairs.length] = encodeURIComponent(key) +"="+ encodeURIComponent(variables[key]);
}
return variablePairs;
},
getSWFHTML: function() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "PlugIn");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ (this.getAttribute('style') || "") +'"';
swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
var params = this.getParams();
 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
var pairs = this.getVariablePairs().join("&");
 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
swfNode += '/>';
} else { // PC IE
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "ActiveX");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ (this.getAttribute('style') || "") +'">';
swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
var params = this.getParams();
for(var key in params) {
 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
}
var pairs = this.getVariablePairs().join("&");
if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
swfNode += "</object>";
}
return swfNode;
},
write: function(elementId){
if(this.getAttribute('useExpressInstall')) {
// check to see if we need to do an express install
var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
this.setAttribute('doExpressInstall', true);
this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
this.addVariable("MMdoctitle", document.title);
}
}
if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
try{n.innerHTML = this.getSWFHTML();}
catch(err){
return
}
return true;
}else{
if(this.getAttribute('redirectUrl') != "") {
document.location.replace(this.getAttribute('redirectUrl'));
}
}
return false;
}
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins && navigator.mimeTypes.length){
var x = navigator.plugins["Shockwave Flash"];
if(x && x.description) {
PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
}
}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
var axo = 1;
var counter = 3;
while(axo) {
try {
counter++;
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
//document.write("player v: "+ counter);
PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
} catch (e) {
axo = null;
}
}
} else { // Win IE (non mobile)
// do minor version lookup in IE, but avoid fp6 crashing issues
// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
try{
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
}catch(e){
try {
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
} catch(e) {
if (PlayerVersion.major == 6) {
return PlayerVersion;
}
}
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
} catch(e) {}
}
if (axo != null) {
PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}
}
return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
if(this.major < fv.major) return false;
if(this.major > fv.major) return true;
if(this.minor < fv.minor) return false;
if(this.minor > fv.minor) return true;
if(this.rev < fv.rev) return false;
return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
getRequestParameter: function(param) {
var q = document.location.search || document.location.hash;
if (param == null) { return q; }
if(q) {
var pairs = q.substring(1).split("&");
for (var i=0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return pairs[i].substring((pairs[i].indexOf("=")+1));
}
}
}
return "";
}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
var objects = document.getElementsByTagName("OBJECT");
for (var i = objects.length - 1; i >= 0; i--) {
objects[i].style.display = 'none';
for (var x in objects[i]) {
if (typeof objects[i][x] == 'function') {
objects[i][x] = function(){};
}
}
objects[i].removeNode(true);
}
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;




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

AJAX_URL = '/ajax/ajax.php'

loadingImg_dark = '/image/versus_loader_black_100x100.gif?v=213'
loadingImg_darksm = '/image/versus_loader_black_60x60.gif?v=213'
loadingImg_white = '/image/versus_loader_white_100x100.gif?v=213'
loadingImg_whitesm = '/image/versus_loader_white_60x60.gif?v=213'

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

BaseAjax._xArray = {};


BaseAjax.makeAjaxCall = function(url) {

BaseAjax._count++;

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

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].loaderDiv && BaseAjax._xArray[countVar].loaderType){
BaseAjax.setLoaderOverlay(BaseAjax._xArray[countVar].returnDiv);

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);
}
});

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.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 = '/_site/image/blank.gif?v=213';

if( $(theElement).css('position') != 'absolute' )
$(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=0);-moz-opacity:.0;opacity:.0;'+
'z-index:1200; '+
'"></div> '
);



}




// JavaScript Document

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



_xMain={


init:function(){
this.setIE6PngSprites();
this.setInputTextAutofills();
this.setThumbnailHovers();
this.setDropdowns();
this.setHovers();
this.setDetailHeatingTalked()
this.fixRedRibbon();
this.setLandingDetailScrollbars();
this.setTwitterModules();
},

setHovers:function(){

$('#plck_make_comment_template').find('a').live('mouseover',function(){
$(this).addClass('hover');
})
.live('mouseout',function(){
$(this).removeClass('hover');
});


$('#header_input_holder').live('mouseover',function(){
$(this).addClass('input_holder_hover');
})
.live('mouseout',function(){
$(this).removeClass('input_holder_hover');
});

$('.inline_arrow').live('mouseover',function(){
$(this).addClass('inline_arrow_hover');
})
.live('mouseout',function(){
$(this).removeClass('inline_arrow_hover');
});

$('div.a').live('mouseover',function(){
$(this).addClass('a_hover');
})
.live('mouseout',function(){
$(this).removeClass('a_hover');
});

$('#generic_linklist').children('a').live('mouseover',function(){
$(this).addClass('hover');
})
.live('mouseout',function(){
$(this).removeClass('hover');
});

$('.gear_image_area').find('.gear_small').hover(
function(){
var $parent = $(this).parents('.gear_image_area');
var l_nRel = $(this).attr('rel');
if(!$parent.find('.gear_large_'+l_nRel).is(':visible')){
$parent.find('.gear_large').fadeOut(200);
$parent.find('.gear_large_'+l_nRel).fadeIn(200);
}
},
function(){  }
);
},

setDropdowns:function(){

var l_nMaxHeight = 180;

$('.dropdown_content').each(function(){
var $l_xContainerObj = $(this)
var $l_xObj = $(this).children('.dropdown_content_holder')
$l_xContainerObj.addClass('dropdown_content_load');

setTimeout(function(){
var l_nHeight = $l_xObj.height();
if(l_nHeight > l_nMaxHeight){
$l_xObj.css('height',l_nMaxHeight+'px') 
l_nHeight = l_nMaxHeight;
$l_xObj.jScrollPane({
'topCapHeight':6,
'bottomCapHeight':6,
'dragMaxHeight':21,
'dragMinHeight':21
});
}

setTimeout(function(){
$l_xObj.attr('rel',l_nHeight);
$l_xContainerObj.removeClass('dropdown_content_load');
},100 )

},100);
});

$('.dropdown_main').unbind();

$('.dropdown_main').click(function(){

var $l_xContent = $(this).siblings('.dropdown_content')
$l_xContent.toggle();
var $l_xContentHolder = $l_xContent.find('.dropdown_content_holder')
var l_nHeight = $l_xContentHolder.attr('rel');
$l_xContent.find('.dropdown_content_left, .dropdown_content_right').css('height',l_nHeight+'px');


})
.hover(function(){
$(this).addClass('dropdown_main_hover');
},function(){
$(this).removeClass('dropdown_main_hover');
});


$('.dropdown_row').blur(function(){
var $dropdown_row = $(this);
setTimeout(function(){ 
$dropdown_row.find('.dropdown_content').hide(); 
}, 200);
});




},

switchDropdown:function(p_xThis){

var l_sSlug = $(p_xThis).attr('rel');
var l_sName = $(p_xThis).html();

var l_xDropdown = $(p_xThis).parents('.dropdown_row');

$(l_xDropdown).attr('title',l_sName)

$(l_xDropdown).data('choice',l_sSlug);

$(l_xDropdown).find('.dropdown_main_middle').html(l_sName);

$(l_xDropdown).find('.dropdown_content').hide();
$(l_xDropdown).blur();
},

setIE6PngSprites:function(){

if(document.isIE6){

$('.sprite').find('a').each(function(){
var $this = $(this);
if($this.hasClass('png')){
$(this).live('mouseover',function(){
$(this).addClass('a_hover');
})
.live('mouseout',function(){
$(this).removeClass('a_hover');
}).
addClass('fixcursor');
}
     });
}

},

setInputTextAutofills:function(){

$('textarea.autofill, input.autofill').each(function(){
$(this).val($(this).attr('rel'));
$(this).focus(function(){
if($(this).val() == $(this).attr('rel'))
$(this).val('');
});
$(this).blur(function(){
if($(this).val() == '')
$(this).val($(this).attr('rel'));
});
});

},


setThumbnailHovers:function(){


$('.mod_photo_tn').live('mouseover',function(){
$(this).addClass('mod_photo_tn_hover');
})
.live('mouseout',function(){
$(this).removeClass('mod_photo_tn_hover');
});

$('.mod_video_tn').live('mouseover',function(){
$(this).addClass('mod_video_tn_hover');
})
.live('mouseout',function(){
$(this).removeClass('mod_video_tn_hover');
});

$('.mod_blog_tn').live('mouseover',function(){
$(this).addClass('mod_blog_tn_hover');
})
.live('mouseout',function(){
$(this).removeClass('mod_blog_tn_hover');
});

$('.mod_misc_tn').live('mouseover',function(){
$(this).addClass('mod_misc_tn_hover');
})
.live('mouseout',function(){
$(this).removeClass('mod_misc_tn_hover');
});

$('.mod_video_tn .addremove').live('mouseover',function(){
$(this).parent().addClass('mod_video_tn_hover_cancel');
})
.live('mouseout',function(){
$(this).parent().removeClass('mod_video_tn_hover_cancel');
});

$('#detail_tab_module').find('.addremove').live('mouseover',function(){
$(this).parent().addClass('img_holder_hover_cancel');
})
.live('mouseout',function(){
$(this).parent().removeClass('img_holder_hover_cancel');
});

},

setLandingDetailScrollbars:function(){

if(!document._bIsPictureLanding && !document._bIsVideoLanding) return;

var $l_xTabModule = $('#detail_tab_module')
//$l_xTabModule.height( $l_xTabModule.height() )
//var l_nMaxHolderHeight = ($l_xTabModule.hasClass('detail_tab_module_pictures'))?83:62

$l_xTabModule.find('.row_holder').each(function(){
var $l_xRowHolder = $(this)
$l_xRowHolder.addClass('row_holder_load');

setTimeout(function(){
$l_xRowHolder.jScrollPane({
'topCapHeight':6,
'bottomCapHeight':6,
'scrollbarMargin':0,
'scrollbarWidth':17
});


},100);

});

setTimeout(function(){
$l_xTabModule.find('.row_holder').removeClass('row_holder_load');
$('#detail_tab_module').find('.jScrollPaneContainer').eq(0).show();
$('#detail_tab_module').find('.jScrollPaneContainer').eq(1).hide();
},150);

},

setDetailHeatingTalked:function(){
$('#detail_tab_module').find('.heating_tab').live('click',function(){
$('#detail_tab_module').find('.jScrollPaneContainer').eq(0).show();
$('#detail_tab_module').find('.jScrollPaneContainer').eq(1).hide();
$('#detail_tab_module').find('.talkedup_tab').removeClass('sprite_selected');
$('#detail_tab_module').find('.queuedup_tab').removeClass('sprite_selected');
$(this).addClass('sprite_selected');
if(document.isIE6)
IEPNGFix.update();
});
$('#detail_tab_module').find('.talkedup_tab').live('click',function(){
$('#detail_tab_module').find('.jScrollPaneContainer').eq(1).show();
$('#detail_tab_module').find('.jScrollPaneContainer').eq(0).hide();
$('#detail_tab_module').find('.heating_tab').removeClass('sprite_selected');
$(this).addClass('sprite_selected');
if(document.isIE6)
IEPNGFix.update();
});
$('#detail_tab_module').find('.queuedup_tab').live('click',function(){
$('#detail_tab_module').find('.jScrollPaneContainer').eq(1).show();
$('#detail_tab_module').find('.jScrollPaneContainer').eq(0).hide();
$('#detail_tab_module').find('.heating_tab').removeClass('sprite_selected');
$(this).addClass('sprite_selected');
if(document.isIE6)
IEPNGFix.update();
});
},

fixRedRibbon:function(){
var $ribbon = $('#mod_redribbon');
if($ribbon.length){
setTimeout(function(){
var l_nAuxHeights = 0;
l_nAuxHeights += $ribbon.children('.top').height();
l_nAuxHeights += $ribbon.children('.bottom').height();

l_nContentHeight = $ribbon.children('.content').height();

if(l_nContentHeight > l_nAuxHeights){
$ribbon.children('.middle').height(l_nContentHeight-l_nAuxHeights);
}
},100);
}
},

stopFeatureAutocycleOnVideoClick:function(){
if(document._bIsHome)
_xHome.stopAutoPlay();
else if(document._sFeatureAreaType=='sport_wide' || document._sFeatureAreaType=='sport_narrow' || document._sFeatureAreaType=='show' || document._sFeatureAreaType=='post' || document._sFeatureAreaType=='wide_img' || document._sFeatureAreaType=='gear')
_xFeature.stopAutoPlay();
},

startFeatureAutocycleOnVideoClick:function(){
if(document._bIsHome)
_xHome.startAutoPlay();
else if(document._sFeatureAreaType=='sport_wide' || document._sFeatureAreaType=='sport_narrow' || document._sFeatureAreaType=='show' || document._sFeatureAreaType=='post' || document._sFeatureAreaType=='wide_img' || document._sFeatureAreaType=='gear')
_xFeature.startAutoPlay();
},

setTwitterModules:function(){
$('.twitter_name')
.click(
function(){ $(this).addClass('selected').siblings('.twitter_name').removeClass('selected');}
)
.hover(
function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); }
);

}



}




// JavaScript Document



_xItem={

_xData : new Array(),


getItemInfoAsString:function(p_sDataType,p_nPage){
var l_xData = this._xData[p_sDataType];

var l_nNumPerPage = l_xData._nNumPerPage;
var l_nOffset = (p_nPage)*l_nNumPerPage;

var l_aItemIds = l_xData._aItems;
var l_aItemsIdsAndType = l_xData._aItemsIdTypeSet;
var l_sAssetType = l_xData._sAssetType;
var l_sModType = l_xData._sModType;
var l_sUniqueId = l_xData._sUniqueId;
var l_sStreamDescriptor = l_xData._sStreamDescriptor;
var l_nCurrentIndex = l_xData._nCurrentIndex;

var l_sReturnString = "";
if(l_xData._nTotalItems){
l_sReturnString += '&p_nTotal='+l_xData._nTotalItems;
}else{
l_sReturnString += '&p_nTotal='+l_aItemsIdsAndType.length;
}

//display item ids
l_sReturnString += '&p_nItems=';
var l_nCurrentId = null;
for(var i=0; i<l_nNumPerPage;i++){
if(l_nCurrentId = this._xData[p_sDataType]._aItems[l_nOffset+i])
l_sReturnString+=((i)?',':'')+l_nCurrentId;
else break;
}

//build json object using jquery $.toJSON for id and type for items to be displayed
var l_xIdItemTypes = "";
for(var i=0; i<l_nNumPerPage;i++){
 var l_sIdItemType = {"id":""+l_aItemsIdsAndType[l_nOffset+i].id+"","type":""+l_aItemsIdsAndType[l_nOffset+i].type+""};
 var l_xJsonEncodedIdItemType = $.toJSON(l_sIdItemType); 
 l_xIdItemTypes += ((i)?',':'')+l_xJsonEncodedIdItemType;
}

l_sReturnString += '&p_xItemsIdAndType=['+l_xIdItemTypes+']';
l_sReturnString += '&p_sAssetType='+l_sAssetType;
l_sReturnString += '&p_sModType='+l_sModType;
l_sReturnString += '&p_sUniqueId='+l_sUniqueId;
l_sReturnString += '&p_sStreamDescriptor='+l_sStreamDescriptor;
l_sReturnString += '&p_nOffset='+l_nOffset;
l_sReturnString += '&p_nCurrentIndex='+l_nCurrentIndex;

return l_sReturnString;
},

setItemInfo:function(p_sDataType,p_aData){
this._xData[p_sDataType] = {};
this._xData[p_sDataType] = p_aData;
},


modPaginate:function(p_nPage,p_xObj){

$l_xInner = $(p_xObj).parents('.mod_inner')

$l_sModId = $l_xInner.attr('id');

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += _xItem.getItemInfoAsString($l_sModId,p_nPage-1);

BaseAjax._xArgs.returnDiv = '#'+$l_sModId;
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

},


talkedModulePaginate:function(p_nPage,p_xObj){

BaseAjax._xArgs.data = 'a=ModMiniDetailAjaxCall';
BaseAjax._xArgs.data += '&p_sModule=talked'
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_nType='+document._nItemType;
BaseAjax._xArgs.returnDiv = '#mini_talked_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall(AJAX_URL);

},

heatingModulePaginate:function(p_nPage,p_xObj){

BaseAjax._xArgs.data = 'a=ModMiniDetailAjaxCall';
BaseAjax._xArgs.data += '&p_sModule=heating'
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_nType='+document._nItemType;
BaseAjax._xArgs.returnDiv = '#mini_heating_module';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall(AJAX_URL);

}

}

// JavaScript Document

$(document).ready(function(){
if(document.isPhotoDetail)
_xPhotoDetail.init();
});




_xPhotoDetail={
_bLoading:false,
_aPath : null,
_nItemValue : null,

init:function(){
this.initHistory();
},


initHistory:function(){
$.historyInit(_xPhotoDetail.detectChangeAddress);
if(!this._aPath)
$.historyLoad('/item/1/');
},


gotoPhotoItem:function(p_nId){
if(_xPhotoDetail._bLoading) return;
_xPhotoDetail._bLoading = true;

if (document.isPhotoDetail) {
$.historyLoad('/item/'+p_nId+'/');
}
else {
_xPhotoDetail.loadPhotoDetail(p_nId);
}

$.each($('iframe.ad'), function() {
this.contentWindow.location.reload();
});
},

grabAddressData:function(hash){
hash = hash.replace(/^.*#/, '');
var l_aPathNames= hash.split('/'); 
if(l_aPathNames[1]=='item' && l_aPathNames[2]){
this._aPath = l_aPathNames
this._nItemValue = l_aPathNames[2]
}
else{
this._aPath = null
this._nItemValue = null
}

},

detectChangeAddress:function(hash){
_xPhotoDetail.grabAddressData(hash);
if(_xPhotoDetail._nItemValue){
_xPhotoDetail.loadPhotoDetail(_xPhotoDetail._nItemValue);
}else{
_xPhotoDetail.gotoPhotoItem(1);
}
},


loadPhotoDetail:function(p_nPage){

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += _xItem.getItemInfoAsString('photo_detail',p_nPage-1,1);

BaseAjax._xArgs.returnDiv = '#ajax_photo_detail_behind';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax._xArgs.callBack = _xPhotoDetail.pushDetailToFront;

BaseAjax.makeAjaxCall(AJAX_URL);

},

pushDetailToFront:function(){
$detail = $('#ajax_photo_detail');
$behind = $('#ajax_photo_detail_behind');

$detail.addClass('ajax_photo_detail_switching');
$behind.addClass('ajax_photo_detail_behind_switching');

$detail.fadeOut(500,function(){ 
 $detail.remove();
$behind.attr('id','ajax_photo_detail').attr('class','ajax_photo_detail').after('<div id="ajax_photo_detail_behind"  class="ajax_photo_detail_behind"></div>')
_xPhotoDetail._bLoading = false;
  });
}

}

// JavaScript Document



_xVideo={



loadVideoLandingDetail:function(p_nPage){

BaseAjax._xArgs.data = 'a=VideoLandingDetailAjaxCall';

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += _xItem.getItemInfoAsString('video_detail',p_nPage-1,1);

BaseAjax._xArgs.returnDiv = '#detail_inner';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

}





}

// JavaScript Document


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



_xCookie = {

_sQueueName : 'cookieJar',
_sQueueData : '',

init:function(){
this.setClickHandlers();

if(document._bIsVideoDetail == true){
this.buildQueuedUpModule(0);
}
else if(document._bIsVideoLanding == true){
this.buildLandingQueuedUpModule();
}
},



addToQueue:function(p_aVideoData){
var l_sQueue = this.grabQueue();
var l_sCookieId = new Date().getTime();

if(!l_sQueue){ // if queue cookie does not yet exist
this.initQueue(l_sCookieId); // initialize queue cookie (the "cookie jar")
$.cookie(l_sCookieId, p_aVideoData[0]+'##*##'+p_aVideoData[1]+'##*##'+p_aVideoData[2], {path:'/'}); // create cookie for selected video
}
else if(!this.checkQueueForVideoUrl(p_aVideoData[0])){ // else if video's url is not in queue cookie
this._sQueueData = l_sQueue+'##*##'+l_sCookieId; // add selected video's url to queue cookie
this.setQueue();
$.cookie(l_sCookieId, p_aVideoData[0]+'##*##'+p_aVideoData[1]+'##*##'+p_aVideoData[2], {path:'/'}); // create cookie for selected video
}

if(document._bIsVideoDetail == true){
this.buildQueuedUpModule(0);
}
else if(document._bIsVideoLanding == true){
this.buildLandingQueuedUpModule();
}
},


checkQueueForVideoUrl:function(p_sVideoUrl){ 
var l_sQueue = this.grabQueue();
var l_aQueueArray = l_sQueue.split('##*##');

for(var i=0; i<l_aQueueArray.length; i++){
var l_sId = l_aQueueArray[i];
var l_sVideoCookie = $.cookie(l_sId);
var l_aVideoCookieArray = l_sVideoCookie.split('##*##');
var l_sVideoCookieUrl = l_aVideoCookieArray[0];
if(l_sVideoCookieUrl == p_sVideoUrl){
return true;
}
}
return false;
},


removeFromQueue:function(p_sVideoId){
var l_sQueue = this.grabQueue();
var l_aQueueArray = l_sQueue.split('##*##');

if(l_aQueueArray.indexOf(p_sVideoId) >= 0){ // if selected video url is in queue cookie
l_nIndex = l_aQueueArray.indexOf(p_sVideoId);
l_aQueueArray.splice(l_nIndex, 1); // remove selected video url from queue cookie

if(l_aQueueArray.length > 0){ // if queue cookie is not empty
this._sQueueData = l_aQueueArray.join('##*##'); // recreate delimited string
this.setQueue();
}
else { // if queue cookie is now empty, delete queue cookie
$.cookie(this._sQueueName, null, {path:'/'});
}

$.cookie(p_sVideoId, null, {path:'/'}); // finally, delete selected video's cookie

if(document._bIsVideoDetail == true){
this.buildQueuedUpModule(0);
}
else if(document._bIsVideoLanding == true){
this.buildLandingQueuedUpModule();
}
}
},



grabQueue:function(){
return $.cookie(this._sQueueName);
},

setQueue:function(){
$.cookie(this._sQueueName, this._sQueueData, {path:'/'});
},

initQueue:function(p_aFirstVideoUrl){
$.cookie(this._sQueueName, p_aFirstVideoUrl, {path:'/'});
},



setClickHandlers:function(){
$('.btn_video_add').live('click', function(){
var l_aVideoData = new Array();

if($(this).hasClass('heating_add')){
var l_sAnchor = $(this).parent().parent().parent().parent();
l_aVideoData[2] = _xCookie.trimImageSuffix($(this).parent().siblings('img').attr('src'));
}
else{
var l_sAnchor = $(this).parent().siblings('a');
l_aVideoData[2] = _xCookie.trimImageSuffix(l_sAnchor.children('img').attr('src'));
}

l_aVideoData[0] = _xCookie.trimVideoUrl(l_sAnchor.attr('href'));
l_aVideoData[1] = l_sAnchor.attr('title');

_xCookie.addToQueue(l_aVideoData);

return false;
});


$('#vid_landing_queued').find('.btn_video_sub').live('click', function(){
var l_sAnchor = $(this).parent().parent().parent().parent();   
var l_sVideoId = l_sAnchor.attr('rel');

_xCookie.removeFromQueue(l_sVideoId);

return false;
});


$('#module_side_queued_heat').find('.btn_video_sub').live('click', function(){
var l_sAnchor = $(this).parent().siblings('a');   
var l_sVideoId = l_sAnchor.attr('rel');

_xCookie.removeFromQueue(l_sVideoId);

return false;
});
},


buildQueuedUpModule:function(p_nVideoNumber){
if(this.grabQueue()){
var l_sQueue = this.grabQueue();
var l_aQueueArray = l_sQueue.split('##*##');
var l_sVideoId = l_aQueueArray[p_nVideoNumber];

var l_sVideoCookie = $.cookie(l_sVideoId);
var l_sVideoCookieArray = l_sVideoCookie.split('##*##');

var l_sHtml = '<div class="mod_video_tn">'+
'<a href="'+l_sVideoCookieArray[0]+'" title="'+l_sVideoCookieArray[1]+'" rel="'+l_sVideoId+'" class="tn_holder"><img src="'+l_sVideoCookieArray[2]+'_126.jpg?v=213" /></a>'+
'<div class="addremove">'+
'<div class="btn_video_sub sprite"><a href=""><span>Remove Video</span></a></div>'+
'</div>'+
  '</div>'+
  '<div class="mod_video_tn_title">'+
l_sVideoCookieArray[1]+
  '</div>'+
  this.buildQueuedUpPagination(p_nVideoNumber);
}
else {
var l_sHtml = '<div style="font-size: 11px; padding: 15px;">Your queue is currently empty.</div>';
}

$('#module_side_queued_heat').children('.module_side_tn_holder').eq(0).html(l_sHtml);
},


buildQueuedUpPagination:function(p_nVideoNumber){
var l_nCurrentPage = p_nVideoNumber + 1;

if(this.grabQueue()){
var l_sQueue = this.grabQueue();
var l_aQueueArray = l_sQueue.split('##*##');

if(l_aQueueArray.length <= 1 ){
return '';
}

var l_sItemDisplay = '<b>'+l_nCurrentPage+'</b>';

var l_bClickLeft = (l_nCurrentPage != 1);
var l_bClickRight = (l_nCurrentPage != l_aQueueArray.length);

var l_sLeftString, l_sRightString, l_sLeftClass, l_sRightClass;

(l_bClickLeft) ? l_sLeftString = 'onclick="_xCookie.buildQueuedUpModule('+(p_nVideoNumber-1)+')"' : l_sLeftString = '';
l_sLeftString += ' href="javascript:void(0);"';

(l_bClickRight)? l_sRightString = 'onclick="_xCookie.buildQueuedUpModule('+(p_nVideoNumber+1)+')"' : l_sRightString = '';
l_sRightString += ' href="javascript:void(0);"';

(l_bClickLeft) ? l_sLeftClass = '' : l_sLeftClass = 'sprite_selected';
(l_bClickRight) ? l_sRightClass = '' : l_sRightClass = 'sprite_selected';


var l_sHtml = '<div class="mod_video_tn_pagination">'+
'<div class="pagi_holder">'+    
'<div class="mod_video_tn_pagination_left sprite '+l_sLeftClass+'"><a '+l_sLeftString+'><span>Left</span></a></div>'+           
'<div class="mod_video_tn_pagination_right sprite '+l_sRightClass+'"><a '+l_sRightString+'><span>Right</span></a></div>'+
l_sItemDisplay+' of <b>'+ l_aQueueArray.length +'</b>'+
'</div>'+
  '</div>';
  
return l_sHtml;
}
},


buildLandingQueuedUpModule:function(){
var l_sHtml = '';

if(this.grabQueue()){
var l_sQueue = this.grabQueue();
var l_aQueueArray = l_sQueue.split('##*##');

for(var i=0; i<l_aQueueArray.length; i++){
var l_sVideoId = l_aQueueArray[i];
var l_sVideoCookie = $.cookie(l_sVideoId);
var l_sVideoCookieArray = l_sVideoCookie.split('##*##');


var l_sFirstRow, l_sOddEven;
(i==0) ?  l_sFirstRow = 'first_row' : l_sFirstRow = '';
(((i+1)%2)==0) ? l_sOddEven = 'even_row' : l_sOddEven = 'odd_row';

l_sHtml += '<a href="'+l_sVideoCookieArray[0]+'" class="row '+l_sFirstRow+'" title="'+l_sVideoCookieArray[1]+'" rel="'+l_sVideoId+'">'+
'<div class="'+l_sOddEven+'">'+
'<div class="img_holder">'+
'<img src="'+l_sVideoCookieArray[2]+'_w88.jpg?v=213" />'+
'<div class="addremove">'+
'<div class="btn_video_sub sprite"><div class="a"><span>Remove Video</span></div></div>'+
'</div>'+
'</div>'+
'<div class="txt_holder">'+
'<div class="p_holder">'+
'<p>'+l_sVideoCookieArray[1]+'</p>'+
'</div>'+
'<div class="clear"></div>'+
/*'<div class="timestamp">9/23/2009</div>'+ //TODO: Add timestamp and duration?
'<div class="duration">2:28</div>'+*/
'</div>'+
'</div>'+
'</a>';
}
}
else {
var l_sHtml = '<div style="color: #FFF; font-size: 11px; padding: 15px;">Your queue is currently empty.</div>';
}

setTimeout(function(){
$('#vid_landing_queued').html(l_sHtml);

$('#detail_tab_module').find('.jScrollPaneContainer').eq(1).show();
$('#detail_tab_module').find('.jScrollPaneContainer').eq(0).hide();
$('#detail_tab_module').find('.heating_tab').removeClass('sprite_selected');
$('.queuedup_tab').addClass('sprite_selected');
if(document.isIE6)
IEPNGFix.update();

setTimeout(function(){
$('#vid_landing_queued').jScrollPane({
'topCapHeight':6,
'bottomCapHeight':6,
'scrollbarMargin':0,
'scrollbarWidth':17
});
},100);
},200);
},



trimImageSuffix:function(p_sImageSrc){
var l_sIndex;

if(p_sImageSrc.indexOf('.jpg?v=213') >= 0){
l_sIndex = p_sImageSrc.indexOf('.jpg?v=213');
p_sImageSrc = p_sImageSrc.substr(0, l_sIndex+4);
}
if(p_sImageSrc.indexOf('.gif?v=213') >= 0){
l_sIndex = p_sImageSrc.indexOf('.gif?v=213');
p_sImageSrc = p_sImageSrc.substr(0, l_sIndex+4);
}
if(p_sImageSrc.indexOf('.png?v=213') >= 0){
l_sIndex = p_sImageSrc.indexOf('.png?v=213');
p_sImageSrc = p_sImageSrc.substr(0, l_sIndex+4);
}

return p_sImageSrc;
},

trimVideoUrl:function(p_sVideoUrl){
if(p_sVideoUrl.indexOf('in-stream') >= 0){
var l_sIndex = p_sVideoUrl.indexOf('in-stream');
p_sVideoUrl = p_sVideoUrl.substr(0, l_sIndex);
}
return p_sVideoUrl;
}


}


$(document).ready(function(){
_xBrowser.init();
if( document._bStandardBrowser ){
_xBrowser.standardBrowserInit();
}
if( document._bBlogLandingBrowser ){
_xBrowser.blogLandingBrowserInit();
}
if( document._bShowDetailBrowser ){
_xBrowser.showDetailBrowserInit();
}

//if( document._bMainSearch ){
//_xBrowser.mainSearchrInit();
//}

});


_xBrowser={
_bLoading:false,
_aPath : null,
_sDropdown1 : null,
_sDropdown2 : null,
_sHash : null,

init:function(){
this.initHeaderLinks();
this.initDropdowns();
this.initAlphabet();
},

standardBrowserInit:function(){
$.historyInit(_xBrowser.detectChangeAddress);
},
blogLandingBrowserInit:function(){
$.historyInit(_xBrowser.detectChangeAddressForBlogLanding);
},

initAlphabet:function(){


$('#browser_alphabet').find('a').live('click',function(){

var l_sSearchTerm = $('#browsing_search_input').val()

var l_sSort = $('#browsing_sort').attr('rel')
var l_sFilter1 = $('#browsing_filter_1').attr('rel')
var l_sFilter2 = $('#browsing_filter_2').attr('rel')
var l_nItemType = document._nBrowserType;

var l_sAlphabet = $(this).attr('rel');

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nSportsId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchTerm;
BaseAjax._xArgs.data += '&p_nAlphabet='+l_sAlphabet;

BaseAjax._xArgs.returnDiv = '#browsing_content_holder'
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

return false;

});

},
initDropdowns:function(){
$('#mod_browsing_filter_1').find('a').live('click',function(){
var l_sSlug = $(this).attr('rel');
var l_sSort = $('#mod_browsing_sort').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sSlug;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#module_bar_browse_videos_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_inner'
BaseAjax._xArgs.loaderType = 'whitesm'

BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

});

$('#mod_browsing_filter_2').find('a').live('click',function(){
var l_sSlug = $(this).attr('rel');
var l_sSort = $('#mod_browsing_sort').attr('rel')
var l_sFilter1 = $('#mod_browsing_filter_1').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sSlug;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#module_bar_browse_videos_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_inner'
BaseAjax._xArgs.loaderType = 'whitesm'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

});

$('#mod_browsing_sort').find('a').live('click',function(){
var l_sSort = $(this).attr('rel');
var l_sFilter1 = $('#mod_browsing_filter_1').attr('rel')
var l_sFilter2 = $('#mod_browsing_filter_2').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#module_bar_browse_videos_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_inner'
BaseAjax._xArgs.loaderType = 'whitesm'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

});

$('#browsing_filter_1').find('a').live('click',function(){
var l_sSlug = $(this).attr('rel');
var l_sSort = $('#browsing_sort').attr('rel')
if(l_sSlug)
$.historyLoad('/'+l_sSlug+'/sort='+l_sSort+'/');
else{
$.historyLoad('/sort='+l_sSort+'/');
}
});

$('#browsing_filter_2').find('a').live('click',function(){
var l_sSlug = $(this).attr('rel');
var l_sSort = $('#browsing_sort').attr('rel')
var l_sFilter1 = $('#browsing_filter_1').attr('rel')

$.historyLoad('/'+l_sFilter1+'/'+l_sSlug+'/sort='+l_sSort+'/');

});

$('#browsing_sort').find('a').live('click',function(){
var l_sSort = $(this).attr('rel');

var l_sFilter1 = $('#browsing_filter_1').attr('rel')
var l_sFilter2 = $('#browsing_filter_2').attr('rel')

if(l_sFilter2)
$.historyLoad('/'+l_sFilter1+'/'+l_sFilter2+'/sort='+l_sSort+'/');
else if(!l_sFilter1)
$.historyLoad('/sort='+l_sSort+'/');
else
$.historyLoad('/'+l_sFilter1+'/sort='+l_sSort+'/');

});

$('#browsing_search_form').livequery('submit',function(){
var l_sSearchValue = $.trim($(this).children('.browsing_search_input').val());

var l_sSort = $('#browsing_sort').attr('rel')
var l_sFilter1 = $('#browsing_filter_1').attr('rel')
var l_sFilter2 = $('#browsing_filter_2').attr('rel')
var l_nItemType = document._nBrowserType;

var l_sAlphabet = '';
if ($('#browser_alphabet').length)
l_sAlphabet = $('#browser_alphabet').find('.current').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nSportsId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchValue;
BaseAjax._xArgs.data += '&p_nAlphabet='+l_sAlphabet;

BaseAjax._xArgs.returnDiv = '#browsing_content_holder'
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

return false;
});


},

modBrowsingFilterPaginate:function(p_nPage){

var l_sSort = $('#mod_browsing_sort').attr('rel')
var l_sFilter1 = $('#mod_browsing_filter_1').attr('rel')
var l_sFilter2 = $('#mod_browsing_filter_2').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#module_bar_browse_videos_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_inner'
BaseAjax._xArgs.loaderType = 'whitesm'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},


fullBrowserFilterPaginate:function(p_nPage){

var l_sSort = $('#browsing_sort').attr('rel')
var l_sFilter1 = $('#browsing_filter_1').attr('rel')
var l_sFilter2 = $('#browsing_filter_2').attr('rel')
var l_nItemType = document._nBrowserType;
var l_sSearchTerm = $('#browsing_search_input').val()

var l_sAlphabet = '';
if ($('#browser_alphabet').length)
l_sAlphabet = $('#browser_alphabet').find('.current').attr('rel')

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nSportsId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchTerm;
BaseAjax._xArgs.data += '&p_nAlphabet='+l_sAlphabet;


BaseAjax._xArgs.returnDiv = '#browsing_content_holder'
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

},


// Set links to only use $.history if on the same page. Otherwise link with hash.
initHeaderLinks:function(){
$('#header').find('.link').each(function(){
var l_sUrl = $(this).attr('href')
if(l_sUrl.search('#') != -1){
l_sHash = l_sUrl.replace(/^.*#/, '')
l_sUrl = l_sUrl.replace(/#.*/, '');
l_sUrl = l_sUrl.replace(/.*.com/, '');
l_sUrl = l_sUrl.replace(/.*.net/, '');
var l_sCurrent = window.location.pathname;
l_sCurrent = l_sCurrent.replace(/^.*#/, '');

if(l_sCurrent == l_sUrl){
$(this).attr('rel',l_sHash).click(function(){ 
$.scrollTo('#browser')
var l_sTheHash = $(this).attr('rel')
_xBrowser.hashLinkHit(l_sTheHash);
   return false
   });
}
}
});

},


hashLinkHit:function(l_sHash){
_xBrowser.grabAddressData();
l_sOldHash = _xBrowser._sHash;
if(l_sHash != l_sOldHash){
$.historyLoad(l_sHash);
}
},

grabAddressData:function(){
hash = window.location.hash
hash = hash.replace(/^.*#/, '');
var l_aPathNames= hash.split('/'); 
if(_.isArray(l_aPathNames)){
this._sHash = hash;
this._aPath = l_aPathNames
this._sDropdown1 = l_aPathNames[1]
this._sDropdown2 = l_aPathNames[2]
}
else{
this._sHash = null;
this._aPath = null
this._sDropdown1 = null
this._sDropdown2 = null
}

},

detectChangeAddressForBlogLanding:function(hash){
var l_aPathNames= hash.split('/'); 

if( l_aPathNames[1]){
// Lets assume the hash will be /sort/page/
var l_sSort =l_aPathNames[1];
var l_nPage =l_aPathNames[2];

var l_sFilter ='';

var l_sSearchTerm = $('#browsing_search_input').val();
//if default text
if (l_sSearchTerm == 'Tag Search' )l_sSearchTerm = '';
var l_sSort = $('#browsing_sort').attr('rel');

var regx = /sort=(.*)/;
var found = l_aPathNames[1] .match( regx );
if(found){
   l_sSort = found[1];
   }
   regx = /page=(.*)/;
   var found = l_aPathNames[2] .match( regx );
   if(found){
   l_nPage = found[1];
   }

var l_nItemType = document._nBrowserType;

BaseAjax._xArgs.data = 'a=BlogLandingAjaxCall';
BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nBlogId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchTerm;

BaseAjax._xArgs.returnDiv = '#browsing_content';
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside';
BaseAjax._xArgs.loaderType = 'dark';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

$.scrollTo('#browser');
}


},

blogLandingFilterPaginate:function(p_nPage){

var l_sSort = $('#browsing_sort').attr('rel');

var l_nItemType = document._nBrowserType;
var l_sSearchTerm = $('#browsing_search_input').val();
//if default text
if (l_sSearchTerm == 'Tag Search' )l_sSearchTerm = '';

BaseAjax._xArgs.data = 'a=BlogLandingAjaxCall';
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nBlogId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchTerm;


BaseAjax._xArgs.returnDiv = '#browsing_content';
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside';
BaseAjax._xArgs.loaderType = 'dark';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

$.scrollTo('#browsing_content_holder_inside', 300);
},
//Blog Landing Page, Verus blogs (Soon Related To Be) 3X1 mod
modBlogsBrowsingPaginate:function(p_nPage){

BaseAjax._xArgs.data = 'a=ModBlogsBrowserAjaxCall';
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.returnDiv = '#module_bar_browse_blogs_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_blogs_inner'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},

BlogsAggregatePaginate:function(p_nPage){

BaseAjax._xArgs.data = 'a=BlogsAggregatePaginateBrowserAjaxCall';
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_bIsHip='+$('.is_hip').attr('rel');
BaseAjax._xArgs.returnDiv = '#browse_blogs_aggregate_holder'
BaseAjax._xArgs.loaderDiv = '#browse_blogs_aggregate_inner'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

$.scrollTo('#browse_blogs_aggregate_holder', 300);
},

//Blog Aggregate Page, Verus blogs 2X1 mod
modBlogsAggregatePaginate:function(p_nPage){
BaseAjax._xArgs.data = 'a=ModBlogsAggregateBrowserAjaxCall';
BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.returnDiv = '#module_bar_browse_blogs_holder'
BaseAjax._xArgs.loaderDiv = '#module_bar_browse_blogs_inner'
BaseAjax._xArgs.loaderType = 'darksm'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},



detectChangeAddress:function(hash){

var l_aPathNames= hash.split('/');


if( l_aPathNames[1]){
var l_sFilter1 =''
var l_sFilter2 =''

var l_sSearchTerm = $('#browsing_search_input').val()
var l_sSort = $('#browsing_sort').attr('rel')

var l_sAlphabet = '';
if ($('#browser_alphabet').length)
l_sAlphabet = $('#browser_alphabet').find('.current').attr('rel')

var regx = /sort=(.*)/

for(var i=0; i<l_aPathNames.length; i++) { 
   if( l_aPathNames[i] ){
   var found = l_aPathNames[i] .match( regx );
   if(found){
   l_sSort = found[1]
   }else if(l_sFilter1){
l_sFilter2= l_aPathNames[i]
   }else{
   l_sFilter1= l_aPathNames[i]
   }
   }
}

var l_nItemType = document._nBrowserType;

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sFilter1='+l_sFilter1;
BaseAjax._xArgs.data += '&p_sFilter2='+l_sFilter2;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;
BaseAjax._xArgs.data += '&p_nItemType='+l_nItemType;
BaseAjax._xArgs.data += '&p_nSectionId='+document._nSportsId;
BaseAjax._xArgs.data += '&p_sSearchTerm='+l_sSearchTerm;
BaseAjax._xArgs.data += '&p_nAlphabet='+l_sAlphabet;

BaseAjax._xArgs.returnDiv = '#browsing_content_holder'
BaseAjax._xArgs.loaderDiv = '#browsing_content_holder_inside'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

$.scrollTo('#browser')

}
},

showDetailBrowserInit:function(){
this.setShowDetailDropdowns();

},

setShowDetailDropdowns:function(){

$('#show_detail_sort').find('a').live('click',function(){
var l_sSort = $(this).attr('rel');
var l_sFilter = $('#show_detail_filter').attr('rel');
_xBrowser.showDetailAjax(1,l_sFilter,l_sSort);
});
$('#show_detail_filter').find('a').live('click',function(){
var l_sFilter = $(this).attr('rel');
var l_sSort = $('#show_detail_sort').attr('rel');
_xBrowser.showDetailAjax(1,l_sFilter,l_sSort);
});

},

showDetailPaginate:function(p_nPage){
var l_sSort = $('#show_detail_sort').attr('rel');
var l_sFilter = $('#show_detail_filter').attr('rel');
_xBrowser.showDetailAjax(p_nPage,l_sFilter,l_sSort);
},

showDetailAjax:function(p_nPage, p_sFilterSlug, p_sSortSlug){

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sFilterSlug='+p_sFilterSlug;
BaseAjax._xArgs.data += '&p_sSortSlug='+p_sSortSlug;
BaseAjax._xArgs.data += '&p_nShowId='+document._nShowId;
BaseAjax._xArgs.data += '&p_sShowSlug='+document._sShowSlug;

BaseAjax._xArgs.returnDiv = '#show_widget_browser'
BaseAjax._xArgs.loaderDiv = '#show_widget_browser_inside'
BaseAjax._xArgs.loaderType = 'white'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},

loadPlayerIntoShowPage: function(p_sDomTarget, l_sPlatformId, l_sVideoTitle, l_sVideoThumbnail, l_sVideoHeight, l_sVideoWidth, l_nVideoId, p_sHref){
        //set video meta data
l_sVideoTitle = l_sVideoTitle.toUpperCase();
var l_aTextInfo = { c:'ffffff',type:'bl','bg':'3A3A3A',tran:true,s:14,t: ''+l_sVideoTitle+'', w:375, 'bb':'5px' }
l_sTitleNameUrl = makeCustomImage(l_aTextInfo);
  l_sTitleNameDiv = '<img alt = '+l_sVideoTitle+' src = '+l_sTitleNameUrl+' class="customimg">'; 
$('#show_widget_meta').html(l_sTitleNameDiv);

//set pick a side button:
l_sPickASideButton = '<div class="pickaside_button sprite"><a class="png" href="'+p_sHref+'#addcomment"><span>Pick A Side</span></a></div>'; 
$('#pickaside_button_meta').html(l_sPickASideButton);

//display video player
l_aVideoInfo = new Array();
l_aVideoInfo["VideoThumbnail"] = l_sVideoThumbnail;
l_aVideoInfo["VideoHeight"] = l_sVideoHeight;
l_aVideoInfo["VideoWidth"] = l_sVideoWidth;
l_aVideoInfo["wmode"] = "transparent";
l_aVideoInfo["setInstreamAd"] = true;
l_aVideoInfo["autoplay"] = true;

if(document._bVideoAutoPlay){
 document._bVideoAutoPlay = null;
} else {
$.scrollTo('.show_detail_content', 300, { easing:'swing', offset: 20 });
}


 document._bArticleFromShows = true;
 document._bIncrementRecommendForShows = true;
 document.l_sCMSArticleSlug = "http://www.versus.com/shows/"+l_sVideoTitle;
 document.l_sCMSArticleTitle = l_sVideoTitle;
 document.l_aCMSArticleIds = _xCore.getYesNoCommentIds(l_nVideoId, "604");
 document.l_aCMSArticleTags = "";
 document.l_sCMSArticleSection = "test_section_shows";
 _xCore.checkIfArticleExists(""+l_nVideoId+"_604_");
 
//set platform video player 
_xThePlatformVideoPlayer.displayPlayer(p_sDomTarget, l_sPlatformId, l_aVideoInfo);
}

}


// JavaScript Document



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

})

_xTruebox ={

init:function(){
//setTimeout(function(){_xTruebox.makeEditVideo();},500);
//setTimeout(function(){_xTruebox.makeSignupRegister();},500);
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, #confirm-thankyou, #confirm-error, #thankyou').live('click',function(){
_xTruebox._sGroupUploadKey = null
_xTruebox._sUserGroupBlog = null;
_xTruebox._sUserFiresUp = null;
_xTruebox._sRecommendationKey = null;
_xTruebox._sRecommendationType = null;
_xTruebox._sRecommendationLoc = null;
_xTruebox.closePopup();
});
$('#truebox').find('.check').live('click',function(){
$(this).toggleClass('check_selected');
});



},


makeEditVideo:function(){
this.makePopup('create','event');
},

makePopup:function( p_sAction,p_sAssetType, p_sFunctionName, p_sGroupKey, p_sTags){
this.makePopupOverlay();
$('#truebox').empty().show().css('top',  $(document).scrollTop()+100  );

switch(p_sAction+p_sAssetType){
case 'uploadvideo':
   this.makePopupAssetEditor(p_sAction,p_sAssetType, "_xPluckVideo.uploadVideo('groups')");
break;
case 'editvideo':
case 'uploadimage':
   this.makePopupAssetEditor(p_sAction,p_sAssetType, "_xPluckPhoto.uploadPhoto('groups')");
break;   
case 'editimage':
break;
case 'creategroup':
   _xForms.displayGroupForm(null);
break;
case 'createblog':
   _xForms.displayGroupBlog('post');
break;
case 'userblog':
   _xForms.displayUserBlog(); 
break;
case 'createevent':
   _xForms.displayGroupEvent('post');
break;   
case 'uploadugcphoto':
    _xUGCContent.upload('upload', 'image', p_sFunctionName, p_sGroupKey, p_sTags);
break;
case 'uploadugcvideo':
    _xUGCContent.upload('upload', 'video', p_sFunctionName, p_sGroupKey, p_sTags);
break;
case 'uploadugcblog':
    _xUGCContent.upload('upload', 'blog', p_sFunctionName, p_sGroupKey, p_sTags);
break;
case 'joinugcgroup':
_xTruebox.displayJoinGroupForm(p_sFunctionName, p_sGroupKey, p_sTags);
break;
case 'joingroup':
      _xForms.displayThankYouMessage();
break;
case 'sendemail':
      _xForms.displayEmailForm(p_sFunctionName, p_sGroupKey);
    break;  
case 'submitfeedback':
_xTruebox.displayFeedbackForm();
break;
case 'submithdrequest':
_xTruebox.displayHDRequestForm();
break;
case 'submitforgotpw':
_xTruebox.displayForgotPwForm();
break;
case 'sharesocial':
     _xTruebox.shareSocial(p_sFunctionName, p_sGroupKey);
break;


}

},

_bSubmitForgotPwFormSent: false,

displayForgotPwForm: function(){
$('#truebox').attr('class','truebox png truebox_forgotpw');

var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_forgotpw">Forgot Your Password?</div>'+
'<div id="forgotpw_content" class="forgotpw_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div class="forgotpw_msg"></div>'+

'<div id="forgotpw_form">'+
'<div class="txt txt_emailaddress">Email Address</div>'+
'<input type="text" class="text forgotpw_email" id="forgotpw_email" />'+

'<div class="gap20"></div>'+

'<div class="submitbtn sprite"><a href="javascript:void(0)" onclick="_xTruebox.submitForgotPwForm()" ><span>Submit</span></a></div>'+
'</div>'+
'<div id="return_div"></div>'+
'</div>';
  
$('#truebox').html(l_sHtml);

},

submitForgotPwForm: function(){
if(_xTruebox._bSubmitForgotPwFormSent) return false;

var l_sEmail =  $("#forgotpw_email").val();

if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test(l_sEmail) == false){
alert("Email Address is in an invalid format.");
return false;
}

_xTruebox._bSubmitForgotPwFormSent = true;


BaseAjax._xArgs.data = 'a=SubmitForgotPwForm&l_sEmail='+l_sEmail;
BaseAjax._xArgs.callBack = _xTruebox.submitForgotPw_callback;

BaseAjax.makeAjaxCall(AJAX_URL);
},

submitForgotPw_callback: function(){
_xTruebox._bSubmitForgotPwFormSent = false;
$('#return_div').html(BaseAjax.returnVar); // p_sResult will either call displayForgotPwThanks or displayForgotPwError
},

displayForgotPwThanks: function(){
$('#truebox').attr('class','truebox png truebox_forgotpw_thankyou');

var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_forgotpw">Forgot Your Password?</div>'+
'<div id="forgotpw_content" class="forgotpw_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div class="forgotpw_msg"></div>'+
'<div class="sprite closethis"><a href="javascript:void(0);" onclick="_xTruebox.closePopup();"><span>Close This</span></a></div>'+
'</div>';
  
$('#truebox').html(l_sHtml);
},

displayForgotPwError: function(){
$('#truebox').attr('class','truebox png truebox_forgotpw_error');

var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_forgotpw">Forgot Your Password?</div>'+
'<div id="forgotpw_content" class="forgotpw_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div class="forgotpw_msg"></div>'+
'<div class="sprite tryagain"><a href="javascript:void(0);" onclick="_xTruebox.displayForgotPwForm();"><span>Try Again</span></a></div>'+
'</div>';
  
$('#truebox').html(l_sHtml);
},


displayHDRequestForm: function(){
   $('#truebox').addClass('truebox_asseteditor').addClass('truebox_hd_req');
   
$('#truebox').load('/_site/templates/hdrequest_popup.php');

},

_bSubmitHDFormSent: false,

submitHDForm:function(){
if(_xTruebox._bSubmitHDFormSent) return false;

var l_sFirstName =  $("#hd_firstname").val();
var l_sLastName =  $("#hd_lastname").val();
var l_sCity =  $("#hd_city").val();
var l_sState = $("#hd_state_dropdown").data('choice')
var l_sEmail =  $("#hd_email").val();
var l_sPhone =  $("#hd_phone").val();
var l_sCable =  $("#hd_cable").val();
var l_sMessage =  $("#hd_comments").val();

 var l_asErrors = new Array();

if(/[a-zA-Z]{2,}/.test( l_sFirstName ) == false ||
(/[a-zA-Z]{2,}/.test( l_sLastName) == false ) )
l_asErrors.push("Sorry, your Name or Last Name was too short. Please enter at least 2 characters.");

if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test(l_sEmail) == false)
l_asErrors.push("Email Address is in an invalid format.");

if(!l_sCity)
l_asErrors.push("Please enter a City.");

if(!l_sState)
l_asErrors.push("Please enter a State.");

if(!l_sCable)
l_asErrors.push("Please enter a Cable Provider.");


if(l_asErrors.length > 0){
alert(l_asErrors.join("\n"));
return false;
}

_xTruebox._bSubmitHDFormSent = true;

BaseAjax._xArgs.data = 'a=SubmitHDForm';
BaseAjax._xArgs.data += '&l_sFirstName='+l_sFirstName;
BaseAjax._xArgs.data += '&l_sLastName='+l_sLastName;
BaseAjax._xArgs.data += '&l_sCity='+l_sCity;
BaseAjax._xArgs.data += '&l_sState='+l_sState;
BaseAjax._xArgs.data += '&l_sEmail='+l_sEmail;
BaseAjax._xArgs.data += '&l_sPhone='+l_sPhone;
BaseAjax._xArgs.data += '&l_sCable='+l_sCable;
BaseAjax._xArgs.data += '&l_sMessage='+l_sMessage;

BaseAjax._xArgs.callBack = _xTruebox.submitHDForm_callback;

BaseAjax.makeAjaxCall(AJAX_URL);
},
submitHDForm_callback:function(){
_xTruebox._bSubmitHDFormSent = false;

  var l_sStartText = 'FOR SENDING YOUR HD REQUEST';
  var l_aTextInfo = { v_height:44,lh:3,c:'000000',type:'med','bg':'ffffff',tran:true,s:13,w:230,cen:true,t:l_sStartText}
  var l_sImageUrl = makeCustomImage(l_aTextInfo);
  
$('#confirm-thankyou').addClass('thankyou_generic').append('<img style="top:193px" class="finishtext" src="'+l_sImageUrl+'" >')
$('#plck-media-content').hide();

  
  
},

displayFeedbackForm: function(){
  
$('#truebox').addClass('truebox_asseteditor').addClass('truebox_oneline');
  
var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_submitfeedback">Feedback</div>'+
'<div id = "asseteditor" >'+
'<div id = "asseteditor_content" class="asseteditor_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div id = "plck-media-content">'+

'<div class="txt txt_firstname">First Name</div>'+
'<div id = "invalid_title" class="invalid"></div>'+
'<input type="text" class="text" id="fb_firstname" />'+

'<div class="txt txt_lastname">Last Name</div>'+
'<div id = "invalid_title" class="invalid"></div>'+
'<input type="text" class="text" id="fb_lastname" />'+

'<div class="txt txt_email">Email</div>'+
'<input type="text" class="text" id="fb_email" />'+

'<div class="txt txt_comments">Comments</div>'+
'<textarea class="text" id="fb_comments" ></textarea>'+

'<div class="gap20"></div>'+
'<div id = "error" class = "plk_always_hide">true</div>'+
//'<div id = "action" class = "plk_always_hide">'+p_sAction+'</div>'+ //TODO: ASK ED

'<div class="submitbtn sprite"><a href="javascript:void(0)" onclick="_xTruebox.submitFeedbackForm()" ><span>Submit</span></a></div>'+
'<div class="cancelbtn sprite"><a href="javascript:void(0)" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>'+
'</div>'+
'<div id = "media-loading" class="plk_always_hide"><div class="video_loading_text">Loading...</div></div>'+
'<div id = "confirm-thankyou"></div>'+
'<div id = "confirm-error"></div>'+

'</div>'+
'</div>';
  
$('#truebox').html(l_sHtml);
   },

_bSubmitFeedbackFormSent :false,

submitFeedbackForm:function(){
if(_xTruebox._bSubmitFeedbackFormSent) return false;
 
var p_aErrors = new Array();
p_aErrors = _xTruebox.validateFeedbackForm();

if(p_aErrors.length > 0){
alert(p_aErrors.join("\n"));
return false;
}

var l_sFirstName =  $("#fb_firstname").val();
var l_sLastName =  $("#fb_lastname").val();
var l_sEmail =  $("#fb_email").val();
var l_sMessage =  $("#fb_comments").val();

_xTruebox._bSubmitFeedbackFormSent = true;

BaseAjax._xArgs.data = 'a=SubmitFeedback';
BaseAjax._xArgs.data += '&p_sFirstName='+l_sFirstName;
BaseAjax._xArgs.data += '&p_sLastName='+l_sLastName;
BaseAjax._xArgs.data += '&p_sEmail='+l_sEmail;
BaseAjax._xArgs.data += '&p_sMessage='+l_sMessage;

BaseAjax._xArgs.callBack = _xTruebox.submitFeedbackForm_callback;

BaseAjax.makeAjaxCall(AJAX_URL);

},

submitFeedbackForm_callback:function(){

_xTruebox._bSubmitFeedbackFormSent = false;

var l_sStartText = 'FOR SENDING YOUR FEEDBACK';
var l_aTextInfo = { v_height:44,lh:3,c:'000000',type:'med','bg':'ffffff',tran:true,s:13,w:230,cen:true,t:l_sStartText}
var l_sImageUrl = makeCustomImage(l_aTextInfo);
  
$('#confirm-thankyou').addClass('thankyou_generic').append('<img style="top:193px" class="finishtext" src="'+l_sImageUrl+'" >')
$('#plck-media-content').hide();

},

validateFeedbackForm:function(){
var l_asErrors = new Array();

if(/[a-zA-Z]{2,}/.test( $("#fb_firstname").val() ) == false ||
(/[a-zA-Z]{2,}/.test( $("#fb_lastname").val() ) == false ) )
l_asErrors.push("Sorry, your Name or Last Name was too short. Please enter at least 2 characters.");

if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test($("#fb_email").val()) == false)
l_asErrors.push("Email Address is in an invalid format.");

if(!$("#fb_comments").val())
l_asErrors.push("Please enter a comment.");

return l_asErrors;

},


displayJoinGroupForm: function(p_sFunctionName, p_sGroupKey, p_nColumnNumber){
  
 if(_xUser.getCookie("")){
  
  var l_sCurrentCookie = _xValidate.getCookie("at");
  if(l_sCurrentCookie){
//get userkey from cookie
l_aCookieInfo = l_sCurrentCookie.split("%26");
l_aUserKey = l_aCookieInfo[0].split("=");
l_sUserKeyInfo = l_aUserKey[1];
l_sUserKeySplit = l_sUserKeyInfo.split("%3D");
l_sUserKey = l_sUserKeySplit[1];

  
$('#truebox').addClass('truebox_joinugcgroup');
  
var l_sText = 'ARE YOU SURE YOU WANT TO JOIN THIS GROUP?';
var l_aTextInfo = { c:'000000',type:'med','bg':'ffffff',tran:true,s:13,lh:4,w:230,cen:true,t:l_sText}
var l_sImageUrl = makeCustomImage(l_aTextInfo);
    var l_sModuleType = "generic";
var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_joingroup">Join Group</div>'+
  '<div class="forgotpw_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div class="gap20"></div>'+
'<img src="'+l_sImageUrl+'" style="margin: 40px 0 40px 44px;" />'+
'<div class="yesbtn sprite"><a onclick="javascript:'+p_sFunctionName+'(\'' + p_sGroupKey + '\', \'' + l_sUserKey + '\', \'' + l_sModuleType + '\', \'' + p_nColumnNumber + '\')"><span>Yes</span></a></div>'+
'<div class="nobtn sprite"><a href="javascript:void(0)" onclick="_xTruebox.closePopup();"><span>No</span></a></div>'+
 '</div>';
  
$('#truebox').html(l_sHtml);
  
   }

  }else{
  _xTruebox.makeSignupRegister();
        } 
   },


makePopupAssetEditor:function(p_sAction,p_sAssetType, p_sFunctionName){
  if(_xUser.getCookie("")){
$('#truebox').addClass('truebox_asseteditor');


var l_sHtml = ''+
'<div class="png txt txt_'+p_sAction+p_sAssetType+'">'+p_sAction+' '+p_sAssetType+'</div>'+
'<div id = "asseteditor" >'+
'<div id = "asseteditor_content" class="asseteditor_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div id = "plck-media-content">'+
'<form id="uploadassetform" class="uploadassetform" method="post" action="" enctype="multipart/form-data">'+
'<input id="galleryKey" type="hidden" name="galleryKey" value="" />'+
'<input type="file" id="assetupload" class="assetupload" name="Filedata" onChange="_xValidate.validateMedia(this.value, \'' +p_sAssetType+ '\' )"/>'+
'</form>'+
'<div id = "invalid_file_format" class= "invalid_file_format"></div>'+

'<div class="hr_twin_light"></div>'+
'<div class="txt txt_title">Title</div>'+
'<div id = "invalid_title" class="invalid"></div>'+
'<input type="text" class="text" id="title" />'+
'<div class="txt txt_description">Description</div>'+
'<textarea class="text" id="desc" ></textarea>'+
'<div class="txt txt_tags">Tags</div>'+
'<input type="text" class="text" id="tags" />'+
'<div class="gap20"></div>'+
'<div id = "error" class = "plk_always_hide">true</div>'+
'<div id = "action" class = "plk_always_hide">'+p_sAction+'</div>'+

'<div class="'+p_sAction+'btn sprite"><a onclick = "javascript:'+p_sFunctionName+'" ><span>'+p_sAction+'</span></a></div>'+
'<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>'+
'</div>'+
'<div id = "media-loading" class="plk_always_hide"><div class="video_loading_text">Loading...</div></div>'+
'<div id = "confirm-thankyou"></div>'+
'<div id = "confirm-error"></div>'+

'</div>'+
'</div>';


$('#truebox').html(l_sHtml);
  }else{
  _xTruebox.makeSignupRegister();
  }
  

},
   
shareSocial: function(p_sSectionName, f){

var l_bIsSelectedSectionName = false;
switch(p_sSectionName){
  case 'blogs-landing':
    var l_sArticleSlug = $(f).parents('.article_inner:first').find('.title').attr('href');
var l_sArticleUrl = "http://"+g_xVersusBaseDomain+l_sArticleSlug;
var l_sArticleTitleRaw = $(f).parents('.article_inner:first').find('.title').html();
l_bIsSelectedSectionName = true;
  break;
  case 'blog-detail':
    var l_sArticleTitleRaw = $(f).parents('.article_inner:first').find('#article_title').html();
var l_sArticleUrl = window.location.href;
l_bIsSelectedSectionName = true;
  break;
  case 'picture-detail':
    var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
l_bIsSelectedSectionName = true;
  break;
  case 'video-landing':
    var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleSlug = $(f).parents('.detail_meta:first').find('a').attr('href');//window.location.href;
var l_sArticleUrl = "http://"+g_xVersusBaseDomain+l_sArticleSlug;
l_bIsSelectedSectionName = true;
  break;
  case 'video-detail':
    var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
l_bIsSelectedSectionName = true;
  break;
  case 'gear':
    var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
l_bIsSelectedSectionName = true;
  break;
  case 'group-picture':
var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('#photo-detail-meta-template-final').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
l_bIsSelectedSectionName = true;
  break;
  case 'group-video':
   var l_sArticleTitleRaw = $(f).parents('.detail_meta:first').find('#video-detail-meta-template-final').find('.customimg').attr('alt');
   var l_sArticleUrl = window.location.href;
   l_bIsSelectedSectionName = true;
  break;
  case 'group-blog':
   var l_sArticleSlug = $(f).parents('.article_inner:first').find('.title').attr('href');
   var l_sArticleUrl = "http://"+g_xVersusBaseDomain+l_sArticleSlug;
   var l_sArticleTitleRaw = $(f).parents('.article_inner:first').find('.title').html();
   l_bIsSelectedSectionName = true;
  break;

}
//incase the switch case fails we assign the url of the page as the article url and title as the document title
if(l_bIsSelectedSectionName == false){
   var l_sArticleUrl = window.location.href;
   var l_sArticleTitleRaw = document.title;
   var l_sArticleTitle = addSlashes(l_sArticleTitleRaw);
}

var l_sArticleTitle = addSlashes(l_sArticleTitleRaw);
  
   $('#truebox').addClass('truebox_share');
   var l_sText = '';
   var l_aTextInfo = { c:'000000',type:'med','bg':'ffffff',tran:true,s:13,lh:4,w:230,cen:true,t:l_sText}
   var l_sImageUrl = makeCustomImage(l_aTextInfo);
   var l_sHtml = "";
   l_sHtml +=   '<div class="png txt txt_sharecontent">Share Content</div>'+
   '<div class="share_content">'+
   '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
   '<div class="gap20"></div>'+
   '<img src="'+l_sImageUrl+'" style="margin: 20px 0 20px 44px;" />'+
'<br class="clear"></br>'+
    '<a onclick="_xTruebox.shareButton(\'facebook\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/FaceBook_32x32.png?v=213"></a>&nbsp;&nbsp;'+ 
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'twitter\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/Twitter_32x32.png?v=213" alt="Twitter"></a>&nbsp;&nbsp;'+ 
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'digg\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/Digg_32x32.png?v=213" alt="Digg"></a>&nbsp;&nbsp;'+ 
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'reddit\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/Reddit_32x32.png?v=213" alt="Reddit"></a>&nbsp;&nbsp;'+ 
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'delicious\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/delicious_32x32.png?v=213" alt="Delicious"></a>&nbsp;&nbsp;'+  
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'technorati\', \''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/Technorati_32x32.png?v=213" alt="Technorati"></a>&nbsp;&nbsp;'+ 
'<a style="cursor:pointer" onclick="_xTruebox.shareButton(\'stumble-upon\',\''+l_sArticleUrl+'\', \''+l_sArticleTitle+'\');"><img src="/image/Stumbleupon_32x32.png?v=213" alt="StumbleUpon"></a>&nbsp;&nbsp;'+ 
'</div>';
  
  
   $('#truebox').html(l_sHtml);
},

shareButton: function(p_sSocialSource, p_sArticleUrl, p_sArticleTitle){
var l_xSharePopupWindow;
switch(p_sSocialSource) {
case 'facebook':
l_xSharePopupWindow = window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(p_sArticleUrl)+"&t="+encodeURIComponent(p_sArticleTitle), 'facebook_popup', 'width=800, height=400, resizable=yes, scrollbars=yes');
  break;
case 'twitter':
l_xSharePopupWindow = window.open("http://twitter.com/home?status="+encodeURIComponent(p_sArticleTitle)+" : "+encodeURIComponent(p_sArticleUrl), 'twitter_popup', 'width=820, height=460, resizable=yes, scrollbars=yes');
break;
case 'digg':
l_xSharePopupWindow = window.open("http://digg.com/submit?phase=2&url="+encodeURIComponent(p_sArticleUrl)+"&title="+encodeURIComponent(p_sArticleTitle), 'digg_popup', 'width=960, height=700, resizable=yes, scrollbars=yes');
break;
case 'reddit':
l_xSharePopupWindow = window.open("http://reddit.com/submit?url="+encodeURIComponent(p_sArticleUrl)+"&title="+encodeURIComponent(p_sArticleTitle), 'reddit_popup', 'width=860, height=730, resizable=yes, scrollbars=yes');
break;
case 'delicious':
l_xSharePopupWindow = window.open("http://delicious.com/save?v=5&noui&jump=close&url="+encodeURIComponent(p_sArticleUrl)+"&title="+encodeURIComponent(p_sArticleTitle), 'delicious_popup', 'width=600, height=400, resizable=yes, scrollbars=yes');
break;
case 'technorati':
l_xSharePopupWindow = window.open("http://technorati.com/faves?add="+encodeURIComponent(p_sArticleUrl), 'technorati_popup', 'width=970, height=570, resizable=yes, scrollbars=yes');
break;
case 'stumble-upon':
l_xSharePopupWindow = window.open("http://stumbleupon.com/submit?url="+encodeURIComponent(p_sArticleUrl)+"&title="+encodeURIComponent(p_sArticleTitle), 'stumbleupon_popup', 'width=960, height=700, resizable=yes, scrollbars=yes');
break;
}

//handle case for google chrome issue where window.focus() does not work
var isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
if(isChrome){
l_xSharePopupWindow.blur();
setTimeout(l_xSharePopupWindow.focus(), 0);
} else{
l_xSharePopupWindow.focus();
}
},
   
makePoll:function(p_nId){

this.makePopupOverlay();
$('#truebox').addClass('truebox_poll');
$('#truebox').show().css('top',  $(document).scrollTop() +30 );

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

BaseAjax._xArgs.data += '&p_nId='+p_nId;

BaseAjax._xArgs.returnDiv = '#truebox';

BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);


},

makeSignupRegister:function(){

this.makePopupOverlay();

$('#truebox').addClass('truebox_signupregister');

//if form was already AJAXed in (has HTML content)
if ( $('#truebox').html() ){
//reset INPUT elements in the form
$('#register_form').find('input').each(function() {
switch( $(this).attr('type') ) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                $(this).attr('checked','false');
        }
    });
    
// reset checkboxes (since our checkboxes are actualy styled DIVs )
$('#register_form').find('.check').each(function() {
$(this).removeClass('check_selected');
});

//reset login form
$('#login_form').find('input').each(function() {
switch( $(this).attr('type') ) {
case 'password':
            case 'text':
            $(this).val('');
            break;
        }
});

$('#login_errors').html('');
$('#register_errors').html('');

$('#register_errors').hide();
$('#login_errors').hide();

$('#return_div').html('');
$('#truebox').show().css('top',  $(document).scrollTop()  );
}else{
//if not - call server
$('#truebox').load('/_site/templates/signin_popup.php');
$('#truebox').show().css('top',  $(document).scrollTop()  );
}
},


makeMemberDirectory:function(l_sHtml){
this.makePopupOverlay();
$('#truebox').addClass('truebox_memberdirectory');
$('#truebox').show().css('top',  $(document).scrollTop()  );
$('#truebox').html( l_sHtml );

},


makePopupOverlay:function(){
var l_nWindowHeight = $(window).height();
var l_nBodyHeight = $('body').height();

var l_nTheHeight = (l_nWindowHeight > l_nBodyHeight)?l_nWindowHeight:l_nBodyHeight;
if(document.isIE6)
$('#truebox_overlay').show().height( l_nTheHeight + 200 );
else
$('#truebox_overlay').fadeIn(200).height( l_nTheHeight + 200 );

},

closePopup : function(){
if(_xHome._bPollOpen){
_xHome.cleanPollPopup();
}
if(_xTruebox._sGroupUploadKey){
//_xTruebox._sGroupUploadKey = null;
}

$('#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();
//console.log($('#truebox').html());
}

}


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


_xNavigation={

init:function(){
this.setHovers();
this.setTier4();
},

_nLoadDelay:400,

setHovers:function(){

$('#tier2').find('.link').live('mouseover',function(){
$(this).addClass('link_hover');
})
.live('mouseout',function(){
$(this).removeClass('link_hover');
});


$('#tier2').find('.changer_link').live('mouseover',function(){
var $this = $(this)
setTimeout(function(){
if($this.hasClass('link_hover') && !$this.hasClass('full_hover')  ){
$this.addClass('full_hover');
_xNavigation.tier2mouseover($this);
}
},_xNavigation._nLoadDelay);
})
.live('mouseout',function(){
var $this = $(this)
setTimeout(function(){
if((!$this.hasClass('link_hover'))&&$this.hasClass('full_hover')){
_xNavigation.tier2mouseout($this);
$this.removeClass('full_hover');
}
},_xNavigation._nLoadDelay);
});



$('#tier1').find('.tab').live('mouseover',function(){
$(this).addClass('link_hover');
var $this = $(this)
setTimeout(function(){
if($this.hasClass('link_hover') && !$this.hasClass('full_hover')  ){
$this.addClass('full_hover');
_xNavigation.tier1mouseover($this);
}
},_xNavigation._nLoadDelay);
})
.live('mouseout',function(){
$(this).removeClass('link_hover');
var $this = $(this)
setTimeout(function(){
if((!$this.hasClass('link_hover'))&&$this.hasClass('full_hover')){
_xNavigation.tier1mouseout($this);
$this.removeClass('full_hover');
}
},_xNavigation._nLoadDelay);
});


},



grabTier4:function(){
BaseAjax._xArgs.data = 'a=GetTierAjaxCall';
BaseAjax._xArgs.data += '&p_nTierType='+document._sTierType;
BaseAjax._xArgs.data += '&p_nSportsId='+document._nSportsId;

BaseAjax._xArgs.returnDiv = '#tier4_content'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},

tier1mouseover:function(p_xThis){
var l_sVertical = $(p_xThis).attr('rel');
if(l_sVertical=='sports'){
l_sVertical='';
_xNavigation.changeLowerTiersByTier1(l_sVertical,'/');
}
else
_xNavigation.changeLowerTiersByTier1(l_sVertical,'/'+l_sVertical+'/');

// preserve selected
$l_xTabSelected = $('#tier1').find('.tab_selected')
if(!$('#tier1').find('.original_selected').length){
$l_xTabSelected.addClass('original_selected');
}else{

}
$l_xTabSelected.removeClass('tab_selected');
$l_xTabSelected.find('a').removeClass('selected_tab');

$(p_xThis).addClass('tab_selected');
$(p_xThis).find('a').addClass('selected_tab');

},
tier1mouseout:function(p_xThis){

},

tier1mouseoverreset:function(){
$('#tier1').find('.tab_selected').removeClass('tab_selected').find('a').removeClass('selected_tab');
$('#tier1').find('.original_selected').addClass('tab_selected').find('a').addClass('selected_tab');
},

tier2mouseover:function(p_xThis){
var l_sHref = $(p_xThis).attr('rel');
var l_sVertical = l_sHref.replace(/\//g,'');
_xNavigation.changeLowerTiersByTier2(l_sVertical);
},
tier2mouseout:function(p_xThis){

},

_bChangedByTier1:false,
_bChangedByTier2:false,
_xResetAjaxCall :null,
_xResetTimeoutCall:null,

changeLowerTiersByTier1:function(p_sSlug,p_sHref){
BaseAjax._xArgs.data = 'a=ChangeNavOnTier1AjaxCall';
BaseAjax._xArgs.data += '&p_sSlug='+p_sSlug;
BaseAjax._xArgs.data += '&p_sHref='+p_sHref;
BaseAjax._xArgs.data += '&p_sRequest='+document._sRequestUri ;
BaseAjax._xArgs.data += '&p_sSportsSkin='+document._sSportsSkin;
BaseAjax._xArgs.data += '&p_bClosed=0';

BaseAjax._xArgs.returnDiv = '#tier234'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
_xNavigation._bChangedByTier1=true;
},

changeLowerTiersByTier2:function(p_sSlug){
BaseAjax._xArgs.data = 'a=ChangeNavOnTier2AjaxCall';
BaseAjax._xArgs.data += '&p_sSlug='+p_sSlug;
BaseAjax._xArgs.data += '&p_sRequest='+document._sRequestUri ;
BaseAjax._xArgs.data += '&p_bClosed=0';

BaseAjax._xArgs.returnDiv = '#tier34'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
_xNavigation._bChangedByTier2=true;
},

checkResetNav:function(){
_xNavigation._xResetTimeoutCall =  setTimeout(function(){
if(_xNavigation._bHeaderIn||_xNavigation._bTier4Opening||_xNavigation._bTier4Closing)
return false;
if(_xNavigation._bChangedByTier1){
BaseAjax._xArgs.data = 'a=ChangeNavOnTier1AjaxCall';
BaseAjax._xArgs.data += '&p_sRequest='+document._sRequestUri ;
BaseAjax._xArgs.data += '&p_sSportsSkin='+document._sSportsSkin;
if(0&&document._bIsSportsPage){
BaseAjax._xArgs.data += '&p_sSlug=';
BaseAjax._xArgs.data += '&p_sHref=/';
}else{
BaseAjax._xArgs.data += '&p_sSlug='+document._sRequestUri.replace(/\//g,'');
BaseAjax._xArgs.data += '&p_sHref='+document._sRequestUri;
}
BaseAjax._xArgs.data += '&p_bClosed=1';

BaseAjax._xArgs.returnDiv = '#tier234'
BaseAjax._xArgs.requestType = "GET"; 
_xNavigation._xResetAjaxCall = BaseAjax.makeAjaxCall(AJAX_URL);
_xNavigation._bChangedByTier1=false
_xNavigation._bChangedByTier2=false
}else if(_xNavigation._bChangedByTier2){
BaseAjax._xArgs.data = 'a=ChangeNavOnTier2AjaxCall';
BaseAjax._xArgs.data += '&p_sSlug='+document._sSportsSkin;
BaseAjax._xArgs.data += '&p_sRequest='+document._sRequestUri ;
BaseAjax._xArgs.data += '&p_bClosed=1';

BaseAjax._xArgs.returnDiv = '#tier34'
BaseAjax._xArgs.requestType = "GET"; 
_xNavigation._xResetAjaxCall = BaseAjax.makeAjaxCall(AJAX_URL);
_xNavigation._bChangedByTier2=false
}
},250);
},

_bTier4Opening : false,
_bTier4Closing : false,
_bTier4In : false,
_bTier4ToHover : false,
_bTier4QueueExpand : false,
_bTier4QueueCollapse : false,
_xTier4Timer:null,
_nTier4Delay:500,
_nTier4Speed:200,

setTier4:function(){

$('#header').hover(function(){
_xNavigation._bTier4Opening = false;
if(_xNavigation._xResetAjaxCall){
if(BaseAjax.abort(_xNavigation._xResetAjaxCall)){
_xNavigation._bChangedByTier1=true;
}
_xNavigation._xResetAjaxCall = null;
}
if(_xNavigation._xResetTimeoutCall){
clearTimeout(_xNavigation._xResetTimeoutCall)
_xNavigation._xResetTimeoutCall = null;
}

if(_xNavigation._bTier4Opening){
_xNavigation._bTier4QueueCollapse=false
_xNavigation._bTier4QueueExpand=false;
return false;
}

_xNavigation._bHeaderIn = true;
clearTimeout(_xNavigation._xTier4Timer);
_xNavigation._xTier4Timer = setTimeout(function(){
if(!_xNavigation._bTier4Closing){
if(!_xNavigation._bTier4In){
if(_xNavigation._bHeaderIn){
_xNavigation._bTier4Opening = true;
_xNavigation.openTier4();
}
}
}else{
_xNavigation._bTier4QueueCollapse=false
_xNavigation._bTier4QueueExpand=true;
}
},_xNavigation._nTier4Delay);

},function(){
//return;
if(_xNavigation._bTier4Closing){
_xNavigation._bTier4QueueCollapse=false
_xNavigation._bTier4QueueExpand=false;
return false;
}
_xNavigation._bHeaderIn = false;
clearTimeout(_xNavigation._xTier4Timer);
_xNavigation._xTier4Timer = setTimeout(function(){
if(!_xNavigation._bHeaderIn){
if(!_xNavigation._bTier4Opening){
_xNavigation._bTier4Closing = true;
_xNavigation.closeTier4();
}
else{
_xNavigation._bTier4QueueExpand=false
_xNavigation._bTier4QueueCollapse=true;
}
}
},_xNavigation._nTier4Delay);
});

},

openTier4:function(){
if(!_xNavigation._bTier4QueueCollapse){
$('#header_expand_btn').parent().hide();
$('#header_collapse_btn').parent().show();
$('#tier4').fadeIn(_xNavigation._nTier4Speed,function(){
_xNavigation._bTier4Opening = false;
_xNavigation._bTier4In = true
if(_xNavigation._bTier4QueueCollapse){
_xNavigation._bTier4QueueCollapse = false;
_xNavigation.closeTier4();
}
});
}else{
_xNavigation._bTier4Opening = false;
_xNavigation._bTier4QueueCollapse = false
_xNavigation._bTier4Closing = false;
}
},

closeTier4:function(){
$('#header_expand_btn').parent().show();
$('#header_collapse_btn').parent().hide();
$('#tier4').fadeOut(_xNavigation._nTier4Speed,function(){
_xNavigation._bTier4Closing = false;
_xNavigation._bTier4In = false
if(_xNavigation._bTier4QueueExpand){
_xNavigation.openTier4();
_xNavigation._bTier4QueueExpand = false;
}else{
_xNavigation.checkResetNav()
}
});
}





}

// JavaScript Document

$(document).ready(function(){

if( document._bIsBlog ){
_xBlog.init();
}

});

_xBlog={
init:function(){
this.setTables();
},

setTables:function(){

$('#article_inner').find('table').each(function(){

$(this).attr('cellspacing',0).attr('cellpadding',0).attr('bordercolor',"black");

$(this).find('tr').eq(0).find('th').addClass('top');

$(this).find('tr:odd').find('td').addClass('odd');
});

}


}

// JavaScript Document

$(document).ready(function(){

if( document._bIsShowDetail ){
_xShowDetail.init();
}

});

_xShowDetail={
init:function(){
this.setWidgetTabs();
},

setWidgetTabs:function(){

$('#show_widget .navtab').each(function(){
var l_nIndex = $('#show_widget .navtab').index(this);

$(this).click(function(){
  $('#show_widget .widgetarea').hide();
$('#show_widget .widgetarea'+l_nIndex).show();
  $('#show_widget .navtab').removeClass('navtab_selected');
  $(this).addClass('navtab_selected');
$(this).blur();
});

$(this).hover(function(){
$(this).addClass('navtab_hover');
},function(){
$(this).removeClass('navtab_hover');
});

});



}

}

// JavaScript Document

$(document).ready(function(){

if( document._bIsSweepstakesDetail ){
_xSweepstakesDetail.init();
}

});

_xSweepstakesDetail={
init:function(){
this.setWidgetTabs();
this.setJscrollPane();
},

setWidgetTabs:function(){

$('#ss_info_container').find('.navtab').hover(
function(){ $(this).addClass('navtab_hover'); },
function(){ $(this).removeClass('navtab_hover'); }
);

},

setJscrollPane:function(){
$('#ss_info_container').find('.ss_info_text_inner').jScrollPane( {scrollbarWidth: 10, dragMaxHeight: 21} );
}

}


// JavaScript Document

$(document).ready(function(){

if( document._bIsSportsPage ){
_xSportsPage.init();
_xWidgetStats.init();
}

});

_xSportsPage={
_nStandingsTotalWidth:0,
_nStandingsViewableWidth:0,
_nStandingsExtraWidth:0,
_nStandingsPosition:0,

init:function(){
this.setRelatedHovers();
//this.setStandingsBarWidths();
this.setStandingsArrows();
this.setStandingsLinks();
},

setRelatedHovers:function(){

$('#sport_related_content').find('.sport_rc_element').live('mouseover',
function(){ 
$(this).attr('rel','on');
$(this).addClass('sport_rc_hover').find('a').fadeIn(200); 
}
);

$('#sport_related_content').find('.sport_rc_element').live('mouseout',
function(){
var l_xThis = $(this);
$(l_xThis).attr('rel','off');
setTimeout(function(){
if( $(l_xThis).attr('rel') == 'off' )
$(l_xThis).removeClass('sport_rc_hover').find('a').fadeOut(200); 
},100);
}
);

},

setStandingsBarWidths:function(){
var item_count = $('#standings_item_shifter').children('.standings_visible').children('.standings_bar_item').size();
this._nStandingsTotalWidth = item_count * 182; //width of one item is 181px (including padding/border)

this._nStandingsViewableWidth = $('#standings_item_wrapper').width();
this._nStandingsExtraWidth = this._nStandingsTotalWidth - this._nStandingsViewableWidth;
$('#standings_item_shifter').children('.standings_visible').width(this._nStandingsTotalWidth);
 
if (this._nStandingsExtraWidth <= 5)
$('#standings_bar_right').addClass('sprite_selected'); //deactivate arrow
else
$('#standings_bar_right').removeClass('sprite_selected'); //(re)activate arrow

$('#standings_bar_left').addClass('sprite_selected'); //left arrow deactivated by default on page load and every time new standings-set is loaded

$('#standings_item_shifter').find('.standings_set').each(function(){
$l_xItemSet = $(this).find('.standings_bar_item');
$l_xItemSet.eq( $l_xItemSet.length-1 ).addClass('no_bord');

 });
},

setStandingsArrows:function(){
$('#standings_bar_right').click(function(){
if (!$(this).hasClass('sprite_selected')){
_xSportsPage._nStandingsPosition -= 182;

$('#standings_item_shifter').animate({marginLeft: _xSportsPage._nStandingsPosition}, 200 );
if (_xSportsPage._nStandingsPosition < 0)
$('#standings_bar_left').removeClass('sprite_selected'); //activate arrow
if (_xSportsPage._nStandingsPosition + _xSportsPage._nStandingsExtraWidth <= 5)
$('#standings_bar_right').addClass('sprite_selected'); //deactivate arrow
}
});

$('#standings_bar_left').click(function(){
if (!$(this).hasClass('sprite_selected')){
_xSportsPage._nStandingsPosition += 182;

$('#standings_item_shifter').animate({marginLeft: _xSportsPage._nStandingsPosition}, 200 );
if (_xSportsPage._nStandingsPosition == 0)
$('#standings_bar_left').addClass('sprite_selected'); //deactivate arrow
$('#standings_bar_right').removeClass('sprite_selected'); //activate arrow
}
});
},

setStandingsLinks:function(){
$('#standings_bar_header').find('.standings_link').click(function(){
l_sLinkRel = $(this).attr('rel');

if(l_sLinkRel == 'east' || l_sLinkRel == 'west'){
$('#standings_bar_header').find('.sprite_selected').removeClass('sprite_selected');
$(this).parent().addClass('sprite_selected');

$chosenBtn = $('#standings_bar_header').find('.'+l_sLinkRel+' .sprite').eq(0)

$chosenBtn.addClass('sprite_selected');
$('#division_'+$chosenBtn.children('a').attr('rel')).addClass('standings_visible').siblings('.standings_visible').removeClass('standings_visible');

$('#standings_bar_header').find('.btn_holder').hide();
$('#standings_bar_header').find('.'+l_sLinkRel).show();

}else{
$('#standings_bar_header').find('.east .sprite_selected, .west .sprite_selected').removeClass('sprite_selected');
$(this).parent().addClass('sprite_selected');
$('#division_'+l_sLinkRel).addClass('standings_visible').siblings('.standings_visible').removeClass('standings_visible');
}
//reset standings-bar shifter position to 0
_xSportsPage._nStandingsPosition = 0;
$('#standings_item_shifter').css('margin-left', 0);

//reset shifter width values now that a new standings_set is in view
_xSportsPage.setStandingsBarWidths();
});
}

}







function _xClassWidgetStatsDivision(){
this._sName;
this._aTeams;
this.init = function(){this._aTeams = new Array(); }
this.setName = function(p_sData){ this._sName = p_sData }
this.getName = function(){ return this._sName }
this.addTeam = function(p_sData){ this._aTeams.push(p_sData) }
this.getTeams = function(p_sData){ return this._aTeams }
this.init();
}

function _xClassWidgetStatsConference(){
this._sName;
this._aDivisions; 
this.init = function(){ this._aDivisions = new Array(); }
this.setName = function(p_sData){ this._sName = p_sData }
this.getName = function(){ return this._sName }
this.addDivision = function(p_sData){ this._aDivisions.push(p_sData) }
this.getDivisions = function(p_sData){ return this._aDivisions }
this.init();
}

_xWidgetStats = {

_nInterval : 5000,
 _sLastUpdate : '',
_aEasternConference : null,
_aWesternConference : null,

_aAtlanticDivision: null,
_aNortheastDivision : null,
_aSoutheastDivision : null,
_aCentralDivision : null,
_aNorthwestDivision : null,
_aPacificDivision : null,

init : function(){
if($('#stats-widget').length){
this.intervalTick();
}
},

intervalTick : function(){

if($('#stats-widget').find('#shsTimestamp').length == 1){

  var l_sTimeStamp = $('#stats-widget').find('#shsTimestamp').text();
if(this._sLastUpdate == l_sTimeStamp){
//alert('same');
}else{
this._sLastUpdate = l_sTimeStamp;
this.parseData();
}
setTimeout( function(){ _xWidgetStats.intervalTick()}, this._nInterval);
}else{
setTimeout( function(){ _xWidgetStats.intervalTick()}, 500);
} 
},

buildTeamsArrayForConference : function(p_xConference){
var l_aTeamsInOrder = new Array();
var l_aDivisions = p_xConference.getDivisions();
for(var i=0; i<l_aDivisions.length; i++){
var l_aTeams = l_aDivisions[i].getTeams();
for(var j=0; j<l_aTeams.length; j++){
l_aTeamsInOrder.push(l_aTeams[j]);
}
}
return l_aTeamsInOrder;
},


ouputDivision : function(p_xDivision,p_sDivId){
var l_aTeams = p_xDivision._aTeams;
var l_sOutput = '';
for(var j=0; j<l_aTeams.length; j++){
l_sOutput += '<div class="standings_bar_item">';
l_sOutput += '<div class="rank_number rank'+(j+1)+'"></div>';

l_sOutput += '<div class="rank_info"><img src="/image/nhl_logos/'+l_aTeams[j].name.replace(/[\s.]+/, "")+'.png?v=213" /><p>'+l_aTeams[j].name+'</p><p class="rank_record">'+l_aTeams[j].wins+'W-'+l_aTeams[j].losses+'L-'+l_aTeams[j].ol+'OT<br/>'+l_aTeams[j].points+'PTS</p></div></div>';
}
$('#'+p_sDivId).html(l_sOutput);
},


ouputConference : function(p_xConference,p_sDivId){
var l_aTeams = this.buildTeamsArrayForConference(p_xConference);
var l_sOutput = '';
for(var j=0; j<l_aTeams.length; j++){
l_sOutput += '<div class="standings_bar_item">';

if(j<9){
l_sOutput += '<div class="rank_number rank'+(j+1)+'"></div>'; 
}
else{
l_sOutput += '<div class="rank_number_small"><div class="small_rank small_rank'+Math.floor((j+1)/10)+'"></div><div class="small_rank small_rank'+(j+1)%10+'"></div></div>';
}

l_sOutput += '<div class="rank_info"><img src="/image/_nhl_team_logo.gif?v=213" /><p>'+l_aTeams[j].name+'</p><p>'+l_aTeams[j].wins+'W-'+l_aTeams[j].losses+'L-'+l_aTeams[j].points+'TL</p></div></div>';
}
$('#'+p_sDivId).html(l_sOutput);
},

ouputOverall : function(p_aConferences,p_sDivId){
l_aOverallOrder = new Array();
for(var i=0; i<p_aConferences.length; i++){
var l_aTeams = this.buildTeamsArrayForConference(p_aConferences[i]);
for(var j=0; j<l_aTeams.length; j++){
l_aOverallOrder[l_aTeams[j].points+'.'+j*(i+1)] = l_aTeams[j];
}
}
var l_aTeamsOrder = this.keySort(l_aOverallOrder );
l_aTeams = l_aOverallOrder;
var l_sOutput = '';
for(var i=l_aTeamsOrder.length-1; i>0; i--){
var j = l_aTeamsOrder[i];
l_sOutput += '<div class="standings_bar_item"><div class="rank_number rank'+(j+1)+'"></div><div class="rank_info"><img src="/image/_nhl_team_logo.gif?v=213" class="png" /><p>'+l_aTeams[j].name+'</p><p>'+l_aTeams[j].wins+'W-'+l_aTeams[j].losses+'L-'+l_aTeams[j].points+'TL</p></div></div>'; 
}
$('#'+p_sDivId).html(l_sOutput);
},


keySort : function(array, flag) {
var keys = new Array();
for(k in array) { keys.push(k);}
keys.sort( function (a, b) {
if (flag && flag != 'undefined') {if(flag == 'integer') {a = parseInt(a); b = parseInt(b);}}
return (a > b) - (a < b);} );
return keys;
},
  
parseData : function(){

this._aAtlanticDivision= new _xClassWidgetStatsDivision();
this._aNortheastDivision = new _xClassWidgetStatsDivision();
this._aSoutheastDivision = new _xClassWidgetStatsDivision();
this._aCentralDivision = new _xClassWidgetStatsDivision();
this._aNorthwestDivision = new _xClassWidgetStatsDivision();
this._aPacificDivision = new _xClassWidgetStatsDivision();

this._aEasternConference = new _xClassWidgetStatsConference();
this._aWesternConference = new _xClassWidgetStatsConference();

this.parseConference('.shsECStand',this._aEasternConference);
this.parseConference('.shsWCStand',this._aWesternConference); 

//console.dir(this._aEasternConference);

//this.ouputConference(this._aEasternConference,'standings_set_east');
//this.ouputConference(this._aWesternConference,'standings_set_west');

this.ouputDivision(this._aEasternConference._aDivisions[0],'division_atlantic');
this.ouputDivision(this._aEasternConference._aDivisions[1],'division_northeast');
this.ouputDivision(this._aEasternConference._aDivisions[2],'division_southeast');

this.ouputDivision(this._aWesternConference._aDivisions[0],'division_central');
this.ouputDivision(this._aWesternConference._aDivisions[1],'division_northwest');
this.ouputDivision(this._aWesternConference._aDivisions[2],'division_pacific');

//this.ouputOverall(new Array(this._aEasternConference,this._aWesternConference),'standings_set_overall');
_xSportsPage.setStandingsBarWidths();

},


parseConference : function(p_sDivId,p_aConference){
 
var l_aDivision = null;
$('#stats-widget').find(p_sDivId).find('tr').each( function(){

switch( $(this).attr('class') ){
case 'shsTableTtlRow':  break;
case 'shsTableSubttlRow': // division
if(l_aDivision)
p_aConference.addDivision(l_aDivision);
l_aDivision = new _xClassWidgetStatsDivision();
l_aDivision.setName($(this).find('td').text());
break;
case 'shsRow1Row': case 'shsRow0Row':  // Team Stats
var l_xTeam = new Object();
l_xTeam.name = $(this).find('td:eq(0)').text();
l_xTeam.url = $(this).find('td:eq(0) a').attr('href');
l_xTeam.wins = $(this).find('td:eq(1)').text();
l_xTeam.losses = $(this).find('td:eq(2)').text();
l_xTeam.ol = $(this).find('td:eq(3)').text();
l_xTeam.points = $(this).find('td:eq(4)').text();
l_aDivision.addTeam(l_xTeam);
break;
} 
});
p_aConference.addDivision(l_aDivision);
}
}


// JavaScript Document

$(document).ready(function(){

if( document._bIsHome ){
_xHome.init();
}

});

_xHome={

_nWideVidWidth : 608,
_nWideVidHeight : 357,

_nVidWidth : 476,
_nVidHeight : 357,

_bIsAutoPlay:true,
_nAutoPlayTimeout:10000,
_xAutoPlayTimer:null,

_aMainFeatureArray:null,

_bChanging : false,
_bPollOpen:false,
_bListenToAutoPlay:false,

_nCurrentFeature : 0,
_nClosedWidgetHolderBottom : -67,
_nClosedWidgetWidth : 362,
_nOpenWidgetHolderBottom : 0,
_nOpenWidgetHolderBottomIE6 : -1,
_nOpenWidgetWidth : 446,

_bOpening : false,
_bClosing : false,

_bToOpen : false,
_bToClose : false,

_bOpenTimeout : false,
_bCloseTimeout : false,

init:function(){

this.setClicks();
this.setHover();
this.loadSelectorBasedOn(0)

this.startAutoPlay()

},

startAutoPlay:function(){
if(_xHome._bIsAutoPlay){
_xHome._bListenToAutoPlay = true;
clearTimeout(_xHome._xAutoPlayTimer);
_xHome._xAutoPlayTimer = setTimeout(function(){
if(_xHome._bListenToAutoPlay){
_xHome.changeFeatureBy(1)
}
   },_xHome._nAutoPlayTimeout)

}
},

stopAutoPlay:function(){
_xHome._bListenToAutoPlay = false;
_xHome._bToOpen = false;
clearTimeout(_xHome._xAutoPlayTimer);
},

setClicks:function(){

$('#mainfeature_selectors').children('.left').click(function(){
_xHome.changeFeatureBy(-1);
});
$('#mainfeature_selectors').children('.right').click(function(){
_xHome.changeFeatureBy(1);
});

$('#mainfeature_pagination_holder').children('a').click(function(){
 $('#unique_banner_instream_300x250').hide();
var l_nNewFeature =  $(this).attr('rel') 
_xHome.changeFeature(l_nNewFeature);
$(this).blur();
});

},

showPollResults:function(p_nHomeFeature){

var l_sText = _xHome._aMainFeatureArray[p_nHomeFeature].text
var l_nYes = _xHome._aMainFeatureArray[p_nHomeFeature].yes
var l_nNo = _xHome._aMainFeatureArray[p_nHomeFeature].no;

var l_nPercentYes = Math.round(l_nYes/(l_nYes+l_nNo)*100);
var l_nPercentNo = Math.round(l_nNo/(l_nYes+l_nNo)*100);

if(l_nPercentNo<10) var l_sGraphString = '0000'+l_nPercentNo;
else if(l_nPercentNo==100) var l_sGraphString = '00100';
else var l_sGraphString = '000'+l_nPercentNo;

var l_sHtml = '<div class="col1"><p>'+l_sText+'</p></div>'+
'<div class="col2"><img src="/image/graph/PieGraph_50_'+l_sGraphString+'.png?v=213" class="png"><p class="yes">I\'M IN! '+l_nPercentYes+'%</p>'+
'<p class="no">NO WAY! '+l_nPercentNo+'%</p></div><div class="gap10"></div>'

$('#home_pollresult_holder').show().html(l_sHtml);

},

hidePollResults:function(){

$('#home_pollresult_holder').empty();

},

loadSelectorBasedOn:function(l_nId){
l_nId = parseInt(l_nId);
var l_nPrev = (l_nId)?(l_nId-1):this._aMainFeatureArray.length-1;
var l_nNext = (l_nId+1)%(this._aMainFeatureArray.length);

var l_xPrev = this._aMainFeatureArray[l_nPrev];
var l_xNext = this._aMainFeatureArray[l_nNext];
var l_xThis = this._aMainFeatureArray[l_nId];

$('#mainfeature_left_title').html( l_xPrev.title );
$('#mainfeature_right_title').html( l_xNext.title );
$('#mainfeature_left_img').attr('src', l_xPrev.thumburi );
$('#mainfeature_right_img').attr('src', l_xNext.thumburi );

$('#mainfeature_badge').css('top',l_xThis.badgey+'px')
$('#mainfeature_badge').css('left',l_xThis.badgex+'px')
$('#badge_readmore').attr('href',l_xThis.url)

var l_sModHtml1 = (l_xThis.mod1html)?l_xThis.mod1html:'<div class="gap20"></div>';
var l_sModHtml2 = (l_xThis.mod2html)?l_xThis.mod2html:'<div class="gap20"></div>';
var l_sModHtml3 = (l_xThis.mod3html)?l_xThis.mod3html:'<div class="gap20"></div>';


$('#home_mods').children('.home_mod_1').html( l_sModHtml1 );
$('#home_mods').children('.home_mod_2').html( l_sModHtml2 );
$('#home_mods').children('.home_mod_3').html( l_sModHtml3 );

$('.mainfeature_video').empty();
if(l_xThis.platformvideocode != 0){
$('#returndiv').html(l_xThis.platformvideocode);
$('.mainfeature_video_holder').show();
}else if(l_xThis.pluckvideourl){
var flashvars = {p_sURL:l_xThis.pluckvideourl};
var params = { menu:false, wmode:'transparent', bgcolor:'000000', allowFullScreen:true};
var attributes = {};
swfobject.embedSWF("/_site/swf/VersusVideoPlayer.swf", "mainfeature_video", this._nWideVidWidth, this._nWideVidHeight, "9.0.0","_site/swf/expressInstall.swf", flashvars, params, attributes);
$('.mainfeature_video_holder').show();
}
else{
$('.mainfeature_video_holder').hide();
}

_xHome.hidePollResults();
if(l_xThis.pollid && l_xThis.pollid != "0"){
$('#mainfeature_badge').children('.sprite_poll').show();
$('#home_poll').attr('rel',l_xThis.pollid);
if(l_xThis.pollfade){
$('#mainfeature_badge').children('.sprite_poll').addClass('sprite_poll_faded')
$('#mainfeature_badge').children('.sprite_poll_cover').show();
_xHome.showPollResults(l_nId);
}else{
$('#mainfeature_badge').children('.sprite_poll').removeClass('sprite_poll_faded')
$('#mainfeature_badge').children('.sprite_poll_cover').hide();
$('#home_pollresult_holder').hide();
}
}else{
$('#mainfeature_badge').children('.sprite_poll').hide();
$('#mainfeature_badge').children('.sprite_poll_cover').hide();
}
},

changeFeatureBy:function(l_nInt){

var l_nNewFeature =   (this._nCurrentFeature+l_nInt)%(_xHome._aMainFeatureArray.length)

if(l_nNewFeature < 0)
 l_nNewFeature  = this._aMainFeatureArray.length - 1;
 
this.changeFeature(l_nNewFeature)
},
finishPollPopup:function(p_nHomeFeature,p_sText,p_nYes,p_nNo){

$('#mainfeature_badge').children('.sprite_poll').addClass('sprite_poll_faded')
$('#mainfeature_badge').children('.sprite_poll_cover').show();
_xHome._aMainFeatureArray[p_nHomeFeature].text = p_sText;
_xHome._aMainFeatureArray[p_nHomeFeature].yes = p_nYes;
_xHome._aMainFeatureArray[p_nHomeFeature].no = p_nNo;
_xHome._aMainFeatureArray[p_nHomeFeature].pollfade = 1;
_xTruebox.closePopup();
_xHome.showPollResults(p_nHomeFeature);

},
cleanPollPopup:function(){
_xHome.startAutoPlay()
_xHome._bPollOpen = false;
},
changeFeature:function(l_nId){
if(!_xHome._bPollOpen){
if(l_nId != _xHome._nCurrentFeature && !this._bChanging ){

_xHome.stopAutoPlay()

_xHome._nCurrentFeature = parseInt(l_nId)
$('#mainfeature_pagination_holder').children('.current').removeClass('current');
$('#mainfeature_pagination_holder').children('a').eq(l_nId).addClass('current');
var l_xData = _xHome._aMainFeatureArray[l_nId];

this._bChanging = true;
$body = $('body')
$bg_fader = $('#bg_fader')

l_nWidth = $body.width();
l_nHeight = $body.height();
l_sColor = $body.css('background-color');

$bg_fader.width( l_nWidth ) ;
$bg_fader.height( l_nHeight ) ;

$bg_fader.css('background-color',l_sColor)
$bg_fader.fadeIn(250,function(){

$body.css('background-image', 'url('+l_xData.mainuri+')' )

_xHome.loadSelectorBasedOn(l_nId)

$bg_fader.fadeOut(200,function(){
_xHome._bChanging = false;
_xHome.startAutoPlay();
});

})

}
}
},


setHover:function(){


$('#mainfeature_selectors').children('.left, .right').hover(function(){
$(this).addClass('hover');
},function(){
$(this).removeClass('hover');
});


$('#widget, #mainfeature_pagination_holder, #mainfeature_selectors').hover(function(){
_xHome._bOpenTimeout = true;
_xHome._bCloseTimeout = false;
setTimeout(function(){
if(_xHome._bOpenTimeout)
_xHome.openWidget();
},50)
},function(){
_xHome._bOpenTimeout = false;
_xHome._bCloseTimeout = true;
setTimeout(function(){
if(_xHome._bCloseTimeout)
_xHome.closeWidget();
},50)
});

},

openWidget:function(){
if(this._bClosing){
this._bToOpen = true;
}else{
if(this._bOpening){
this._bToClose = false;
}else{
_xHome.stopAutoPlay()
this._bOpening = true;
$('#mainfeature_selectors').fadeIn(300)
if(document.isIE6)
$('#widgetholder').animate({bottom:this._nOpenWidgetHolderBottomIE6+'px'},300);
else
$('#widgetholder').animate({bottom:this._nOpenWidgetHolderBottom+'px'},300);
$('#widget').animate({width:this._nOpenWidgetWidth+'px'},300,function(){
  _xHome.openCallback()
  }); 
$('#widget').css('overflow','visible');
}
}
},
closeWidget:function(){
if(this._bOpening){
this._bToClose = true;
}else{
if(this._bClosing){
this._bToOpen = false;
}else{
this._bClosing = true;
$('#mainfeature_selectors').fadeOut(300)
$('#widgetholder').animate({bottom:this._nClosedWidgetHolderBottom+'px'},300);
$('#widget').animate({width:this._nClosedWidgetWidth+'px'},300,function(){
 _xHome.closeCallback()
  }); 
$('#widget').css('overflow','visible');
}
}
},

openCallback : function(){
this._bOpening = false;
if(this._bToClose){
this._bToClose = false;
this.closeWidget()
}
},
closeCallback : function(){
this._bClosing = false;
if(this._bToOpen){
this._bToOpen = false;
this.openWidget()
}else{
_xHome.startAutoPlay()
}
}





}


$(document).ready(function(){
if(document._bIsSchedule )
_xSchedule.init();
});


_xSchedule = {

_nTimeWidth : 104,
_nCurrentTimeChunk:0,
_xTimeInner : null,
_aDayInner : null,
_bCopyDayOverCheck : false,

_nMorningChunk:0,
_nDayChunk:24,
_nPrimeTimeChunk:36,
_nLateNightChunk:43,
_nLastStart : 0, // avoid overlaps
_nLastEnd : 0, // avoid overlaps

_aSchedule : new Array(),
_aWeekdays : new Array("SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"),
_aMonths : new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),
_aTimeSlots : new Array(), // 30 minute slots
_aLastEndChunk : new Array(), // keep track of last end chunk in a given day slot

_dev : 0,


init:function(){
this.setClicks();
this.createArrayTimeSlots();
this.getSchedule();
},

// generate 30 minute increment slots
createArrayTimeSlots:function() {
 var l_nSlot = 0;
 for (l_nHour = 0; l_nHour < 24; l_nHour++) {
 this._aTimeSlots[((l_nHour<10)?'0'+l_nHour:l_nHour) + "00"] = l_nSlot++;
 this._aTimeSlots[((l_nHour<10)?'0'+l_nHour:l_nHour) + "30"] = l_nSlot++;
 }
 //console.dir(this._aTimeSlots);
},

counter : 0,
addToArrayTimeSlots:function(p_sDaySlot, p_sTimeSlot, p_aValue) {
 if (!this._aSchedule[p_sDaySlot]) {
 this._aSchedule[p_sDaySlot] = new Array();
 }
 if (this._aSchedule[p_sDaySlot][p_sTimeSlot]) {
 return false;
 }
 if (this._nLastStart >= p_aValue['starts_at']
 || this._nLastEnd >= p_aValue['ends_at']) {
 alert(counter);
 return false;
 }

 this._aSchedule[p_sDaySlot][p_sTimeSlot] = new Array();
 this._aSchedule[p_sDaySlot][p_sTimeSlot] = p_aValue;
 this._nLastStart = p_aValue['starts_at'];
 this._nLastEnd = p_aValue['ends_at'];
 return true;
},

getSchedule:function() {
 $.get("/feeds/schedule/7/"+ getGMTOffset() +"/",  {}, function(xml) {
 l_aCopyFromPreviousDay = new Array();
 l_nPreviousEndsAt = 0;
 l_nPreviousStartsAt = 0;
 $('show', xml).each(function(i) {
 l_aStartsAt = new Array();
 l_nStartsAt = $(this).find('starts_at').text();
 // fix a bug where shows could overlap
 l_sUpdateString = "";
 // this show start time overlaps with previous show end time so adjust it
 l_aStartsAt = _xSchedule.unixtimetoday(l_nStartsAt);
 l_aEndsAt = new Array();
 l_nEndsAt = $(this).find('ends_at').text();
 l_aEndsAt = _xSchedule.unixtimetoday(l_nEndsAt);

 l_sDaySlot = '<b>' + l_aStartsAt['weekday'] + '</b><br />' + l_aStartsAt['month'] + ' ' + l_aStartsAt['day'] + ' ' + l_aStartsAt['year'];

 if (_xSchedule._bCopyDayOverCheck) {
 //console.log('check: '+l_aCopyFromPreviousDay.length)
 //console.dir(l_aCopyFromPreviousDay);
 l_sTimeSlot = _xSchedule._aTimeSlots['0000'];
 l_aCopyFromPreviousDay['schedule']['slots'] = (((parseInt(l_aCopyFromPreviousDay['ends_at']['24hour']) * 60 + parseInt(l_aCopyFromPreviousDay['ends_at']['minutes']))/* - 0*/) / 30);
 _xSchedule.addToArrayTimeSlots(l_sDaySlot, l_sTimeSlot, l_aCopyFromPreviousDay['schedule']);
 _xSchedule._bCopyDayOverCheck = false;
 }
 

 l_aSchedule = new Array();
 l_aSchedule['slots'] = 1; // default 30 minutes
 if (l_aStartsAt['day'] == l_aEndsAt['day']) {
 l_aSchedule['slots'] = (((l_aEndsAt['24hour'] * 60 + l_aEndsAt['minutes']) - (l_aStartsAt['24hour'] * 60 + l_aStartsAt['minutes'])) / 30);
 } else {
 l_aSchedule['slots'] = ((24 * 60 - (l_aStartsAt['24hour'] * 60 + l_aStartsAt['minutes'])) / 30);
 }
 l_aSchedule['title'] = $(this).find('title_name').text();
 l_aSchedule['description'] = $(this).find('title_synopsis').text();
 l_aSchedule['sport_name'] = $(this).find('sport_name').text();
 l_aSchedule['sport_url'] = $(this).find('sport_url').text();
 l_aSchedule['starts_at_stamp'] = $(this).find('starts_at_stamp').text();
 l_aSchedule['ends_at_stamp'] = $(this).find('ends_at_stamp').text();
 l_aSchedule['starts_chunk'] = $(this).find('starts_chunk').text();
 l_aSchedule['ends_chunk'] = $(this).find('ends_chunk').text();
 l_aSchedule['id'] = $(this).find('id').text();
 l_aSchedule['starts_at_ustamp'] = l_nStartsAt;
 l_aSchedule['ends_at_ustamp'] = l_nEndsAt;
 l_aSchedule['uStartStampUpdate'] = l_sUpdateString;
 l_aSchedule['unix'] = l_aStartsAt['unix'];
 l_aSchedule['day'] = l_aStartsAt['day'];
 
 var l_nEndsChunk =  l_aSchedule['ends_chunk'];
 
//((l_nHour<10)?'0'+l_nHour:l_nHour) + "00"
// console.log("" + ((l_aStartsAt['24hour']<10)?'0'+l_aStartsAt['24hour']:l_aStartsAt['24hour']) + ((l_aStartsAt['minutes'])?l_aStartsAt['minutes']:'00'));
 
 l_sTimeSlot = _xSchedule._aTimeSlots["" + 
((l_aStartsAt['24hour']<10)?'0'+l_aStartsAt['24hour']:l_aStartsAt['24hour']) +
((l_aStartsAt['minutes'])?l_aStartsAt['minutes']:'00')
 ];
 _xSchedule.addToArrayTimeSlots(l_sDaySlot, l_sTimeSlot, l_aSchedule);

 // in case show continues through the next day
 if (l_aStartsAt['day'] != l_aEndsAt['day'] && parseInt(l_nEndsChunk)) {
 l_aCopyFromPreviousDay['schedule'] = new Array();
 l_aCopyFromPreviousDay['schedule'] = $.extend(true, {}, l_aSchedule); // goofy clone
 l_aCopyFromPreviousDay['starts_at'] = new Array();
 l_aCopyFromPreviousDay['starts_at'] = l_aStartsAt;
 l_aCopyFromPreviousDay['ends_at'] = new Array();
 l_aCopyFromPreviousDay['ends_at'] = l_aEndsAt;
 //console.log('set:')
 //console.dir(l_aCopyFromPreviousDay);
 _xSchedule._bCopyDayOverCheck = true;
 }
 
 l_aSchedule = new Array(); // reset
 l_nPreviousEndsAt = l_nEndsAt;
 l_nPreviousStartsAt = l_nStartsAt;
 });
 _xSchedule.printSchedule();
 });
},

printSchedule:function() {
 var l_sSchedule = '';
//   l_sSchedule = '<div class="day"><b>MONDAY</b> <br />OCT 5 2009</div><div class="show_holder_outer"><div class="show_holder_inner"><table cellpadding="0" cellspacing="0" class="dayrow"><tr><td class="show">Whacked out Sports</td><td class="show">Whacked out Sports</td><td class="show">Whacked out Sports</td><td class="show">Whacked out Sports</td><td class="show">Whacked out Sports</td></tr></table></div></div><div class="gap3"></div>';

 for (var l_sDaySlot in this._aSchedule) {
 if(l_sDaySlot=='indexOf') continue; // have to because of introduced function
 l_sSchedule += '<div class="day">' + l_sDaySlot + '</div>';
l_sSchedule += '<div class="show_holder_outer"><div class="show_holder_inner">';
l_sSchedule += '<table cellpadding="0" cellspacing="0" class="dayrow"><tr>';
var l_nSlotCount = 0;
for (var l_sTimeSlot in this._aSchedule[l_sDaySlot]) {
 if(l_sTimeSlot=='indexOf') continue; // have to because of introduced function
var l_nStartsChunk = parseInt(this._aSchedule[l_sDaySlot][l_sTimeSlot]['starts_chunk'])
var l_nEndsChunk = parseInt(this._aSchedule[l_sDaySlot][l_sTimeSlot]['ends_chunk'])
var l_nSlots = Math.round(parseInt(this._aSchedule[l_sDaySlot][l_sTimeSlot]['slots']));
if(l_nStartsChunk>l_nEndsChunk && l_nEndsChunk && !l_nSlotCount){
l_nStartsChunk = 0
}else{
if(l_nSlotCount > l_nEndsChunk && l_nStartsChunk < l_nEndsChunk){
continue;
}
if(l_nSlotCount > l_nStartsChunk){
l_nSlots = parseInt(l_nEndsChunk) - parseInt(l_nSlotCount);
}

while(l_nSlotCount < l_nStartsChunk && l_nSlotCount<48){
if (this._dev) {
l_sSchedule += '<td class="show colspan1 dummy">' + l_nSlotCount + ': No scheduled programming</td>';
} else {
l_sSchedule += '<td class="show colspan1 dummy">No scheduled programming</td>';
}
l_nSlotCount++
}
}
if (l_nSlots < 1) {
continue;
}
l_sSchedule += '<td class="show colspan' + l_nSlots + '">';
l_sSchedule += this._aSchedule[l_sDaySlot][l_sTimeSlot]['title'];

if (this._dev) {
l_sSchedule += '<br>i:' + this._aSchedule[l_sDaySlot][l_sTimeSlot]['id'];
l_sSchedule += '<br>slot:' + l_sTimeSlot;
l_sSchedule += '<br>s:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['starts_at_stamp'];
l_sSchedule += '<br>e:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['ends_at_stamp'];
l_sSchedule += '<br>sc:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['starts_chunk'];
l_sSchedule += '<br>ec:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['ends_chunk'];
l_sSchedule += '<br>su:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['starts_at_ustamp'];
l_sSchedule += '<br>eu:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['ends_at_ustamp'];
l_sSchedule += '<br>unix:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['unix'];
l_sSchedule += '<br>day:'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['day'];

l_sSchedule += this._aSchedule[l_sDaySlot][l_sTimeSlot]['uStartStampUpdate'];
} else {
//              l_sSchedule += '<br>'+this._aSchedule[l_sDaySlot][l_sTimeSlot]['description'].substring(0, 20);
}

l_sSchedule += '</td>';
l_nSlotCount+=parseInt(l_nSlots);
}
while(l_nSlotCount< 48){
if (this._dev) {
l_sSchedule += '<td class="show colspan1 dummy">' + l_nSlotCount + ': No scheduled programming</td>';
} else {
l_sSchedule += '<td class="show colspan1 dummy">No scheduled programming</td>';
}
l_nSlotCount++
}
l_sSchedule += '</tr></table>';
l_sSchedule += '</div></div>';
 l_sSchedule += '<div class="gap3"></div>';
 }

 $("#showarea").html(l_sSchedule);


 this.setRefs();
 this.jumpToCurrent();
},

unixtimetoday:function(p_nUnixTimestamp) {
 var theDate = new Date(parseInt(p_nUnixTimestamp) * 1000);
     var l_nCustomOffset = (g_nServerTimezoneOffset - (getGMTOffset()))
// l_nCustomOffset = 0;
 theDate = new Date( (parseInt(p_nUnixTimestamp) +( l_nCustomOffset*60*60) ) * 1000);
 var l_aDate = new Array();
 l_aDate['weekday'] = this._aWeekdays[theDate.getDay()];
 l_aDate['year'] = theDate.getFullYear();
 l_aDate['month'] = this._aMonths[theDate.getMonth()];
 l_aDate['day'] = theDate.getDate();
 l_aDate['24hour'] = theDate.getHours();
 l_aDate['minutes'] = theDate.getMinutes();
 l_aDate['meridiem'] = (l_aDate['24hour'] < 12 ? "AM" : "PM");
 l_aDate['12hour'] = l_aDate['24hour'] % 12;
 l_aDate['unix'] = theDate.getTime()/1000;
 return l_aDate;
},

setRefs:function(){

this._xTimeInner = $('#time_holder_inner');
this._aDayInner = $('#showarea').find('.show_holder_inner');

},

jumpToCurrent:function(){

var l_xDate = new Date();
var l_nHours = parseInt(l_xDate.getHours());
var l_nMinutes = parseInt(l_xDate.getMinutes());

l_nHours *= 2;

if(l_nMinutes > 30) l_nHours ++;

_xSchedule._nCurrentTimeChunk = l_nHours;
_xSchedule.scrollAll();

},

setClicks:function(){

$('#chunk_morning').click(function(){
_xSchedule._nCurrentTimeChunk = _xSchedule._nMorningChunk;
_xSchedule.scrollAll();
});
$('#chunk_day').click(function(){
_xSchedule._nCurrentTimeChunk = _xSchedule._nDayChunk;
_xSchedule.scrollAll();
});
$('#chunk_primetime').click(function(){
_xSchedule._nCurrentTimeChunk = _xSchedule._nPrimeTimeChunk;
_xSchedule.scrollAll();
});
$('#chunk_latenight').click(function(){
_xSchedule._nCurrentTimeChunk = _xSchedule._nLateNightChunk;
_xSchedule.scrollAll();
});

$('#timerow_right').click(function(){
if(_xSchedule._nCurrentTimeChunk<43){
_xSchedule._nCurrentTimeChunk++
_xSchedule.scrollAll();
}
});


$('#timerow_left').click(function(){

if(_xSchedule._nCurrentTimeChunk>0){
_xSchedule._nCurrentTimeChunk--
_xSchedule.scrollAll();
}

});

},

scrollAll:function(){


if(_xSchedule._nCurrentTimeChunk>=43) _xSchedule._nCurrentTimeChunk=43

_xSchedule._xTimeInner.animate({'left':(-_xSchedule._nCurrentTimeChunk*_xSchedule._nTimeWidth)},0);
_xSchedule._aDayInner.each(function(){
$(this).animate({'left':(-_xSchedule._nCurrentTimeChunk*_xSchedule._nTimeWidth)},0);
})


}



}








$(document).ready(function(){

if( document._bIsGames){
_xGames.init();
}


});


_xGames={// JavaScript Document
init:function(){
this.setDropdown();
},
setDropdown:function(){
$("#games_dropdown_sort").find("a").live('click',function(){
var l_sSort = $(this).attr('rel');

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

BaseAjax._xArgs.data += '&p_nPage=1';
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#games_landing_rows'
BaseAjax._xArgs.loaderDiv = '#games_landing_rows_inner'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

});
},
paginateTo:function(p_nPage){
var l_sSort = $('#games_dropdown_sort').attr('rel')


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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sSort='+l_sSort;

BaseAjax._xArgs.returnDiv = '#games_landing_rows'
BaseAjax._xArgs.loaderDiv = '#games_landing_rows_inner'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

$.scrollTo('#games_landing_rows', 300);

}
}

$(document).ready(function(){
if (!document._bIsMobilePage) {
_xUser.init();
}
});


_xUser = {

init:function(){
$('body').append('<div id="communityupdates" class="png communityupdates"></div>');
this.setForms();
this.isLoggedIn();
this.setClicks()
},

setClicks:function(){
$('#communityupdates').live('click',function() {_xTruebox.makeSignupRegister() });
$('#header_login').live('click',function() {_xTruebox.makeSignupRegister() });
$('#header_register').live('click',function() {_xTruebox.makeSignupRegister() });

$('#account').live('click', function(){ setTimeout(function(){window.location.replace("/user/?uid="+_xUser.getPluckUserInfoFromCookie("", "id"))},100) });
},

getCookie: function (name){
//temporary cookie names. 
//TODO:Rename/Revisit cookie names

name = 'versus_user'; namePl = 'at'; //for now

//get cookies using jquery
var cookies_hd = $.cookies.get(namePl);
var cookies_versus = $.cookies.get('versus_user');

//initialize variables
var cms_cookie_found = false; // set boolean t/f default f
var pl_cookie_found = false;

// if the extracted name matches passed check_name
if (cookies_hd != null ){
pl_cookie_found = true;
return cookies_hd;
}else if (cookies_versus != null ){
cms_cookie_found = true;
return cookies_versus;
}

//TODO if needed return array of cookie values
if (cms_cookie_found == true && pl_cookie_found == true)
return true;

if (!pl_cookie_found || !cms_cookie_found )
{
return null;
}
},
    

gotoAccountPage:function(){
window.location="/user/?uid="+_xUser.getPluckUserIsnfoFromCookie("at");
},


//parses pluck cookie and returns userkey for MyAccount link to redirect to user profile page
//TODO:Vishal merge cookie handling functions into one.
getPluckUserInfoFromCookie: function (l_sName, l_sType){
// first we'll split this cookie up into name/value pairs
// note: document.cookie only returns name=value, not the other components
l_sName = "at";
var l_sCookie = $.cookies.get(l_sName);

if (l_sCookie !=null){
     var l_sPluckCookieSplit = l_sCookie.split("&");

 switch(l_sType){
  case 'id':
//split cookie id and get pluck cookie id
//var l_sPluckCookieSplit = l_sCookie.split("|");
//var l_nPluckCookieId = l_sPluckCookieSplit[0];
 var l_sPluckIdSplit = l_sPluckCookieSplit[0].split("=");
 var l_nPluckCookieId = l_sPluckIdSplit[1]; 
  break;
  case 'name':
//split cookie and get pluck cookie name 
//var l_sPluckCookieSplit = l_sCookie.split("|");
//var l_nPluckCookieId = l_sPluckCookieSplit[1];
     var l_sPluckNameSplit = l_sPluckCookieSplit[1].split("=");
 var l_nPluckCookieId = l_sPluckNameSplit[1]; 
  break;
 }
return l_nPluckCookieId;
} else{
   return null;
}

},

deleteCookie: function( name, path, domain ) {
//for now
name = 'versus_user';
namePluck = 'hd';
path = '/';
domain = '.versus.com';
domainPluck = '.versus.com';

if ( this.getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";

if ( this.getCookie( namePluck ) ) document.cookie = namePluck + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domainPluck : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
},

isLoggedIn:function(){

//checks cookies
loggedin = false;

//if cookie with name versus_user exist
if (this.getCookie('versus_user') && this.getCookie('hd'))
{
loggedin = true;
}
//then user is logged in

if(loggedin)
this.loggedIn();
else
this.loggedOff();
},

setForms:function(){


//Add listeners
$('#login_button').live('click',function(){ $('#login_form').submit() });
$('#register_button').live('click',function(){ $('#register_form').submit() });
$('#sign_out').live('click',function(){ _xUser.logOff(); });

// On Login Submit
$('#login_form').livequery('submit',function(){
// Perform actions when a user signs in.


// Validate form in JS first
p_aErrors = new Array();
p_aErrors = _xUser.validateLogin();

if(p_aErrors.length > 0){
$('#register_errors').html('');
$('#register_errors').hide();
$('#login_errors').html('');
$('#login_errors').show();
$('#login_errors').html(_xUser.printErrors(p_aErrors));
return false;
}

//AJAX PHP validate
$('#login_errors').html('');
$('#register_errors').html('');
BaseAjax.login($("#login_form input[name=username]").val(),$("#login_form input[name=password]").val(),$("#login_form input[name=redirectTo]").val());

//If return was OK (user Logged IN)
//close form and adjust header style
//_xTruebox.closePopup();
//_xUser.loggedIn();

// return false to prevent page refresh
return false;
});

// On Register Submit
$('#register_form').livequery('submit',function(){
// Perform actions when a user registers.
 
p_aErrors = new Array();
p_aErrors = _xUser.validateRegister();

if(p_aErrors.length > 0){
$('#login_errors').html('');
$('#login_errors').hide();
$('#register_errors').html('');
$('#register_errors').show();
$('#register_errors').html(_xUser.printErrors(p_aErrors));
return false;
}

//AJAX PHP validate

first = $("#register_form input[name=firstname]").val();
last = $("#register_form input[name=lastname]").val();
email = $("#register_form input[name=email]").val();
cemail = $("#register_form input[name=confirmemail]").val();
user = $("#register_form input[name=username]").val();
pass = $("#register_form input[name=password]").val();
cpass = $("#register_form input[name=confirmpassword]").val();
captcha_challenge = $("#register_form #recaptcha_challenge_field").val();
captcha_response = $("#register_form #recaptcha_response_field").val();
 
checks = '';

$('#register_form').find('.check_selected').each(function() {
checks += '&check[]='+ escape($(this).attr('rel'));
    });
    


$('#login_errors').html('');
$('#register_errors').html('');
BaseAjax.register(first, last, email, cemail, user, pass, cpass, checks ,captcha_challenge, captcha_response);
//If return was OK (user Logged IN)
//close form and adjust header style

//if we need to log in user after successfull registration
//_xTruebox.closePopup();
//_xUser.logIn();

// return false to prevent page refresh
return false;
});

},

logIn:function(){
//try to log in with pluk
//....


//adjust links
_xUser.loggedIn();
},


loggedIn:function(){
$('#signed_out').hide();
$('#signed_in').show();
$('#communityupdates').hide();

},

logOff:function(){
//TODO
//LOG OFF ACTION IN HERE
//...
BaseAjax.logout();


//just in case
this.deleteCookie();

//adjust links
_xUser.loggedOff();
},

loggedOff:function(){
$('#signed_in').hide();
$('#signed_out').show();
$('#communityupdates').show();
},

validateLogin: function(){
l_asErrors = new Array();

if(/[a-zA-Z0-9]{2,}/.test( $("#login_form input[name=username]").val() ) == false || 
(/[a-zA-Z0-9]{6,16}/.test( $("#login_form input[name=password]").val() ) == false))
l_asErrors.push("Sorry, your user ID or password was not recognized.<br />Please enter a valid user ID and password.");
return l_asErrors;
},

validateRegister: function(){
l_asErrors = new Array();
if(/[a-zA-Z]{2,}/.test( $("#register_form input[name=firstname]").val() ) == false ||
(/[a-zA-Z]{2,}/.test( $("#register_form input[name=lastname]").val() ) == false ) )
l_asErrors.push("Sorry, your Name or Last Name was too short. Please enter at least 2 characters.");


if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test($("#register_form input[name=email]").val()) == false)
l_asErrors.push("Email Address is in an invalid format.");
else
if ( $("#register_form input[name=confirmemail]").val() != $("#register_form input[name=email]").val() )
l_asErrors.push("Email Address and Confirmation must match.");

if(/[a-zA-Z]{1}[-a-zA-Z0-9]{3}[-a-zA-Z0-9]*/.test($("#register_form input[name=username]").val()) == false)
l_asErrors.push("Username must be at least 4 alphanumeric characters (a-z, 0-9, or -) and begin with a letter.");


if($("#register_form input[name=password]").val() == '' || $("#register_form input[name=confirmpassword]").val() == '') 
l_asErrors.push("Password must be between 6 and 16 alphanumeric characters.");
else{
if(/[a-zA-Z0-9]{6,16}/.test($("#register_form input[name=password]").val()) == false)
l_asErrors.push("Password must be between 6 and 16 alphanumeric characters.");
if($("#register_form input[name=password]").val() != $("#register_form input[name=confirmpassword]").val())
l_asErrors.push("Password and Confirmation must match.");
}

return l_asErrors;
},


validateResetPass: function(){
l_asErrors = new Array();
if($("#reset_pass input[name=password]").val() == '' || $("#reset_pass input[name=confirmpassword]").val() == '') 
l_asErrors.push("Password must be between 6 and 16 alphanumeric characters.");
else{
if(/[a-zA-Z0-9]{6,16}/.test($("#reset_passinput[name=password]").val()) == false)
l_asErrors.push("Password must be between 6 and 16 alphanumeric characters.");
if($("#reset_pass input[name=password]").val() != $("#reset_pass input[name=confirmpassword]").val())
l_asErrors.push("Password and Confirmation must match.");
}

return l_asErrors;
},


printErrors: function(p_asErrors){

r_sError = "<div class=\"error\">";
r_sError += "<span class=\"clear\"><!--comment--></span>";
for(var i=0; i < p_asErrors.length; i++){
r_sError += "<span class=\"error list\"><span class=\"validation_error\">"+p_asErrors[i]+"</span></span>";
r_sError += "<div class=\"clear\"><!--comment--></span>";
}
r_sError += "</div>";

return r_sError;
},

submitUpdatePassForm: function(){
p_aErrors = new Array();
p_aErrors = this.validateResetPass();
if(p_aErrors.length > 0){
$('#return_div').html(_xUser.printErrors(p_aErrors));
return false;
}
BaseAjax.updatePass($("#reset_pass input[name=password]").val(),$("#reset_pass input[name=token]").val());

},

_bSubmitSweepstakesFormSent :false,

submitSweepstakesForm:function(){
if(_xUser._bSubmitSweepstakesFormSent) return false;

var l_sFirstName =  $("#ss_firstname").val();
var l_sLastName =  $("#ss_lastname").val();
var l_sAddress1 =  $("#ss_add1").val();
var l_sAddress2 =  $("#ss_add2").val();
var l_sCity =  $("#ss_city").val();
var l_sState =  $("#ss_state_dropdown").data('choice')
var l_nZip =  parseInt($("#ss_zip").val());
var l_nPhone =  parseInt($("#ss_phone").val());
var l_sEmail =  $("#ss_email").val();
var l_sMonth =  $("#ss_month_dropdown").data('choice')
var l_sDay =  $("#ss_day_dropdown").data('choice')
var l_sYear =  $("#ss_year_dropdown").data('choice')

 
var l_asErrors = new Array();

if(/[a-zA-Z]{2,}/.test(l_sFirstName ) == false ||
(/[a-zA-Z]{2,}/.test(l_sLastName) == false ) )
l_asErrors.push("Sorry, your Name or Last Name was too short. Please enter at least 2 characters.");
if(!l_sAddress1)
l_asErrors.push("Please enter a Mailing Address.");

if(!l_sCity)
l_asErrors.push("Please enter a City.");

if(!l_sState)
l_asErrors.push("Please enter a State.");

if(!l_nZip)
l_asErrors.push("Please enter a Zip Code.");

if(!l_nPhone)
l_asErrors.push("Please enter a Phone Number.");

if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test(l_sEmail) == false)
l_asErrors.push("Email Address is in an invalid format.");

if(!l_sMonth || !l_sDay || !l_sYear)
l_asErrors.push("Please enter a valid Date of Birth");

if(l_asErrors.length > 0){
alert(l_asErrors.join("\n"));
return false;
}

_xUser._bSubmitSweepstakesFormSent = true;

BaseAjax._xArgs.data = 'a=SubmitSweepstakes';
BaseAjax._xArgs.data += '&l_nSweepstakesId='+document._nSweepstakesId;
BaseAjax._xArgs.data += '&l_sFirstName='+l_sFirstName;
BaseAjax._xArgs.data += '&l_sLastName='+l_sLastName;
BaseAjax._xArgs.data += '&l_sAddress1='+l_sAddress1;
BaseAjax._xArgs.data += '&l_sAddress2='+l_sAddress2;
BaseAjax._xArgs.data += '&l_sCity='+l_sCity;
BaseAjax._xArgs.data += '&l_sState='+l_sState;
BaseAjax._xArgs.data += '&l_nZip='+l_nZip;
BaseAjax._xArgs.data += '&l_nPhone='+l_nPhone;
BaseAjax._xArgs.data += '&l_sEmail='+l_sEmail;
BaseAjax._xArgs.data += '&l_sMonth='+l_sMonth;
BaseAjax._xArgs.data += '&l_sDay='+l_sDay;
BaseAjax._xArgs.data += '&l_sYear='+l_sYear;

BaseAjax._xArgs.callBack = _xUser.submitSweepstakesForm_callback;

BaseAjax.makeAjaxCall(AJAX_URL);

},
submitSweepstakesForm_callback:function(){

_xUser._bSubmitSweepstakesFormSent = false;

$('#ss_info_text').empty().append('<a href="/" class="sweepstakes_thankyou" title="Return to the Homepage"></a>');

},


validateFeedbackForm:function(){
var l_asErrors = new Array();

if(/[a-zA-Z]{2,}/.test( $("#ss_firstname").val() ) == false ||
(/[a-zA-Z]{2,}/.test( $("#ss_lastname").val() ) == false ) )
l_asErrors.push("Sorry, your Name or Last Name was too short. Please enter at least 2 characters.");
if(!$("#ss_add1").val())
l_asErrors.push("Please enter a Mailing Address.");

if(!$("#ss_city").val())
l_asErrors.push("Please enter a City.");

if(!$("#ss_state_dropdown").data('choice'))
l_asErrors.push("Please enter a State.");

if(!$("#ss_zip").val())
l_asErrors.push("Please enter a Zip Code.");

if(!$("#ss_phone").val())
l_asErrors.push("Please enter a Phone Number.");

if(/^[_a-zaA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test($("#ss_email").val()) == false)
l_asErrors.push("Email Address is in an invalid format.");

if(!$("#ss_month_dropdown").data('choice') || !$("#ss_day_dropdown").data('choice') || !$("#ss_year_dropdown").data('choice'))
l_asErrors.push("Please enter a valid Date of Birth");

return l_asErrors;

},

checkLoginRefresh:function(){
if(document._nGroupId) location.reload(true);

}

}


BaseAjax.register = function(first, last, email, cemail, user, pass, cpass, checks,captcha_challenge, captcha_response){
BaseAjax._xArgs.data = 'a=createUser';
BaseAjax._xArgs.data += '&firstname='+escape(first);
BaseAjax._xArgs.data += '&lastname='+escape(last);
BaseAjax._xArgs.data += '&email='+escape(email);
BaseAjax._xArgs.data += '&cemail='+escape(cemail);
BaseAjax._xArgs.data += '&username='+escape(user);
BaseAjax._xArgs.data += '&password='+escape(pass);
BaseAjax._xArgs.data += '&cpassword='+escape(cpass);
BaseAjax._xArgs.data += '&captcha_challenge='+escape(captcha_challenge);
BaseAjax._xArgs.data += '&captcha_response='+escape(captcha_response);
BaseAjax._xArgs.data += checks;

BaseAjax._xArgs.returnDiv = '#return_div';
BaseAjax._xArgs.callBack = BaseAjax.register_callback;
BaseAjax.makeAjaxCall('/_site/include/lib/user/action.php');
}

BaseAjax.login = function(u,p,r){
BaseAjax._xArgs.data = 'a=loginUser';
BaseAjax._xArgs.data += '&username='+escape(u);
BaseAjax._xArgs.data += '&password='+escape(p);
BaseAjax._xArgs.data += '&redirectTo='+escape(r);
BaseAjax._xArgs.returnDiv = '#return_div';

BaseAjax._xArgs.callBack = BaseAjax.login_callback;
BaseAjax.makeAjaxCall('/_site/include/lib/user/action.php');
}

BaseAjax.logout = function(){
BaseAjax._xArgs.data = 'a=logoutUser';
BaseAjax.makeAjaxCall('/_site/include/lib/user/action.php');
}

BaseAjax.updatePass = function(p,t){
BaseAjax._xArgs.data = 'a=updatePass';
BaseAjax._xArgs.data += '&password='+escape(p);
BaseAjax._xArgs.data += '&token='+escape(t);
BaseAjax._xArgs.returnDiv = '#return_div';

BaseAjax._xArgs.callBack = BaseAjax.updatepass_callback;
BaseAjax.makeAjaxCall('/_site/templates/forgotpass.php');
}


BaseAjax.login_callback = function(){
$('#return_div').html(BaseAjax.returnVar);
if(_xTruebox._sGroupUploadKey){
 var requestBatch = new RequestBatch();
 requestBatch.AddToRequest(new CommunityGroupKey(_xTruebox._sGroupUploadKey));
 requestBatch.BeginRequest(g_xServerUrl, contentCallBack);
 _xTruebox._sGroupUploadKey = null;
}
if(_xTruebox._sUserGroupBlog){
 //redirect to user blog page
 window.location.href = "/user/?plckPersonaPage=PersonaBlog&plckUserId="+_xUser.getPluckUserInfoFromCookie("", "id")+"&uid="+_xUser.getPluckUserInfoFromCookie("", "id")+"";
 _xTruebox._sUserGroupBlog = null;
}
if(_xTruebox._sUserFiresUp){
recommend(_xTruebox._sRecommendationKey, _xTruebox._sRecommendationType,_xTruebox._sRecommendationLoc);
_xTruebox._sUserFiresUp = null;
_xTruebox._sRecommendationKey = null;
_xTruebox._sRecommendationType = null;
_xTruebox._sRecommendationLoc = null;
}
}

BaseAjax.register_callback = function(){
$('#return_div').html(BaseAjax.returnVar);
if(_xTruebox._sGroupUploadKey){
 var requestBatch = new RequestBatch();
 requestBatch.AddToRequest(new CommunityGroupKey(_xTruebox._sGroupUploadKey));
 requestBatch.BeginRequest(g_xServerUrl, contentCallBack);
 _xTruebox._sGroupUploadKey = null;
}
if(_xTruebox._sUserGroupBlog){
//redirect to user blog page
 window.location.href = "/user/?uid="+_xUser.getPluckUserInfoFromCookie("", "id")+"&plckUserId="+_xUser.getPluckUserInfoFromCookie("", "id")+"";
_xTruebox._sUserGroupBlog = null;
}
if(_xTruebox._sUserFiresUp){
recommend(_xTruebox._sRecommendationKey, _xTruebox._sRecommendationType,_xTruebox._sRecommendationLoc);
_xTruebox._sUserFiresUp = null;
_xTruebox._sRecommendationKey = null;
_xTruebox._sRecommendationType = null;
_xTruebox._sRecommendationLoc = null;
}
}

BaseAjax.updatepass_callback = function(){
$('#return_div').html(BaseAjax.returnVar);
}



$(document).ready(function(){
_xPoll.init();
});


_xPoll={

_sPollCookieName : 'polls',
_sQuizCookieName : 'quizzes',

init:function(){
this.setClicks();
},

setClicks:function(){
$('#show_detail_poll').live('click',function(){
_xPoll.makeShowDetailPoll();
});
$('#home_poll').live('click',function(){
_xPoll.makeHomePoll();
});

},




submitQuiz:function(p_nId,p_xElement){

var l_nTargetId = $(p_xElement).parents('.quiz_module').attr('id')
var l_nTargetInnerId = $(p_xElement).parents('.quiz_inner').attr('id');
var l_nTargetRealInnerId = $(p_xElement).parents('.quiz_real_inner').attr('id');


var l_nColNum = $(p_xElement).parents('.quiz_module').attr('rel')

BaseAjax._xArgs.data = 'a=SubmitQuizAjaxCall';

l_bCheckQuizzed = this.checkIfQuizzed(p_nId);
if(!l_bCheckQuizzed){
this.setQuizzed(p_nId)
BaseAjax._xArgs.data += '&p_bCountQuiz=1';
}else{
BaseAjax._xArgs.data += '&p_bCountQuiz=0';
}
BaseAjax._xArgs.data += '&p_nId='+p_nId;

var l_aResults = $('#'+l_nTargetId).find('.quiz_dropdown');

var l_aChoiceString = '';

for( var i=0; i<$(l_aResults).length;i++){

var l_nAnswer = $(l_aResults).eq(i).data('choice');
var l_nQuestion =  $(l_aResults).eq(i).attr('rev');

l_aChoiceString += ((i)?'|':'')+l_nQuestion+'!'+l_nAnswer

}

BaseAjax._xArgs.data += '&p_sResponses='+l_aChoiceString;
BaseAjax._xArgs.data += '&p_nColNum='+l_nColNum;

BaseAjax._xArgs.loaderDiv = '#'+l_nTargetRealInnerId;
if(l_nColNum == 2)
BaseAjax._xArgs.loaderType = 'white';
else
BaseAjax._xArgs.loaderType = 'dark';
BaseAjax._xArgs.returnDiv = '#'+l_nTargetInnerId;
BaseAjax._xArgs.requestType = "POST"; 
BaseAjax.makeAjaxCall(AJAX_URL);


},


makeShowDetailPoll:function(){
var l_nId = $('#show_detail_poll').attr('rel')
if(l_nId ){
_xTruebox.makePoll(l_nId);
}

},

makeHomePoll:function(){

var l_nId = $('#home_poll').attr('rel')

if(l_nId &&!_xHome._bChanging ){
_xHome.stopAutoPlay()
_xHome._bPollOpen = true;
_xTruebox.makePoll(l_nId);
}

},

voteyes:function(p_nId,p_nQuestionId,p_xElement){
_xPoll.vote(p_nId,p_nQuestionId,'p_bYes',p_xElement)
},
voteno:function(p_nId,p_nQuestionId,p_xElement){
_xPoll.vote(p_nId,p_nQuestionId,'p_bNo',p_xElement)
},

vote:function(p_nId,p_nQuestionId, p_sVote,p_xElement){


BaseAjax._xArgs.data = 'a=VotePollAjaxCall';
l_bCheckVoted = this.checkIfVoted(p_nId);

if(!l_bCheckVoted){
this.setVoted(p_nId)
BaseAjax._xArgs.data += '&p_bCountVote=1';
}else{
BaseAjax._xArgs.data += '&p_bCountVote=0';
}

BaseAjax._xArgs.data += '&p_nQuestionId='+p_nQuestionId;
BaseAjax._xArgs.data += '&p_nId='+p_nId;
BaseAjax._xArgs.data += '&'+p_sVote+'=1';

//check if its in mainfeature
if ( _xHome._bPollOpen ){
BaseAjax._xArgs.data += '&p_nHomeFeature='+_xHome._nCurrentFeature;
BaseAjax._xArgs.returnDiv = '#returndiv';
}else{
BaseAjax._xArgs.data += '&p_nHomeFeature=-1';
var l_nTargetId = $(p_xElement).parents('.full_poll_module').attr('id')
BaseAjax._xArgs.returnDiv = '#'+l_nTargetId;

}

// for testing:
BaseAjax._xArgs.data += '&l_nTargetId='+l_nTargetId;


BaseAjax._xArgs.requestType = "POST"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},


checkIfVoted:function(p_nId){
var l_sVote = $.cookie( _xPoll._sPollCookieName );
var l_sVote ='1x2';

if(l_sVote){
var l_aVoteArray = l_sVote.split('x') ;
if( l_aVoteArray.indexOf(''+p_nId) >= 0 ){
return true;
}
}
return false;
},


setVoted:function(p_nId){

var l_sVote = $.cookie( _xPoll._sPollCookieName );
if(l_sVote)
l_sVote += 'x'+p_nId;
else
l_sVote = p_nId

$.cookie( _xPoll._sPollCookieName, l_sVote, {expires:365,path:'/'});


},

checkIfQuizzed:function(p_nId){
var l_sQuiz = $.cookie( _xPoll._sQuizCookieName );
if(l_sQuiz){
var l_aQuizArray = l_sQuiz.split('x') ;
if( l_aQuizArray.indexOf(''+p_nId) >= 0 ){
return true;
}
}
return false;
},


setQuizzed:function(p_nId){

var l_sQuiz = $.cookie( 'polls' );
if(l_sQuiz)
l_sQuiz += 'x'+p_nId;
else
l_sQuiz = p_nId

$.cookie( _xPoll._sQuizCookieName, l_sQuiz, {expires:365,path:'/'});


}



}


$(document).ready(function(){

if(document._sFeatureAreaType=='sport_wide' 
|| document._sFeatureAreaType=='sport_narrow' 
|| document._sFeatureAreaType=='show' 
|| document._sFeatureAreaType=='post' 
|| document._sFeatureAreaType=='wide_img' 
|| document._sFeatureAreaType=='gear')
{
if(_xFeature._aFeatureArray && _xFeature._aFeatureArray.length > 1){
_xFeature.init();
}
}

$('#detail_wide_next_button, #detail_wide_prev_button, #landing_pagi_count').live('click', function(){
_xFeature._bIsAutoPlay = false;
clearInterval(_xFeature._xAutoPlayTimer);
});

});



_xFeature={

_nCurrentFeature:1,

_bIsAutoPlay:false,
_nAutoPlayTimeout:10000,
_xAutoPlayTimer:null,

init:function(){
//this._bIsAutoPlay=true, //only set to true if _xFeature is initialized. prevents unwanted feature rotation in case where only one feature, user plays & pauses feature video
//this.startAutoPlay();
},


startAutoPlay:function(){
if(_xFeature._bIsAutoPlay){
clearInterval(_xFeature._xAutoPlayTimer);
_xFeature._xAutoPlayTimer = setInterval(function(){
_xFeature._nCurrentFeature++;
if(_xFeature._nCurrentFeature > _xFeature._aFeatureArray.length){ _xFeature._nCurrentFeature = 1; }
_xFeature.paginateTo(_xFeature._nCurrentFeature);
   },_xFeature._nAutoPlayTimeout)
}
},

stopAutoPlay:function(){
clearInterval(_xFeature._xAutoPlayTimer);
},


paginateTo:function(p_nPage){


BaseAjax._xArgs.data = 'a=FeatureAjaxCall';

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_nLength='+_xFeature._aFeatureArray.length;
BaseAjax._xArgs.data += '&p_nType='+document._sFeatureAreaType


for (var key in _xFeature._aFeatureArray[p_nPage-1]){
BaseAjax._xArgs.data += '&'+key+'='+_xFeature._aFeatureArray[p_nPage-1][key]
}

BaseAjax._xArgs.returnDiv = '#feature_area_holder';
BaseAjax._xArgs.requestType = "GET"; 

BaseAjax.makeAjaxCall(AJAX_URL);


}





}



// JavaScript Document 


$(document).ready(function(){
if(document._bHasShowAggrigate )
_xShowAggrigate.init();
});


_xShowAggrigate={

_sAlphabet : '',
_sSection : '',
_bFeatured:0,

init:function(){
this.setAlphabet();
$.historyInit(_xShowAggrigate.detectChangeAddress);
},

setAlphabet:function(){

$('#show_alphabet').find('a').live('click',function(){
_xShowAggrigate._sAlphabet =  $(this).attr('rel')
_xShowAggrigate.generalSort(1)
});


},
sortByAll:function(p_sSlug){
$.historyLoad('/all/');

},
sortBySection:function(p_sSlug){
$.historyLoad('/'+p_sSlug+'/');
//_xShowAggrigate._bFeatured = 0;
//_xShowAggrigate._sSection = p_sSlug
//_xShowAggrigate.generalSort(1)

},
sortByFeatured:function(){
$.historyLoad('/featured/');

},
paginateTo:function(p_nPage){

_xShowAggrigate.generalSort(p_nPage)
$.scrollTo('#show_landing_browser', 300);
},

generalSort:function(p_nPage){

BaseAjax._xArgs.data = 'a=ShowLandingAjaxCall';

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += '&p_sAlphabet='+_xShowAggrigate._sAlphabet;
BaseAjax._xArgs.data += '&p_sSection='+_xShowAggrigate._sSection;
BaseAjax._xArgs.data += '&p_bFeatured='+_xShowAggrigate._bFeatured;

BaseAjax._xArgs.returnDiv = '#show_landing_browser'
BaseAjax._xArgs.loaderDiv = '#show_landing_browser_inside'
BaseAjax._xArgs.loaderType = 'dark'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

return false;

},


detectChangeAddress:function(hash){
var l_aPathNames= hash.split('/'); 


if( l_aPathNames[1]){
//   /all/ /featured/ /hunting/ /fishing
var l_sTarget = l_aPathNames[1]

switch(l_sTarget){
case 'hunting':
case 'fishing':
_xShowAggrigate._bFeatured = 0;
_xShowAggrigate._sSection = l_sTarget
_xShowAggrigate.generalSort(1)
break;
case 'featured':
_xShowAggrigate._bFeatured = 1;
_xShowAggrigate._sSection = ''
_xShowAggrigate.generalSort(1)
break;
case 'all':
_xShowAggrigate._bFeatured = 0;
_xShowAggrigate._sSection = ''
_xShowAggrigate.generalSort(1)
break;
}

}

}

}


// necessary because ie6 & 7 lack native indexOf function for Array
// Note: In future. Please use the underscore method
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}


getGMTOffset = function(){
var theDate = new Date();
var l_nOffset = -(theDate.getTimezoneOffset() /60);
return (l_nOffset);
}

makeCustomImage = function(p_xTitleInfo){

p_xTitleInfo.t = p_xTitleInfo.t.replace(/&nbsp;/ig, " ");
    p_xTitleInfo.t = p_xTitleInfo.t.replace(/(<([^>]+)>)/ig," "); 

var l_sCondenced = Base64.encode(php_serialize(p_xTitleInfo))

l_sCondenced = l_sCondenced.replace('/','_')
l_sCondenced = l_sCondenced.replace('+','-')

var l_sHash = MD5(l_sCondenced);

var l_sDir1 = l_sHash.charAt(0);
var l_sDir2 = l_sHash.charAt(1);
var l_sDir3 = l_sHash.charAt(2);

var l_sImageUrl = g_sResourceUrl+'/dimage/'+l_sDir1+'/'+l_sDir2+'/'+l_sDir3+'/'+l_sHash+'/'+l_sCondenced+'.png?v=213';

return l_sImageUrl;
}

addSlashes = function(str) {
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\0/g,'\\0');
return str;
}





/**
*
*  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();
}



_xOmniture = {

init : function(){},

onLogin : function(p_sUsername){
var s=s_gi(s_account); 
s.prop19=p_sUsername; 
//s.eVar4='value'; 
s.events='event12'; 
s.linkTrackVars='prop19,events'; 
s.linkTrackEvents='event12'; 
s.tl(true,'o', 'event');
}

}
 

// JavaScript Document

$(document).ready(function(){
if( document._bHasModules ){
_xModules.init();
}
});

_xModules={

init:function(){
this.initFeturedGallery();
},


initFeturedGallery:function(){


$('.ft_playlists').find('.playlist_item').live('click',function(){
//detect if the playlist module is the first one for instream ads.
var l_bIsFirst = $(this).parents('.ft_playlists').hasClass('ft_playlists_first');

l_nVideoId = $(this).attr('rel');

//Flip scenes
$(this).parents('.ft_playlists').find('.ft_gal_wrp_1').hide();
$(this).parents('.ft_playlists').find('.ft_gal_wrp_2').show();
var l_nTargetDivId = $(this).parents('.ft_playlists').find('.vid_gal_ret').attr('id');
var shift_left;

if($(this).parents('.ft_playlists').find('.ft_gal_wrp_2').attr('rel') != l_nVideoId ){

$(this).parents('.ft_playlists').find('.ft_gal_wrp_2').attr('rel',l_nVideoId);

BaseAjax._xArgs.data = 'a=FeaturedVideGalleryAjaxCall';
BaseAjax._xArgs.data += '&p_nId='+l_nVideoId;
BaseAjax._xArgs.data += '&p_bshowAd='+l_bIsFirst;
BaseAjax._xArgs.returnDiv = '#'+l_nTargetDivId;
BaseAjax._xArgs.loaderDiv = '#'+l_nTargetDivId+' .video_inner';
BaseAjax._xArgs.loaderType = 'white'
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
}
return false;


});

},

getFeatGalleryVideo:function(p_sUniqueId,p_nVideoId, p_sVideoTitle, p_sVideoPub, p_sVideoDesc,p_bShowInstreamAd){

var l_bIsFirst = $('#video_inner_'+p_sUniqueId+'_div').parents('.ft_playlists').hasClass('ft_playlists_first');

//Change Video Info
$('.pl_video_blurb').html(p_sVideoDesc);
$('.pl_video_info').children('h4').children('a').html(p_sVideoTitle);
$('.pl_video_info').children('p').html(p_sVideoPub);
//$('#video_inner').attr('rel',p_nVideoId);

BaseAjax._xArgs.data = 'a=FeaturedVideGalleryAjaxCall';
BaseAjax._xArgs.data += '&id='+p_nVideoId;
BaseAjax._xArgs.data += '&p_bshowAd='+l_bIsFirst;
BaseAjax._xArgs.data += '&action=player';
BaseAjax._xArgs.returnDiv = '#video_inner_'+p_sUniqueId+'_div';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);
},


featuredGalleryCheck:function(){

total_width = $('#playlist_scroll').css('width');
total_width = parseInt( total_width.substring(0,total_width.length-2) );

shift_left = $('#playlist_scroll').css('left');
shift_left = parseInt( shift_left.substring(0,shift_left.length-2) );


if ( shift_left == 0 ){
$('#pl_left').addClass('sprite_selected');
}else{
$('#pl_left').removeClass('sprite_selected');
}

if (total_width-5 <= -(shift_left - 312) ){
$('#pl_right').addClass('sprite_selected');
}else{
$('#pl_right').removeClass('sprite_selected');
}

},


toggleFeatGalleryBack:function(element){
$(element).parents('.ft_playlists').find('.ft_gal_wrp_1').show();
$(element).parents('.ft_playlists').find('.ft_gal_wrp_2').hide();
},

/*
loadVideoLandingDetail:function(p_nPage){

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

BaseAjax._xArgs.data += '&p_nPage='+p_nPage;
BaseAjax._xArgs.data += _xItem.getItemInfoAsString('video_detail',p_nPage-1,1);

BaseAjax._xArgs.returnDiv = '#detail_inner';
BaseAjax._xArgs.requestType = "GET"; 
BaseAjax.makeAjaxCall(AJAX_URL);

}
*/
featuredGalleryClick:function(p_nDirection,element){

//Check Left-Right arrows in Collection scroll
total_width = $(element).parents('.ft_playlists').find('#playlist_scroll').css('width');
//parse out "px" at the end of the string
total_width = parseInt( total_width.substring(0,total_width.length-2) );

if(p_nDirection == 1){//left arrow (scroll to the right)
if($(element).parents('.ft_playlists').find('#pl_left').hasClass('sprite_selected'))
return;

shift_left = $(element).parents('.ft_playlists').find('#playlist_scroll').css('left');
//parse out "px" at the end of the string
shift_left  = shift_left.substring(0,shift_left.length-2);
shift_left = parseInt(shift_left)+312;
$(element).parents('.ft_playlists').find('#playlist_scroll').css('left',shift_left+'px');
}else if(p_nDirection == 2){ //right
if($(element).parents('.ft_playlists').find('#pl_right').hasClass('sprite_selected'))
return;

shift_left = $(element).parents('.ft_playlists').find('#playlist_scroll').css('left');
//parse out "px" at the end of the string
shift_left  = shift_left.substring(0,shift_left.length-2);
shift_left = parseInt(shift_left)-312;
$(element).parents('.ft_playlists').find('#playlist_scroll').css('left',shift_left+'px');
}//none


shift_left = $(element).parents('.ft_playlists').find('#playlist_scroll').css('left');
shift_left = parseInt( shift_left.substring(0,shift_left.length-2) );


if ( shift_left == 0 ){
$(element).parents('.ft_playlists').find('#pl_left').addClass('sprite_selected');
}else{
$(element).parents('.ft_playlists').find('#pl_left').removeClass('sprite_selected');
}

if (total_width-5 <= -(shift_left - 312) ){
$(element).parents('.ft_playlists').find('#pl_right').addClass('sprite_selected');
}else{
$(element).parents('.ft_playlists').find('#pl_right').removeClass('sprite_selected');
}

}
}

_xThePlatformVideo={
_aVideosToDisplay : new Array(),
_aDivsToPlaceVideo : new Array(),
_bAutobahnDetectionComplete : false,
_bAutobahnDetected : null,
_bVideoDisplayed : false,

registerVideoForOuput : function(p_xSwfObject,p_sDivToPlaceVideo){
if(true == this._bAutobahnDetectionComplete){
this.displayVideo(p_xSwfObject,p_sDivToPlaceVideo);
}else{
this._aVideosToDisplay.unshift(p_xSwfObject);
this._aDivsToPlaceVideo.unshift(p_sDivToPlaceVideo);
}
},

handleAutobahnDetection : function(p_bIsAutobahnAvail){
//debugMsg("handleAutobahnDetection called with: " + p_bIsAutobahnAvail);
this._bAutobahnDetectionComplete = true;
this._bAutobahnDetected = p_bIsAutobahnAvail;
this.displayAllVideos();
},

displayAllVideos : function(){
if(0 >= this._aVideosToDisplay.length){
return;
}
var l_xTempSwfObject = null;
var l_xTempDivTarget = null;
for(var i=0; i<this._aVideosToDisplay.length; i++){
l_xTempSwfObject = this._aVideosToDisplay[i];//.shift();
l_xTempDivTarget = this._aDivsToPlaceVideo[i];//.shift();
this.displayVideo(l_xTempSwfObject,l_xTempDivTarget);
}
},

displayVideo : function(p_xSwfObject,p_sDivToPlaceVideo){
if (this._bVideoDisplayed) {
return;
}
if(this._bAutobahnDetected){ 
//p_xSwfObject.addVariable("pluginURL", "type=urlComponent|URL="+g_sResourceUrl+"swf/tp_AutoBahnUrlPlugin.swf|priority=1|autobahnBaseUrl=http://local.swarmcast.net:8001");
}
p_xSwfObject.write( p_sDivToPlaceVideo );
this._bVideoDisplayed = true;
},

writeVideoOnDocumentReady : function(p_xSwfObject,p_sDivToPlaceVideo){
$(document).ready(function() {
     p_xSwfObject.write( p_sDivToPlaceVideo );
});
}
}

_xThePlatformVideoPlayer = {

displayPlayer: function(p_sDomTarget, l_sPlatformId, l_aVideoInfo){
   
var randomnumber=Math.floor(Math.random()*11);
  var so = "so"+randomnumber; 
//Allow instream Ad & register tpRegisterId
   if(l_aVideoInfo["setInstreamAd"] == true){
tpRegisterID(p_sDomTarget);
}

//SWFOBJECT FOR VIDEO
 var so = new SWFObject("http://"+g_xVersusBaseDomain+"/swf/flvPlayer_4.2.3.swf",p_sDomTarget, 
   l_aVideoInfo["VideoWidth"], l_aVideoInfo["VideoHeight"], "9.0.115.0", "#131313");
             
 //VIDEO CONFIGURATION
 // These items set some sensible defaults on the Flash browser control.
 so.addParam("scale", "noscale");
 so.addParam("salign", "tl");
 so.addParam("menu", "true");
 so.addParam("wmode", l_aVideoInfo["wmode"]);
 //Allow full screen
 so.addParam("allowFullScreen", "true");
 // Some player plug-ins use JavaScript calls to interact with the containing page.
 // If you're using one of those plug-ins, you must grant script access.
 so.addParam("allowScriptAccess", "always");
 // Tell the component what its unique ID is.
 so.addVariable("ID", p_sDomTarget);
 so.addVariable("layoutUrl", "/feeds/metaLayout_versus_4.2.3.xml");
 // Set the logging level for the component.
 // This is equivalent to the default.
 so.addVariable("logLevel", "debug");
 so.addVariable("autoPlay", l_aVideoInfo["autoplay"]);
 // Even though we told the Flash control to allow full screen,
 // we also have to tell the component itself.
 so.addVariable("allowFullScreen", "true");
 
 //Set Ad Configuration
 // so.addVariable("adPattern", "count:0");
 so.addVariable("adCookie", "versusvideoads");
 // Earlier we told the Flash control what its size is.
 // Now we also have to tell the component how big to be.
 so.addVariable("height", l_aVideoInfo["VideoHeight"]);
 so.addVariable("width", l_aVideoInfo["VideoWidth"]);
 // Next we tell the component which skin to use.
 so.addVariable("skinURL", "http://"+g_xVersusBaseDomain+"/swf/skinCinematic_4.2.3.swf");
 // Next we load a plug-in. SMIL.swf is necessary if we are
 // going to be parsing advertising data from mps playlists.
 so.addVariable("plugin0", "type=adcomponent|URL=http://"+g_xVersusBaseDomain+"/swf/SMIL_4.2.3.swf|priority=3");
 
 if(l_aVideoInfo["VideoThumbnail"]){
   so.addVariable("previewImageURL", l_aVideoInfo["VideoThumbnail"]);
 }else{
     so.addVariable("previewImageURL", "/image/default-image.jpg?v=213_314.jpg?v=213?v=150");
 }
 // Set a link to our player's RSS feed.
 // This will be available to users who want to subscribe.
 so.addVariable("allowLink", "true");
 
 so.addVariable("playerURL", document.location.href);
 
 so.addVariable("emailServiceURL", "http://player.theplatform.com/ps/mail");
 
 so.addVariable("embeddedPlayerHtml", '<embed src="http://'+g_xVersusBaseDomain+'/swf/flvPlayer_4.2.3.swf" width='+l_aVideoInfo["VideoWidth"]+' height='+l_aVideoInfo["VideoHeight"]+' allowScriptAccess="always" allowFullScreen="true" bgcolor="#131313" wmode="transparent" flashvars="v='+g_xVersusBaseDomain+'/tp_flashvars/'+l_sPlatformId+'/'+l_aVideoInfo["VideoHeight"]+'/'+l_aVideoInfo["VideoWidth"]+'/" />');

 //Ad Plugin Instream Code.
 //Set Instream Ad: show preroll ad and instream ad.
 if(l_aVideoInfo["setInstreamAd"] == true){
 so.addVariable("pluginInStreamPlayer","type=ad|URL=http://"+g_xVersusBaseDomain+"/swf/inStream_4.2.3.swf|host=ad.doubleclick.net|bannerSizes=300x250|bannerRegions=banner_instream_300x250|priority=1");
 } else {
     so.addVariable("pluginInStreamPlayer","type=ad|URL=http://"+g_xVersusBaseDomain+"/swf/inStream_4.2.3.swf|host=ad.doubleclick.net|priority=1");
   }

 // Use this to set a release directly on the player. This link doesn't have to be from the player's feed.
 so.addVariable("releaseURL", "http://release.theplatform.com/content.select?pid="+l_sPlatformId+"&amp;format=SMIL&amp;Tracking=true");
 
//Ad insertion plugin:Format of ad insertion: http://ad.doubleclick.net/pfadx/offsitevideo.versus.dart/<param:dartzone:home>/;type=preroll;sz=480x360;tile=1
so.addVariable("pluginAdInsertion","type=adcomponent|URL=http://"+g_xVersusBaseDomain+"/swf/adInsertionPlugin_4.2.3.swf|priority=1|preRollUrls=http%3A%2F%2Fad.doubleclick.net%2Fpfadx%2Foffsitevideo.versus.dart%2Fhome%2F%3Btype%3Dpreroll%3Bsz%3D480x360%3Btile%3D1%0A");

so.addVariable("pluginControl0", "type=control|URL=http://"+g_xVersusBaseDomain+"/swf/sampleControlPlugIn_4.2.3.swf|scale=true|blink=false");

            //omniture plugin: 
if(g_sEnvironmentCurrent == g_sEnvironmentLive) { 
so.addVariable("pluginOmniture","type=tracking|URL=http://"+g_xVersusBaseDomain+"/swf/omnitureMedia_4.2.3.swf|account=versuscomdev|host=serviceo.comcast.net|frequency=0|trackEvents=event7,event11");
    }
// Near the end we set color values for the items in the component and the skin.
 so.addVariable("backgroundColor", "0x131313");
 so.addVariable("controlBackgroundColor", "0x131313");
 so.addVariable("controlColor", "0xe5e5e5");
 so.addVariable("controlFrameColor", "0x545759");
 so.addVariable("controlHoverColor", "0xFCB136");
 so.addVariable("controlSelectedColor", "0xFCB136");
 so.addVariable("frameColor", "0x131313");
 so.addVariable("pageBackgroundColor", "0x131313");
 so.addVariable("playProgressColor", "0xB53433");
 so.addVariable("scrubberColor", "0xe5e5e5");
 so.addVariable("scrubberFrameColor", "0xB53433");
 so.addVariable("scrubTrackColor", "0xe5e5e5");
 so.addVariable("textBackgroundColor", "0x383838");
 so.addVariable("textColor", "0xe5e5e5");
 so.addVariable("loadProgressColor", "0x5D9070");
 
 //Setup automated HD detection based on autobahn cookie.
 if($.cookie("autobahnDetected") == "1") {
  //so.addVariable("pluginURL", "type=urlComponent|URL="+g_sResourceUrl+"swf/tp_AutoBahnUrlPlugin.swf|priority=1|autobahnBaseUrl=http://local.swarmcast.net:8001");
 }
 //write video to html ondocument ready this would ensure that the companion ad works correctly
     //as it expects the banner div id to exist in html
_xThePlatformVideo.writeVideoOnDocumentReady(so,p_sDomTarget+"_div");

}
}


//Javascript code for instream Ads in thePlatform video player.


function initPDK(){   
//alert("initPDK() " + tpController);
tpController.addEventListener("OnMediaStart", "handleOnMediaStart");
//tpController.addEventListener("OnMediaStart", "dumpClipBanners");
}

// This is called by Instream before requesting the ad from DART and loading into the InStream.swf's inner Dart Shell.
// We can use this to override the original ad URL through the return value.
function getAdURL(originalAdURL){
// Here we have a chance to override the original ad URL
// return originalAdURL;
return null;
} 


// Running for all media start.  
// Instream plugin should set baseClip.isAd to true, so this only runs for ads
function handleOnMediaStart(pdkEvent){
//alert("handleOnMediaStart()");
//dump( pdkEvent );
// If the current clip is an ad
if ( pdkEvent.data.baseClip.isAd )
{
// Iterate through all provided banners.
for ( var i=0; i<pdkEvent.data.baseClip.banners.length; i++)
{
var bannerRegionName = pdkEvent.data.baseClip.banners[i].region;
var bannerURL = pdkEvent.data.baseClip.banners[i].src;
var bannerElement = document.getElementById(bannerRegionName);

bannerURL = bannerURL.replace("pfadx", "adi");

if(document._bIsHome){
$('#unique_banner_instream_300x250').show();
}
//alert ( "300x250 banner found.  Source is: " + bannerURL) ;
if ( bannerElement ) 
{
//bannerElement.innerHTML = "<img src='"+ bannerURL +"'/>";
bannerElement.innerHTML = "<iframe src='"+ bannerURL + "'  width='300'  height='250' scrolling='no' />"; // alternative
setTimeout('timeout_trigger("'+bannerElement+'")', 15000);
}
}
}else{
//alert("Show default ad");
}

}

function timeout_trigger(bannerElement){
//var t = document.getElementById("banner_instream_300x250");
//t.style.display = "none";
//using jquery:
//hide banner area only for homepage
if(document._bIsHome){
$('#unique_banner_instream_300x250').hide();
}
}

function dumpClipBanners(pdkEvent){
//alert("dump clip banners");
dump ( pdkEvent.data.baseClip.banners);
}

//****************************************************************************
// Copyright (C) thePlatform for Media, Inc. All Rights Reserved.
//****************************************************************************

////// UTIL FUNCTIONS ////////////

// dynamically resize an element, for example, the category list
function tpResize(divID, height, width)
{
var element = document.getElementById(divID);
element.style.height = height + "px";
element.style.width = width + "px";
}

// helper function for getting the "top" coordinate of an object
function tpGetTop(obj)
{
result = 0;
while (obj)
{
result += obj.offsetTop;
obj = obj.offsetParent;
}
return result;
}

// helper function for getting the "left" coordinate of an object
function tpGetLeft(obj)
{
result = 0;
while(obj)
{
result += obj.offsetLeft;
obj = obj.offsetParent;
}
return result;
}
tpThisMovie = function(movieName)
{
var oDoc
if (window.frame)
{
oDoc = frame.contentWindow.document || frame.contentDocument.document ;
}
else
{
oDoc = document
}
return oDoc.getElementById(movieName);
}
function tpDebug(str)
{
if (document.getElementById("debugDiv"))
{
document.getElementById("debugDiv").innerHTML += str + "<br>";
}
}

// open a new pop-up window
function tpOpenNewWindow(URLtoOpen, windowName, windowFeatures)
{
var newWindow=window.open(URLtoOpen, windowName, windowFeatures); 
}

// handle tracking URLs
var tpTrackingImage = new Image();
function tpCallTrackingUrl(url)
{
url = unescape(url);
tpTrackingImage.src = url;
for (i = 0; ((!tpTrackingImage.complete) && (i < 100000)); i++)
{
}
}

///// INIT tpController //////////
function tpGetUseJS() { return "true" }
function tpGetInstanceID() { return tpInstanceID; }
function tpGetCommManagerID() { return tpCommID; }
tpLogLevel = "warn";
function tpSetLogLevel(level){ tpLogLevel = level };
function tpGetLogLevel() { return tpLogLevel }
function tpGetProperties()
{
//each pdk controller will call this to get the default properties
var props = new Object();
props.commManagerId = tpGetCommManagerID();
props.instanceId = tpGetInstanceID();
props.useJS = tpGetUseJS();
props.registeredComponents = tpGetRegisteredIDs();
props.logLevel = tpGetLogLevel();
return props;
}

var registeredIDs = new Array();
function tpRegisterID(swfName)
{
for (var i = 0; i < registeredIDs.length; i++)
{
if (registeredIDs[i] == swfName) return;
}
registeredIDs.push(swfName);
}
function tpGetRegisteredIDs()
{
return registeredIDs;
}

// handle references to the communication manager
var tpController;
var tpCommID;
var tpBridgeID;
var tpExternalController;

//the kicks off the creation of the tpController, must be called before any pdk components are set on the page
function tpSetCommManagerID(commID, embed, commManagerUrl)
{
// alert("in tpSetCommManagerID");
// create a unique token for each set of player controls
tpInstanceID = (new Date()).getTime() + "|" + Math.round(Math.random() * 100000000000000000);
if (commID && embed)
{
//get rid of any existing commManager
var divEl = window.document.getElementById("commManagerDiv");
if (divEl)
{
divEl.parentNode.removeChild(divEl);
divEl = null;
}
//create a commManager as the first element in the body
divEl = window.document.createElement('div');
divEl.id = "commManagerDiv";
divEl.style.position = "absolute";
divEl.style.top = "0";
divEl.style.left = "0";
var bodyTag = window.document.getElementsByTagName('body')[0];
bodyTag.insertBefore(divEl, bodyTag.firstChild);
var url = commManagerUrl ? commManagerUrl : ""+g_sResourceUrl+"swf/commManager_4.2.3.swf"
var so = new SWFObject(url, commID, "1", "1", "9.0.0.0");
so.addParam("allowScriptAccess", "always");
so.addParam("wmode", "transparent");
so.write("commManagerDiv");
}
tpController = new tpControllerClass();
tpCommID = commID;
tpBridgeID = commID ? commID : "unknown";
//external controller
//tpCleanupExternal();
}

///// TPCONTROLLER CLASS /////////////

// implementation of the controller proxy in javascript
function tpControllerClass()
{
//vars loaded at bottom
/////// Send Messages to the rest of the app //////////////
///////////////////////////////////////////////////////////

//all communication to the communication manager happens here
this.sendMessage = function(destination, message, skipBus)
{
//tpDebug("putting message on queue: " + message.name + " skipBus?" + skipBus + " canMessage?" + this.canMessage + " isLoading?" + this.isLoading);
var sendObj = new Object();
sendObj.message = message;
sendObj.destination = destination;
if (this.isLoading && !skipBus)
{
//these are low priority messages that should be sent only after OnPlayerLoaded is fired
this.messageQueue.push(sendObj);
}
else if (!this.canMessage)
{
//these are high priority messages (like addEventListener or registerFunction) that usually need to be sent before OnPlayerLoaded is fired
//but we still have to wait until after the communication manager has loaded or they'll just disappear
this.priorityQueue.push(sendObj);
}
else
{
this.doSendMessage(sendObj);
}
}

this.doSendMessage = function(sendObj)//private function
{
if (this.isShutDown) return;
var obj = tpThisMovie(sendObj.destination);

//tpDebug("sending: " + sendObj.message.name + " dest:" + sendObj.destination);
// Flash ExternalInterface will convert any "" or " " string to null.  However,
// in the PDK, null and "" mean different things.  So, if there are blank strings,
// convert to a signal value, and then unconvert on the way out.
/*for (var i=0; i<sendObj.parameters.length; i++)
{
var param = sendObj.parameters[i];
if (typeof param == "string" && (param.length == 0 || param == " "))
{
sendObj.parameters[i] = this.blankString;
}
}*/
//tpDebug("do send message: " + sendObj.message.name);
obj.executeMessage(sendObj.message);
}

this.checkMessageQueue = function()//private function
{
var len = this.messageQueue.length
while (this.messageQueue.length > 0)
{
this.doSendMessage(this.messageQueue.shift());
}
}

this.checkPriorityQueue = function()
{
while (this.priorityQueue.length > 0)
{
var sendObj = this.priorityQueue.shift();
if (sendObj.destination == "unknown") sendObj.destination = tpBridgeID;
this.doSendMessage(sendObj);
}
}

this.wrapMessage = function(messageName, payload)
{
var comm = {globalDataType:this.getDataTypeName("CommInfo"), id:"javascript"}
var message = {globalDataType:this.getDataTypeName("MessageInfo"), name:messageName, payload:payload, comm:comm};
return message;
}
this.getDataTypeName = function(shortType)
{
switch(shortType)
{
case "AdPattern":return "com.theplatform.pdk.data::AdPattern";
case "Banner":return "com.theplatform.pdk.data::Banner";
case "BaseClip":return "com.theplatform.pdk.data::BaseClip";
case "CallInfo":return "com.theplatform.pdk.communication::CallInfo";
case "CategoryInfo":return "com.theplatform.pdk.data::CategoryInfo";
case "Clip":return "com.theplatform.pdk.data::Clip";
case "CommInfo":return "com.theplatform.pdk.communication::CommInfo";
case "CustomData":return "com.theplatform.pdk.data::CustomData";
case "CustomValue":return "com.theplatform.pdk.data::CustomValue";
case "DispatchInfo":return "com.theplatform.pdk.communication::DispatchInfo";
case "FunctionInfo":return "com.theplatform.pdk.communication::FunctionInfo";
case "HandlerInfo":return "com.theplatform.pdk.communication::HandlerInfo";
case "HyperLink":return "com.theplatform.pdk.data::HyperLink";
case "MediaClick":return "com.theplatform.pdk.data::MediaClick";
case "MediaFile":return "com.theplatform.pdk.data::MediaFile";
case "MessageInfo":return "com.theplatform.pdk.communication::MessageInfo";
case "MetricInfo":return "com.theplatform.pdk.data::MetricInfo";
case "Overlay":return "com.theplatform.pdk.data::Overlay";
case "PdkEvent":return "com.theplatform.pdk.events::PdkEvent";
case "ProviderInfo":return "com.theplatform.pdk.data::ProviderInfo";
case "Range":return "com.theplatform.pdk.data::Range";
case "Rating":return "com.theplatform.pdk.data::Rating";
case "Release":return "com.theplatform.pdk.data::Release";
case "ReleaseInfo":return "com.theplatform.pdk.data::ReleaseInfo";
case "ScopeInfo":return "com.theplatform.pdk.communication::ScopeInfo";
case "Sort":return "com.theplatform.pdk.data::Sort";
case "Subtitles":return "com.theplatform.pdk.data::Subtitles";
case "TrackingUrl":return "com.theplatform.pdk.data::TrackingUrl";
}
}
this.createScope = function(scope)
{
if (scope == undefined) return this.defaultScope;
else
{
scope.push("javascript");
tpDebug("creating scopes: " + scope.toString());
return {globalDataType:this.getDataTypeName("ScopeInfo"),controlId:"javascript",isGlobal:true,isAny:false,isEmpty:false,scopeIds:scope};
}
}

//////// handle communication to the rest of the app ///////
////////////////////////////////////////////////////////////

//register a function
this.registerFunction = function(funcName, callback, scopes)
{
var scopeObj = this.createScope(scopes);
var informComm = false;
if (this.functions[funcName] == undefined)
{
this.functions[funcName] = new Object();
informComm = true;
}
for (var i = 0; i < scopeObj.scopeIds.length; i++)
{
var s = scopeObj.scopeIds[i];
if (s == "*") return;//can't register a scope of any
this.functions[funcName][s] = callback;
}
if (informComm)
{
//send the registered function to the commManager
var func = {globalDataType:this.getDataTypeName("FunctionInfo"),name:funcName,scope:scopeObj};
var message = this.wrapMessage("registerFunction", func);
this.sendMessage(tpBridgeID,message,true);
}
}

this.unregisterFunction = function(funcName, scope)
{
var scopeObj = this.createScope(scopes);
if (this.functions[funcName] != undefined)
{
var funcs = this.functions[funcName];
for (var i = 0; i < scopeObj.scopeIds.length; i++)
{
var s = scopeObj.scopeIds[i];
if (s == "*")
{
delete funcs;//delete them all
break;
}
if (funcs[s] != undefined) delete funcs[s];//delete each scope
}
var funcsLeft = false;
if (funcs != undefined)//prune the object
{
for (var sc in funcs)
{
funcsLeft = true;
break;
}
if (!funcsLeft) delete this.functions[funcName];
}
}
if (!funcsLeft)
{
var func = {globalDataType:this.getDataTypeName("FunctionInfo"),name:funcName,scope:scopeObj};
var message = this.wrapMessage("unregisterFunction", func);
this.sendMessage(tpBridgeID,message,true);
}
}

this.addEventListener = function(eventName, callback, scope)
{
tpDebug("adding event listener: " + eventName + " callback:" + callback);
var scopeObj = this.createScope(scope);
var handler = {globalDataType:this.getDataTypeName("HandlerInfo"),name:eventName,handler:callback,scope:scopeObj}
var informComm = false;
if (this.events[eventName] == undefined)
{
this.events[eventName] = new Array();
informComm = true;
}
var evts = this.events[eventName];
var repeat = false;
for (var i = 0; i < evts.length; i++)//repeats?
{
if (evts[i].handler == callback)
{
evts[i] = handler;//replace the scopes
repeat = true;
break;
}
}
if (!repeat) evts.push(handler);
tpDebug("how many listeners? " + evts.length);
if (informComm)
{
tpDebug("informing comm of event listener");
var message = this.wrapMessage("addEventListener", handler);
this.sendMessage(tpBridgeID,message,true);
}
}
this.removeEventListener = function(eventName, callback, scope)
{
if (this.events[eventName] != undefined)
{
var scopeObj = this.createScope(scope);
var handler = {globalDataType:this.getDataTypeName("HandlerInfo"),name:eventName,handler:callback,scope:scopeObj}

var eventArray = this.events[eventName];
for (var i = 0; i < eventArray.length; i++)
{
var h = eventArray[i];
if (h.handler == handler.handler)
{
eventArray = eventArray.splice(i, 1);
break;
}
}
if (eventArray.length == 0)
{
//no callbacks left, zap the variable
delete this.events[eventName];
var message = this.wrapMessage("removeEventListener", handler);
this.sendMessage(tpBridgeID, message, true)
}
}
}

this.dispatchEvent = function(eventName, value, scope)
{
var scopeObj = this.createScope(scope);
var evt = {globalDataType:this.getDataTypeName("PdkEvent"),type:eventName, data:value};
var dispatch = {globalDataType:this.getDataTypeName("DispatchInfo"),evt:evt,scope:scopeObj};
//check local events
this.doDispatchEvent(dispatch);

var message = this.wrapMessage("dispatchEvent", dispatch);
this.sendMessage(tpBridgeID, message, true);
}

this.callFunction = function(funcName, args, scope)
{
var scopeObj = this.createScope(scope);
var call = {globalDataType:this.getDataTypeName("CallInfo"),name:funcName,args:args,scope:scopeObj};
this.doCallFunction(call);

var message = this.wrapMessage("callFunction", call);
this.sendMessage(tpBridgeID, message, true);
}

this.doDispatchEvent = function(dispatch)
{
tpDebug("do dispatching event: " + dispatch.evt.type);
if (this.events[dispatch.evt.type] != undefined)
{
var handlers = this.events[dispatch.evt.type]
for (var i = 0; i < handlers.length; i++)
{
var handler = handlers[i];
tpDebug("checking handler? " + handler.handler)
if (dispatch.scope.isAny)
{
eval(handler.handler)(dispatch.evt);
continue;
}
for (var j = 0; j < handler.scope.scopeIds.length; j++)
{
var s = handler.scope.scopeIds[j];
var fired = false;
if (s == "*")
{
eval(handler.handler)(dispatch.evt);
break;
}
for (var k = 0; k < dispatch.scope.scopeIds.length; k++)
{
tpDebug("running through scopes handler: " + s + " dispatch: " + dispatch.scope.scopeIds[k]);
if (s == dispatch.scope.scopeIds[k])
{
fired = true;
tpDebug("firing");
eval(handler.handler)(dispatch.evt);
break;
}
}
if (fired) break;//go to next handler
}
}
}
}

this.doCallFunction = function(call)
{
if (this.functions[call.name] != undefined)
{
//check local functions
var funcsToCall = new Object();
for (var i = 0; i < call.scope.scopeIds.length; i++)
{
var s = call.scope.scopeIds[i];
if (this.functions[call.name][s] != undefined)
{
funcsToCall[this.functions[call.name][s]] = "f";//we need lookup
}
}
for (var f in funcsToCall)
{
eval(f)(call.args);
}
}
}




//////// RECEIVE CALLS FROM AS //////////////
////////////////////////////////////////////

//all communication from the communication manager happens here
this.receiveMessage = function(destination, message)
{
if (destination == "javascript")
{
//tpDebug("receiving message: " + message.name)
var messStr = message.name;
switch(messStr)
{

case "commReady":
tpBridgeID = tpCommID;
this.canMessage = true;
this.checkPriorityQueue();
break;
case "bridgeReady":
tpBridgeID = message.comm.id;
this.canMessage = true;
this.checkPriorityQueue();
break;
case "dispatchEvent":
var dispatch = message.payload;
this.receiveEvent(dispatch);
break;
case "callFunction":
var call = message.payload;
this.doCallFunction(call);
break;
default:
break;
}
}
else
{
//transfer the message to its final destination
this.sendMessage(destination, message, true);
}
}
this.receiveEvent = function(dispatch)
{
//tpDebug("RECIEVED:" + dispatch.evt.type)

if (dispatch.evt.type == "OnPlayerLoaded")
{
this.isLoading = false;
this.checkMessageQueue();
}
this.doDispatchEvent(dispatch);
}

//create a list of direct calls

// PLAYER

this.setRelease = function(release, replaceDefault, scope)
{
release = this.modRelease(release);
var args = [release, replaceDefault];
this.callFunction("setRelease", args, scope);
}
this.loadRelease = function(release, replaceDefault, scope)
{
release = this.modRelease(release);
var args = [release, replaceDefault];
this.callFunction("loadRelease", args, scope);
}
this.loadReleaseURL = function(releaseURL, replaceDefault, scope)
{
var args = [releaseURL, replaceDefault];
this.callFunction("loadReleaseURL", args, scope);
}
this.setReleaseURL = function(url, replaceDefault, scope)
{
var args = [url, replaceDefault];
this.callFunction("setReleaseURL", args, scope);
}
this.loadSmil = function(smil, replaceDefault, scope)
{
if (replaceDefault == undefined) replaceDefault = true;
this.callFunction("loadSmil", [smil, replaceDefault], scope);
}
this.setSmil = function(smil, scope)
{
this.callFunction("setSmil", [smil], scope);
}
this.resetPlayer = function(scope)
{
this.callFunction("resetPlayer", [], scope);
}
this.setPlayerMessage = function(message, showDuration, scope)
{
if (showDuration == undefined) showDuration = 5000;
this.callFunction("setPlayerMessage", [message, showDuration], scope);
}
this.clearPlayerMessage = function(scope)
{
this.callFunction("clearPlayerMessage", [], scope);
}
this.setCurrentReleaseList = function(id, scope)
{
var args = [id];
this.callFunction("setCurrentReleaseList", args, scope);
}
this.seekToPosition = function(position, scope)
{
var args = [position];
this.callFunction("seekToPosition", args, scope);
}
this.seekToPercentage = function(percent, scope)
{
var args = [percent];
this.callFunction("seekToPercentage", args, scope);
}
this.nextClip = function(scope)
{
var args = [];
this.callFunction("nextClip", args, scope);
}
this.previousClip = function(scope)
{
var args = [];
this.callFunction("previousClip", args, scope);
}
this.mute = function(muted, scope)
{
var args = [muted];
this.callFunction("mute", args, scope);
}
this.pause = function(paused, scope)
{
var args = [paused];
this.callFunction("pause", args, scope);
}
this.setPreviewImageUrl = function(url, scope)
{
var args = [url];
this.callFunction("setPreviewImageUrl", args, scope);
}
this.showFullScreen = function(isFullScreen, scope)
{
var args = [isFullScreen];
this.callFunction("showFullScreen", args, scope);
}
this.showEmailForm = function(visible, scope)
{
var args = [visible];
this.callFunction("showEmailForm", args, scope);
}
this.showLinkForm = function(visible, scope)
{
var args = [visible];
this.callFunction("showLinkForm", args, scope);
}
this.trace = function(str, className, level)
{
var args = [str, className, level];
this.callFunction("trace", args, null); 
}
this.useDefaultPlayOverlay = function(useDefault, scope)
{
var args = [useDefault];
this.callFunction("useDefaultPlayOverlay", args, scope);
}
this.getUseDefaultPlayOverlay = function(scope)
{
var args = [];
this.callFunction("getUseDefaultPlayOverlay", args, scope);
}
this.useDefaultLinkForm = function(useDefault, scope)
{
var args = [useDefault];
this.callFunction("useDefaultLinkForm", args, scope);
}
this.useDefaultEmailForm = function(useDefault, scope)
{
var args = [useDefault];
this.callFunction("useDefaultEmailForm", args, scope);
}
this.getSubtitleLanguage = function(requestor, scope)
{
var args = [requestor];
this.callFunction("getSubtitleLanguage", args, scope);
}
this.clickPlayButton = function(scope)
{
var args = [];
this.callFunction("clickPlayButton", args, scope);
}
this.disablePlayerControls = function(disable, exceptions, scope)
{
var args = [disable, exceptions];
this.callFunction("disablePlayerControls", args, scope);
}
this.setSubtitleLanguage = function(language, scope)
{
var args = [language];
this.callFunction("setSubtitleLanguage", args, scope);
}
this.getPlayerVariables = function(names, scope)
{
var args = [names];
this.callFunction("getPlayerVariables", args, scope);
}
this.setVolume = function(volume, scope)
{
var args = [volume];
this.callFunction("setVolume", args, scope);
}
this.clearAdCookie = function(scope)
{
var args = [];
this.callFunction("clearAdCookie", args, scope);
}

// RELEASE MODEL

this.refreshReleaseModel = function(category, search, sort, range, params, secondaryParams, scope)
{
if (sort) sort.globalDataType = this.getDataTypeName("Sort");
if (range) range.globalDataType = this.getDataTypeName("Range");
var args = [category, search, sort, range, params, secondaryParams];
this.callFunction("refreshReleaseModel", args, scope);
}

// CATEGORY MODEL

this.refreshCategoryModel = function(params, scope)
{
var args = [params];
this.callFunction("refreshCategoryModel", args, scope);
}

// NAVIGATION

this.nextRange = function(scope)
{
var args = [];
this.callFunction("nextRange", args, scope);
}
this.previousRange = function(scope)
{
var args = [];
this.callFunction("previousRange", args, scope);
}


// CLIP INFO

this.setClipInfo = function(clip, isDefault, scope)
{
clip = this.modClip(clip);
var args = [clip, isDefault];
this.callFunction("setClipInfo", args, scope);
}

// CATEGORY LIST

this.clearCategorySelection = function(scope) 
{
var args = [];
this.callFunction("clearCategorySelection", args, scope);
}

// RELEASE LIST

this.suspendPlayAll = function(suspend, scope) 
{
var args = [suspend];
this.callFunction("suspendPlayAll", args, scope);
}
this.playNext = function(wrapAround, naturalEnd, scope) 
{
var args = [wrapAround, naturalEnd];
this.callFunction("playNext", args, scope);
}
this.playPrevious = function(wrapAround, scope) 
{
var args = [wrapAround];
this.callFunction("playPrevious", args, scope);
}

// GENERAL
this.modRelease = function(release)
{
if (release)
{
release.globalDataType = this.getDataTypeName("Release");
if (release.categories) release.categories = this.modCategories(release.categories);
if (release.thumbnails)
{
for (var i = 0; i < release.thumbnails.length; i++)
{
release.thumbnails[i].globalDataType = this.getDataTypeName("MediaFile");
if (release.thumbnails[i].customValues) release.thumbnails[i].customValues = this.modCustomValues(release.thumbnails[i].customValues);

}
}
if (release.customValues) release.customValues = this.modCustomValues(release.customValues);
if (release.metrics)
{
for (var i = 0; i < release.metrics.length; i++)
{
release.metrics[i].globalDataType = this.getDataTypeName("MetricInfo");
}
}
if (release.provider)
{
release.provider.globalDataType = this.getDataTypeName("ProviderInfo");
if (release.provider.customValues) release.provider.customValues = this.modCustomValues(release.provider.customValues);
}
if (release.ratings)
{
for (var i = 0; i < release.ratings.length; i++)
{
release.ratings[i].globalDataType = this.getDataTypeName("Rating");
}
}
// backwards compatibility helper
if (release.URL)
{
release.url = release.URL;
}
}
return release;
}
this.modCustomValues = function(customValues)
{
for (var i = 0; i < customValues.length; i++)
{
customValues[i].globalDataType = this.getDataTypeName("CustomValue");
}
return customValues;
}
this.modCategories = function(categories)
{
for (var i = 0; i < categories.length; i++)
{
categories[i].globalDataType = this.getDataTypeName("CategoryInfo");
}
return categories;
}
this.modClip = function(clip)
{
if (clip)
{
//set the class names correctly for casting in as3.
clip.globalDataType = this.getDataTypeName("Clip");
var baseClip = clip.baseClip;
if (!baseClip) baseClip = new Object();
if (clip.banners) baseClip.banners = clip.banners;
if (clip.overlays) baseClip.overlays = clip.overlays;
clip.baseClip = this.modBaseClip(baseClip);
if (clip.chapter) clip.chapter.globalDataType = this.getDataTypeName("Chapter");
}
return clip;
}
this.modBaseClip = function(baseClip)
{
if (!baseClip) baseClip = new Object();
baseClip.globalDataType = this.getDataTypeName("BaseClip");
if (baseClip.moreInfo)
{
baseClip.moreInfo.globalDataType = this.getDataTypeName("HyperLink");
if (baseClip.moreInfo.clickTrackingUrls) baseClip.moreInfo.clickTrackingUrls = this.modTracking(baseClip.moreInfo.clickTrackingUrls);
}
if (baseClip.banners)
{
for (var i = 0; i < baseClip.banners.length; i++)
{
baseClip.banners[i].globalDataType = this.getDataTypeName("Banner");
if (baseClip.banners[i].clickTrackingUrls) baseClip.banners[i].clickTrackingUrls = this.modTracking(baseClip.banners[i].clickTrackingUrls)
}
}
if (baseClip.overlays)
{
for (var i = 0; i < baseClip.overlays.length; i++)
{
baseClip.overlays[i].globalDataType = this.getDataTypeName("Overlay");
if (baseClip.overlays[i].clickTrackingUrls) baseClip.overlays[i].clickTrackingUrls = this.modTracking(baseClip.overlays[i].clickTrackingUrls)
}
}
if (baseClip.availableSubtitles)
{
for (var i = 0; i < baseClip.availableSubtitles; i++)
{
baseClip.availableSubtitles[i].globalDataType = this.getDataTypeName("Subtitles");
}
}
if (baseClip.categories) baseClip.categories = this.modCategories(baseClip.categories);
if (baseClip.adPattern) baseClip.adPattern.globalDataType = this.getDataTypeName("AdPattern");
if (baseClip.trackingURLs) baseClip.trackingURLs = this.modTracking(baseClip.trackingURLs);
if (baseClip.contentCustomData) baseClip.contentCustomData.globalDataType = this.getDataTypeName("CustomData");
if (baseClip.ownerCustomData) baseClip.ownerCustomData.globalDataType = this.getDataTypeName("CustomData");
if (baseClip.outletCustomData) baseClip.outletCustomData.globalDataType = this.getDataTypeName("CustomData");
return baseClip;
}
this.modTracking = function(trackingUrls)
{
for (var i = 0; i < trackingUrls.length; i++)
{
trackingUrls.globalDataType = this.getDataTypeName("TrackingUrl")
}
return trackingUrls
}
this.shutDown = function()
{
var args = [];
this.callFunction("shutDown", args, ["*"]);
this.isShutDown = true;//prevent any more messages
}
//vars initialized
this.events = new Object();
this.functions = new Object();
this.isLoading = true;
this.canMessage = false;
this.messageQueue = new Array();
this.priorityQueue = new Array();
this.sendQueue = new Array();//yet another queue for timing externalInterface calls
this.isSending = false;
this.sendInterval;
this.shutdownIDs;//array to keep all the controller ids for shutdown
this.isShutDown = false;
this.blankString = "__blank_string__";
this.defaultScope = {globalDataType:this.getDataTypeName("ScopeInfo"),controlId:"javascript",isGlobal:true,isAny:false,isEmpty:false,scopeIds:["javascript","default"]};

}

function tpReceiveMessage(destination, message)
{
//tpDebug("---message received---" + message.name + " dest:" + destination)
tpController.receiveMessage(destination, message);
}


//functions for controlling external players

var tpHolderName = "pdkHolder";
var tpExternalJS;

function tpSetPlayerIDForExternal(playerName){};//no longer needed

function tpSetHolderIDForExternal(holderName)//needed
{
tpHolderName = holderName;
}

function tpLoadExternalMediaJS()
{
tpExternalJS = tpLoadExternalMediaJS.arguments;

for (var i = 0; i < tpExternalJS.length; i++)
{
tpLoadScript(tpExternalJS[i]);
}
}

function tpCleanupExternal()
{
if (tpExternalJS)//if there's no external js, then nothing was loaded in
{
var scripts = window.document.getElementsByTagName('head')[0].getElementsByTagName('script');
for (var i = 0; i < scripts.length;i++)
{
for (var j = 0; j < tpExternalJS.length; j++)
{
if (scripts[i].src == tpExternalJS[j])
{
window.document.getElementsByTagName('head')[0].removeChild(scripts[i]);
break;
}
}
}
tpExternalJS.length = 0;
}
if (tpExternalController)
{
tpExternalController.cleanup();
}
}


/////////////////////////////////////////////////////////////////////

tpScriptLoader = new ScriptLoader();

// called from flash via ExternalInterface
function tpLoadJScript(scriptFile, callback, id, atts)
{
tpScriptLoader.addScript(scriptFile, callback, id, atts);
}

// need to wrap method to fix scoping issue on callback
function callbackDispatcher(loadObj) { tpScriptLoader.callbackDispatcher(loadObj) }
function invokeCallbacks(loadObj) { tpScriptLoader.invokeCallbacks() }

/////////////////////////////////////////////////////////////////////
//L O A D   O B J E C T
/////////////////////////////////////////////////////////////////////
function LoadObj(scriptFile, callback, id, atts)
{
this.script = scriptFile;
this.callback = callback;
this.id = id;
this.atts = atts;
}

/////////////////////////////////////////////////////////////////////
//S C R I P T   L O A D E R
/////////////////////////////////////////////////////////////////////


// constructor
function ScriptLoader()
{
// queued up for loading scripts
this.scriptQueue = new Array();

// queued up for invoking callbacks
this.callbackQueue = new Array();
}

/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.addScript = function(scriptFile, callback, id, atts)
{
var loadObj = new LoadObj( scriptFile, callback, id, atts );
this.scriptQueue.push(loadObj);

// if the queue was empty, we need to kick
// off the queue processing again.

if (this.scriptQueue.length == 1)
this.checkScriptQueue();
}

/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.checkScriptQueue = function()
{
if (this.scriptQueue.length)
{
var loadObj = this.scriptQueue.shift();
this.loadScript(loadObj);
}
else
{
// as a timing precaution, we wait until the queue
// empties out before we invoke callbacks
interval_id = setInterval("invokeCallbacks()",100) // more timing precautions :-/
//this.invokeCallbacks();
}
}

/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.callbackDispatcher = function(loadObj)
{
for (var i in this.callbackQueue)
{
if (this.callbackQueue[i] == loadObj)
{
this.checkScriptQueue();
return;
}
}
this.callbackQueue.push(loadObj);
this.checkScriptQueue();
}

/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.invokeCallbacks = function()
{
clearInterval(interval_id);
while (this.callbackQueue.length)
{
var loadObj = this.callbackQueue.shift();
eval(loadObj.callback)(loadObj.script);
}
}

/////////////////////////////////////////////////////////////////////
ScriptLoader.prototype.loadScript = function(loadObj)
{
var scriptFilename = loadObj.script;
var callbackFunction = loadObj.callback;
var id = loadObj.id;
var atts = loadObj.atts;

// Create script element and set it to load the requested script
var scriptEl = window.document.createElement('script');
scriptEl.charset = "utf-8";
if (id) scriptEl.id = id;
scriptEl.type = "text/javascript";
//scriptEl.defer = true;
if (atts)
{
for (var i = 0; i < atts.length; i++)
scriptEl.setAttribute(atts[i].att, atts[i].value);
}
scriptEl.src = scriptFilename;

if (callbackFunction)
{
// Function to be called when script has finished loading
var _onFinished = function(_loadObj, _callback)
{
// Invoke the callback function
_callback(_loadObj)

// Clean up event handlers
this.onreadystatechange = null;
this.onload = null;
this.onerror = null;
};

// Set callback for IE
// In defiance of MSDN documentation IE's script object has no onload handler
scriptEl.onreadystatechange = function()
{
_onFinished(loadObj, callbackDispatcher);
};

// Set callback for W3C-compatible browsers
scriptEl.onload = function()
{
_onFinished(loadObj, callbackDispatcher);
};
// Set another callback for W3C-compatible browsers
// since onreadystatechange for IE also fires in case of an error
scriptEl.onerror = function()
{
_onFinished(loadObj, callbackDispatcher);
};
}

// Add script element to the document
window.document.getElementsByTagName('head')[0].appendChild(scriptEl);
}

/////////////////////////////////////////////////////////////////////
// ORIGINAL LOADSCRIPT - USED BY MOVENETWORKS 
/////////////////////////////////////////////////////////////////////
function tpLoadScript(scriptFilename, callbackFunction, id, atts)
{
   // Create script element and set it to load the requested script
   var scriptEl = window.document.createElement('script');
   scriptEl.charset = "utf-8";
   if (id) scriptEl.id = id;
   scriptEl.type = "text/javascript";
   //scriptEl.defer = true;
   if (atts)
   {
   for (var i = 0; i < atts.length; i++)
   {
   scriptEl.setAttribute(atts[i].att, atts[i].value);
   }
   }
   scriptEl.src = scriptFilename;
   if (callbackFunction)
   {
   // Function to be called when script has finished loading
   var _onFinished = function(_callbackFunction, _scriptFilename)
   {
   // Invoke the callback function
   _callbackFunction(_scriptFilename);
   
   // Clean up event handlers
   this.onreadystatechange = null;
   this.onload = null;
   this.onerror = null;
   };
   
   // Set callback for IE
   // In defiance of MSDN documentation IE's script object has no onload handler
   scriptEl.onreadystatechange = function()
   {
   _onFinished(callbackFunction, scriptFilename);
   };
   
   // Set callback for W3C-compatible browsers
   scriptEl.onload = function()
   {
   _onFinished(callbackFunction, scriptFilename);
   };
   // Set another callback for W3C-compatible browsers
   // since onreadystatechange for IE also fires in case of an error
   scriptEl.onerror = function()
   {
   _onFinished(callbackFunction, scriptFilename);
   };
   }
   
   // Add script element to the document
   window.document.getElementsByTagName('head')[0].appendChild(scriptEl);
}

/////////////////////////////////////////////////////////////////////



//constructor for tpExternalControl
function tpExternalControllerClass()
{
this.playerTypes = new Object();//keep a lookup of classes
this.extPlayers = new Object();//keep the instances here

this.registerExternalPlayer = function(type, playerClass)
{
this.playerTypes[type] = playerClass;//keep the class as a string
}

this.routeMessage = function(swfId, controllerId, streamType, funcName, args)
{
var curController = this.extPlayers[controllerId];//see if we have the existing controller lookup
if (!curController) curController = this.extPlayers[controllerId] = {};//make a lookup for the controller
var curPlayer = curController[streamType];//now see if we have the actual player object instantiated
if (!curPlayer)
{
var playerClass = this.playerTypes[streamType];
if (!playerClass) return; //we don't have the correct stream type on hand
curPlayer = eval("new " + playerClass + "('" + swfId + "', '" + controllerId + "');");//create a new instance of the class
if (!curPlayer) return;//abort here, too
curController[streamType] = curPlayer;
}
curPlayer[funcName](args);
}

this.returnMessage = function(swfId, controllerId, funcName, args)
{
var obj = tpThisMovie(swfId);
obj.receiveJSMessage(controllerId, funcName, args);
}

this.cleanup = function()
{
for (var controllerId in this.extPlayers)
{
var players = this.extPlayers[controllerId];
for (var player in players)
{
players[player].cleanup();
delete players[player];
}
delete this.extPlayers[controllerId];
}
}
}

function tpExternalMessage(swfId, controllerId, streamType, funcName, args)
{
tpExternalController.routeMessage(swfId, controllerId, streamType, funcName, args);
}

//build this without needing the commManager
tpExternalController = new tpExternalControllerClass();

function tpShowAlert(alertCode) 
{
switch(alertCode)
{
case "FULLSCREEN_DISABLED":
//if (deconcept.SWFObjectUtil.getPlayerVersion().major < 9)
alert("Full screen is only available with Flash 9 or later")
break;
}
}

/**********************************
Here is a list of the events that are produced by the flvPlayer.
Data structures are explained below.  NOTE: The mediaType for any event that sends back an entire playlist
is always "ALL".

Events that send in a playlist data type (which can include multiple clips):
onPlaylistBegin -- fired when new playlist data is first received by the player
onPlaylistEnd -- fired when a playlist has completed playing, either naturally or when it is replaced by another playlist
onClipTime -- fired every 5 seconds or so to give a snapshot of the state of the current playlist and the clips within it

Events that send in a single clip data type:
onBeginMedia -- fired when a media first starts playing, after it has buffered sufficiently.
onEndMedia -- fired when a media has completed naturally.  If a media ends because the playlist has been replaced, this event is not fired.
onMidMedia -- fired when a media reaches a point between 40 and 60 percent.  If the user skips over this section of the media, this event is not fired

playlist data type:
pl.currentDate
pl.playlistID
pl.userName
pl.countryCode
pl.regionCode
pl.browser
pl.operatingSystem
pl.feed
pl.affiliateTag
pl.playerName
pl.clips //array of clips below

clip data type:
clip.baseClip.title
clip.baseClip.author
clip.baseClip.abstract
clip.baseClip.copyright
clip.baseClip.height
clip.baseClip.width
clip.baseClip.isAd
clip.baseClip.keywords
clip.baseClip.releaseID
clip.baseClip.releaseLength -- the length of the clip as shown in system, in milliseconds
clip.baseClip.bitrate -- the bitrate of the clip as shown in system, bps (not kbps)
clip.baseClip.trueLength -- the actual length of the clip as determined at runtime, in milliseconds
clip.baseClip.trueBitrate -- the actual bitrate of the clip as determined at runtime, in kbps (not bps)
clip.baseClip.connectionBitrate -- the actual bitrate of the user's connection as determined at runtime, if this data could not be ascertained, this value will be undefined, in kbps (not bps)
clip.baseClip.loadTime -- the total miliseconds between when the request is made for the clip and when the clip starts running.
clip.baseClip.lengthPlayed -- the total miliseconds that the clip actually played, if the clip did not play, this value is undefined
clip.baseClip.rebufferingTime -- the total miliseconds the player spent buffering itself.

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

tpQOSTypeArray = new Array();
var tpQOScurrentPL;
var tpQOSunloading;

function tpRegisterQOSType(eventType, mediaType, callback)
{
for (var i = 1; i < tpQOSTypeArray.length; i++)
{
if (tpQOSTypeArray[i].eventType == eventType && tpQOSTypeArray[i].mediaType == mediaType && tpQOSTypeArray[i].callback == callback)
{
return;//there's already one there, don't put another in
}
}
var qosTypeObj = {mediaType:mediaType, eventType:eventType, callback:callback}
tpQOSTypeArray.push(qosTypeObj);
}

function tpUnregisterQOSType(type, callback)
{
for (var i = 1; i < tpQOSTypeArray.length; i++)
{
if (tpQOSTypeArray[i].eventType == eventType && tpQOSTypeArray[i].mediaType == mediaType && tpQOSTypeArray[i].callback == callback)
{
tpQOSTypeArray.splice(i, 1);//get rid of the element
break;
}
}
}

//called from the Player when an event is fired
function tpReceiveQOSEvent(eventType, mediaType, obj)
{
if (obj == undefined) return;//don't do anything, the data is bad

if (eventType == "onClipTime" || eventType == "onPlaylistBegin")
{
tpQOScurrentPL = obj;
}
else if (eventType == "onPlaylistEnd")
{
tpQOScurrentPL = null;//get rid so we don't hit twice if browser closes and a new playlist hasn't yet replaced the old
}

//go through the type array and see if we have a match

for (var i = 0; i < tpQOSTypeArray.length; i++)
{
if (tpQOSTypeArray[i].eventType == eventType && (mediaType == "ALL" || tpQOSTypeArray[i].mediaType == mediaType || tpQOSTypeArray[i].mediaType == "ALL"))
{
eval(tpQOSTypeArray[i].callback)(obj);
}
}
}

window.onunload = function()
{
tpQOSUnload();
}

function tpQOSUnload()
{
if(tpQOScurrentPL == undefined || tpQOScurrentPL == null) return;
//mock up a playlist end event
tpQOSunloading = true;
tpReceiveQOSEvent("onPlaylistEnd", "ALL", tpQOScurrentPL);
}

function tpQOSSendURL(url)
{
var connection = new Image();
connection.src = url;
if (tpQOSunloading)
{
for (i = 0; ((!connection.complete) && (i < 100000)); i++)
{
}
}
}





//register our functionality with the qos component
tpRegisterQOSType("onPlaylistEnd", "ALL", "QOSMPS_handlePLEnd");

//what's the base url for the mps qos?
var QOSMPS_baseUrl = "http://release.theplatform.com/tracker.log"
var QOSMPS_qs = "";
var QOSMPS_baseCount = 0;
var QOSMPS_baseClips = new Array();

function QOSMPS_handlePLEnd(pl)
{
QOSMPS_baseCount = 0;
QOSMPS_baseClips.length = 0;
//the first 3 values are always the same

QOSMPS_qs = "?type=qos&ver=1";
//let's parse out the query string
if (pl.currentDate != undefined && pl.currentDate != null && pl.currentDate != "null") QOSMPS_appendStr_qs("d", pl.currentDate);
if (pl.userName != undefined && pl.userName != null && pl.userName != "null") QOSMPS_appendStr_qs("un", pl.userName);
if (pl.countryCode != undefined && pl.countryCode != null && pl.countryCode != "null") QOSMPS_appendStr_qs("cc", pl.countryCode);
if (pl.regionCode != undefined && pl.regionCode != null && pl.regionCode != "null") QOSMPS_appendStr_qs("rc", pl.regionCode);
if (pl.browser != undefined && pl.browser != null && pl.browser != "null") QOSMPS_appendStr_qs("br", pl.browser);
if (pl.operatingSystem != undefined && pl.operatingSystem != null && pl.operatingSystem != "null") QOSMPS_appendStr_qs("os", pl.operatingSystem);
if (pl.feed != undefined && pl.feed != null && pl.feed != "null") QOSMPS_appendStr_qs("p", pl.feed);
if (pl.player != undefined && pl.player != null && pl.player != "null") QOSMPS_appendStr_qs("pl", pl.player);
if (pl.affiliate != undefined && pl.affiliate != null && pl.affiliate != "null") QOSMPS_appendStr_qs("af", pl.affiliate);
if (pl.playlistID != undefined && pl.playlistID != null && pl.playlistID != "null") QOSMPS_appendStr_qs("prid", pl.playlistID);
for (var i = 0;i < pl.clips.length;i++)
{
QOSMPS_parseClip(pl.clips[i]);
}

if (QOSMPS_baseClips.length > 1) QOSMPS_parseAggregate(pl.playlistID)//parse the aggregate data only if there are 2 or more clips
QOSMPS_sendData(QOSMPS_qs);
}

function QOSMPS_parseClip(c)
{
var bc = c.baseClip;
var isC = false;
for (var i = 0; i < QOSMPS_baseClips.length; i++)
{
if (QOSMPS_baseClips[i].releaseID == bc.releaseID)
{
if (bc.isAd)
{
QOSMPS_appendStr_qs("c" + QOSMPS_baseCount, "1");
break;
}
else
{
return;//don't parse this one, it's a repeat content
}
}
}
QOSMPS_baseClips.push(bc);
if (bc.releaseID != undefined)  QOSMPS_appendStr_qs("rid" + QOSMPS_baseCount, bc.releaseID);

if (bc.title != undefined && bc.title != null && bc.title != "null")  QOSMPS_appendStr_qs("t" + QOSMPS_baseCount, bc.title);
if (bc.author != undefined && bc.author != null && bc.author != "null")  QOSMPS_appendStr_qs("a" + QOSMPS_baseCount, bc.author);
if (bc.releaseLength != undefined)  QOSMPS_appendStr_qs("l" + QOSMPS_baseCount, bc.releaseLength);
if (bc.bitrate != undefined && bc.bitrate != NaN && bc.bitrate != "NaN")  QOSMPS_appendStr_qs("b" + QOSMPS_baseCount, bc.bitrate);
if (bc.loadTime != undefined)  QOSMPS_appendStr_qs("lt" + QOSMPS_baseCount, bc.loadTime);
if (bc.trueLength == undefined && c.baseClip.releaseLength != undefined) bc.trueLength = bc.releaseLength;
if (bc.lengthPlayed != undefined)
{
var percentPlayed;
if (bc.trueLength == -1)
{
percentPlayed = 100;//if it's streaming content, this is automatically 100
}
else
{
percentPlayed = QOSMPS_round((bc.lengthPlayed / bc.trueLength) * 100, 2);
} 
if (percentPlayed > 100) percentPlayed = 100;
if (!isNaN(percentPlayed))
{
QOSMPS_appendStr_qs("pp" + QOSMPS_baseCount, percentPlayed);
}
}
if (bc.rebufferingTime != undefined)
{
var percentRebuff = QOSMPS_round((bc.rebufferingTime / (bc.rebufferingTime + bc.lengthPlayed)) * 100, 2);
if (!isNaN(percentRebuff)) QOSMPS_appendStr_qs("pr" + QOSMPS_baseCount, percentRebuff);
}
var percentBW;
if (bc.connectionBitrate != undefined)
{
if (bc.trueBitrate == undefined && bc.bitrate != undefined) bc.trueBitrate == bc.bitrate / 1000;
percentBW = QOSMPS_round((bc.connectionBitrate / bc.trueBitrate) * 100, 2);
if (!isNaN(percentBW))
{
if (percentBW > 100) percentBW = 100;//cap it out at 100%
}
else
{
percentBW = 100;
}
}
else
{
percentBW = 100;
}
if (bc.lengthPlayed != undefined && bc.lengthPlayed > 0)//don't include unless the clip has played
{
bc.percentBW = percentBW;
QOSMPS_appendStr_qs("pb" + QOSMPS_baseCount, percentBW)
}
else
{
bc.percentBW = undefined;
}
if (bc.lengthPlayed != undefined && bc.lengthPlayed > 0)  QOSMPS_appendStr_qs("lp" + QOSMPS_baseCount, bc.lengthPlayed);
QOSMPS_baseCount++;
}

function QOSMPS_parseAggregate(plid)
{
if (plid != undefined) QOSMPS_appendStr_qs("rid" + QOSMPS_baseCount, plid);
var loadTime = QOSMPS_baseClips[0].loadTime;
var trueLength = 0;
var lengthPlayed = 0;
var percentBW = 100;
var bwLength = 0;//the length of the clips that have bandwidth data
var rebuffTime = 0;
var bwCalcArray = new Array();
//aggregate values
for (var i = 0; i < QOSMPS_baseClips.length; i++)
{
var bc = QOSMPS_baseClips[i];
if (bc.trueLength != undefined) trueLength += bc.trueLength;
if (bc.lengthPlayed != undefined)
{
if (bc.lengthPlayed > bc.trueLength) bc.lengthPlayed = bc.trueLength;//account for duration errors so pp is always <= 100;
lengthPlayed += bc.lengthPlayed;
}
if (bc.rebufferingTime != undefined) rebuffTime += bc.rebufferingTime;
if (bc.percentBW != undefined)
{
var bwObj = new Object();
bwObj.percentBW = bc.percentBW;
bwObj.trueLength = bc.trueLength;
bwCalcArray.push(bwObj);
bwLength += bc.trueLength;
}
}

//calculate the weighted bandwidth
var compositeBW = 0;
if (bwLength > 0)
{
for (var i = 0; i < bwCalcArray.length; i++)
{
var bwObj = bwCalcArray[i];
var percentTotal = bwObj.trueLength / bwLength;
compositeBW += bwObj.percentBW * percentTotal
}
}
if (compositeBW > 100) compositeBW = 100;
if (trueLength > 0) QOSMPS_appendStr_qs("l" + QOSMPS_baseCount, trueLength);
if (loadTime != undefined) QOSMPS_appendStr_qs("lt" + QOSMPS_baseCount, loadTime);
if (lengthPlayed > 0 && trueLength > 0)
{
var percentPlayed = QOSMPS_round((lengthPlayed / trueLength) * 100, 2);
if (percentPlayed > 100) percentPlayed = 100;
if (!isNaN(percentPlayed)) QOSMPS_appendStr_qs("pp" + QOSMPS_baseCount, percentPlayed);
}
if (rebuffTime > 0 && trueLength > 0)
{
var percentRebuff = QOSMPS_round((rebuffTime / (rebuffTime + lengthPlayed))*100, 2);
if (!isNaN(percentRebuff)) QOSMPS_appendStr_qs("pr" + QOSMPS_baseCount, percentRebuff);
}
if (compositeBW > 0) QOSMPS_appendStr_qs("pb" + QOSMPS_baseCount, QOSMPS_round(compositeBW, 2));
if (lengthPlayed > 0) QOSMPS_appendStr_qs("lp" + QOSMPS_baseCount, lengthPlayed);
}

function QOSMPS_appendStr_qs(name, value)
{
QOSMPS_qs += "&" + name + "=" + value;
}

function QOSMPS_sendData(qString)
{
//send the query string
var theUrl = QOSMPS_baseUrl + qString;
tpQOSSendURL(theUrl);
//reset the query string
QOSMPS_qs = ""

}

function QOSMPS_round(num, power)
{
var mult = Math.pow(10, power);
var raw = num * mult;
raw = Math.round(raw);
return raw / mult;
}



// Class: Dump
// Author: Shuns (www.netgrow.com.au/files)
// Last Updated: 10/10/06
// Version: 1.1

dump=function(object, showTypes){var dump='';var st=typeof showTypes=='undefined' ? true : showTypes;var winName='dumpWin';var browser=_dumpIdentifyBrowser();var w=760;var h=500;var leftPos=screen.width ?(screen.width-w)/ 2 : 0;var topPos=screen.height ?(screen.height-h)/ 2 : 0;var settings='height='+h+',width='+w+',top='+topPos+',left='+leftPos+',scrollbars=yes,menubar=yes,status=yes,resizable=yes';var title='Dump';var script='function tRow(s){t=s.parentNode.lastChild;tTarget(t, tSource(s));}function tTable(s){var switchToState=tSource(s);var table=s.parentNode.parentNode;for(var i=1;i < table.childNodes.length;i++){t=table.childNodes[i];if(t.style){tTarget(t, switchToState);}}}function tSource(s){if(s.style.fontStyle=="italic"||s.style.fontStyle==null){s.style.fontStyle="normal";s.title="click to collapse";return "open";}else{s.style.fontStyle="italic";s.title="click to expand";return "closed";}}function tTarget(t, switchToState){if(switchToState=="open"){t.style.display="";}else{t.style.display="none";}}';dump+=(/string|number|undefined|boolean/.test(typeof(object))||object==null)? object : recurse(object, typeof object);winName=window.open('', winName, settings);if(browser.indexOf('ie')!=-1||browser=='opera'||browser=='ie5mac'||browser=='safari'){winName.document.write('<html><head><title> '+title+' </title><script type="text/javascript">'+script+'</script><head>');winName.document.write('<body>'+dump+'</body></html>');}else{winName.document.body.innerHTML=dump;winName.document.title=title;var ffs=winName.document.createElement('script');ffs.setAttribute('type', 'text/javascript');ffs.appendChild(document.createTextNode(script));winName.document.getElementsByTagName('head')[0].appendChild(ffs);}winName.focus();function recurse(o, type){var i;var j=0;var r='';type=_dumpType(o);switch(type){case 'regexp':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>RegExp: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'date':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Date: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'function':var t=type;var a=o.toString().match(/^.*function.*?\((.*?)\)/im);var args=(a==null||typeof a[1]=='undefined'||a[1]=='')? 'none' : a[1];r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Arguments: </i></td><td'+_dumpStyles(type,'td-value')+'>'+args+'</td></tr><tr><td'+_dumpStyles('arguments','td-key')+'><i>Function: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'domelement':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Name: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeName.toLowerCase()+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Type: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeType+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Value: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeValue+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>innerHTML: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.innerHTML+'</td></tr>';j++;break;}if(/object|array/.test(type)){for(i in o){var t=_dumpType(o[i]);if(j < 1){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+'</th></tr>';j++;}if(typeof o[i]=='object' && o[i]!=null){r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else if(typeof o[i]=='function'){r+='<tr><td'+_dumpStyles(type ,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else{r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+o[i]+'</td></tr>';}}}if(j==0){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+' [empty]</th></tr>';}r+='</table>';return r;};};_dumpStyles=function(type, use){var r='';var table='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;cell-spacing:2px;';var th='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;text-align:left;color: white;padding: 5px;vertical-align :top;cursor:hand;cursor:pointer;';var td='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;vertical-align:top;padding:3px;';var thScript='onClick="tTable(this);" title="click to collapse"';var tdScript='onClick="tRow(this);" title="click to collapse"';switch(type){case 'string':case 'number':case 'boolean':case 'undefined':case 'object':switch(use){case 'table':r=' style="'+table+'background-color:#0000cc;"';break;case 'th':r=' style="'+th+'background-color:#4444cc;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccddff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'array':switch(use){case 'table':r=' style="'+table+'background-color:#006600;"';break;case 'th':r=' style="'+th+'background-color:#009900;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccffcc;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'function':switch(use){case 'table':r=' style="'+table+'background-color:#aa4400;"';break;case 'th':r=' style="'+th+'background-color:#cc6600;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#fff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'arguments':switch(use){case 'table':r=' style="'+table+'background-color:#dddddd;cell-spacing:3;"';break;case 'td-key':r=' style="'+th+'background-color:#eeeeee;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;}break;case 'regexp':switch(use){case 'table':r=' style="'+table+'background-color:#CC0000;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FF0000;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FF5757;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'date':switch(use){case 'table':r=' style="'+table+'background-color:#663399;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#9966CC;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#B266FF;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'domelement':switch(use){case 'table':r=' style="'+table+'background-color:#FFCC33;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FFD966;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FFF2CC;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;}return r;};_dumpIdentifyBrowser=function(){var agent=navigator.userAgent.toLowerCase();if (typeof window.opera != 'undefined'){return 'opera';} else if (typeof document.all != 'undefined'){if (typeof document.getElementById != 'undefined'){var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, '$1').replace(/ /, '');if(typeof document.uniqueID != 'undefined') {if (browser.indexOf('5.5') != -1){return browser.replace(/(.*5\.5).*/, '$1');}else{return browser.replace(/(.*)\..*/, '$1');}}else{return 'ie5mac';}}}else if(typeof document.getElementById != 'undefined'){if (navigator.vendor.indexOf('Apple Computer, Inc.')!=-1) {return 'safari';}else if(agent.indexOf('gecko')!=-1) {return 'mozilla';}}return false;};_dumpType=function(obj){var t=typeof(obj);if(t=='function'){var f=obj.toString();if((/^\/.*\/[gi]??[gi]??$/).test(f)){return 'regexp';}else if((/^\[object.*\]$/i).test(f)){t='object'}}if(t !='object'){return t;}switch(obj){case null:return 'null';case window:return 'window';case document:return document;case window.event:return 'event';}if(window.event &&(event.type==obj.type)){return 'event';}var c=obj.constructor;if(c !=null){switch(c){case Array:t='array';break;case Date:return 'date';case RegExp:return 'regexp';case Object:t='object';break;case ReferenceError:return 'error';default:var sc=c.toString();var m=sc.match(/\s*function(.*)\(/);if(m !=null){return 'object';}}}var nt=obj.nodeType;if(nt !=null){switch(nt){case 1:if(obj.item==null){return 'domelement';}break;case 3:return 'string';}}if(obj.toString !=null){var ex=obj.toString();var am=ex.match(/^\[object(.*)\]$/i);if(am !=null){var am=am[1];switch(am.toLowerCase()){case 'event':return 'event';case 'nodelist':case 'htmlcollection':case 'elementarray':return 'array';case 'htmldocument':return 'htmldocument';}}}return t;};

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


_xTdf = {

init:function(){
_xTdf.loadInnerNewsModuleInit();
_xTdf.loadInnerNewsflashInit();
},

loadInnerNewsflashInit:function(){
if (undefined !== window._NewsflashAjax)
if(_NewsflashAjax == 'on'){

setInterval(function(){
var _counter = $('#tdf_counter').attr('rel');
$('#tdf_counter').html( (_counter-1)+' s');
$('#tdf_counter').attr('rel', _counter-1 );
},1000*1);

$('.table_news').each(function(){
var l_nPerPage = _l_nPerPage;
var l_nPage = _l_nPage;
var dd = new Date();
var l_nCacheBreaker = dd.getMilliseconds();
//$('#'+l_sId+' .outer_news').height($('#'+l_sId+' .inner_news').height());

BaseAjax._xArgs.data = 'a=TdfNewsflashInner';
BaseAjax._xArgs.data += '&page='+l_nPage;
BaseAjax._xArgs.data += '&per_page='+l_nPerPage;
BaseAjax._xArgs.data += '&stage='+_l_nSelectedStage;
BaseAjax._xArgs.data += '&cb='+l_nCacheBreaker + Math.random();
BaseAjax._xArgs.returnDiv = '#inner_newsflash' ;
BaseAjax._xArgs.callBack = _xTdf.loadInnerNewsflashCallback();
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall(AJAX_URL);
});
}
//alert(l_nCacheBreaker + Math.random());
},

loadInnerNewsModuleInit:function(){
$('.tdf_module_news').each(function(){
var l_sId = $(this).attr('id');
var l_nCol = $(this).attr('rel')
var d = new Date()
//var l_nCacheBreaker = d.getMilliseconds() + Math.random();

//$('#'+l_sId+' .outer_news').height($('#'+l_sId+' .inner_news').height());

BaseAjax._xArgs.data = 'a=TdfNewsModuleInner';
BaseAjax._xArgs.data += '&colnum='+l_nCol;
//BaseAjax._xArgs.data += '&cb='+l_nCacheBreaker;

BaseAjax._xArgs.returnDiv = '#'+l_sId+' .hidden_news' ;
BaseAjax._xArgs.callBack = function(){_xTdf.loadInnerNewsModuleCallback(l_sId,true)};
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall(AJAX_URL);

});

},

loadInnerNewsflashCallback:function(){
setTimeout(function(){
$('#tdf_counter').html(_l_nRefreshPage+' s');
$('#tdf_counter').attr('rel', _l_nRefreshPage );
$('#outer_newsflash').animate({
height:$('#inner_newsflash').height()
},1000,
function(){
$('#outer_newsflash').height('auto')
}
);
},200);

setTimeout(function(){
l_nPerPage = _l_nPerPage;
l_nPage = _l_nPage;
var l = new Date();
BaseAjax._xArgs.data = 'a=TdfNewsflashInner';
BaseAjax._xArgs.data += '&page='+l_nPage;
BaseAjax._xArgs.data += '&per_page='+l_nPerPage;
BaseAjax._xArgs.data += '&stage='+_l_nSelectedStage;
BaseAjax._xArgs.data += '&cb='+ l.getMilliseconds() + Math.random();
BaseAjax._xArgs.returnDiv = '#inner_newsflash';
BaseAjax._xArgs.callBack = _xTdf.loadInnerNewsflashCallback();
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall(AJAX_URL);
},1000*_l_nRefreshPage);  // in 10 sec for now
},

loadInnerNewsModuleCallback:function(p_sId,p_bIsInit){
l_bAnimate = true
if(p_bIsInit!==true){
var l_nNewTimestamp = $.trim($('#'+p_sId+' .outer_news .timestamp').html());
var l_nOldTimestamp = $.trim($('#'+p_sId+' .hidden_news .timestamp').html());

if(l_nNewTimestamp == l_nOldTimestamp){
var l_bAnimate = false;
}
}

if(l_bAnimate){
$('#'+p_sId+' .inner_news').hide();
$('#'+p_sId+' .inner_news').html($('#'+p_sId+' .hidden_news').html());
$('#'+p_sId+' .inner_news').fadeIn(250,function(){
$('#'+p_sId+' .outer_news').animate({
height:$('#'+p_sId+' .inner_news').height()
},1000,
function(){
$('#'+p_sId+' .outer_news').height('auto')
}
);
})
}else{
$('#'+p_sId+' .outer_news').height('auto')
}

setTimeout(function(){
$('#'+p_sId+' .outer_news').height($('#'+p_sId+' .outer_news').height())
var l_nCol = $('#'+p_sId).attr('rel')
BaseAjax._xArgs.data = 'a=TdfNewsModuleInner';
BaseAjax._xArgs.data += '&colnum='+l_nCol;
var z = new Date()
BaseAjax._xArgs.data += '&cb='+ z.getMilliseconds() + Math.random();
BaseAjax._xArgs.returnDiv = '#'+p_sId+' .hidden_news' ;
BaseAjax._xArgs.callBack = _xTdf.loadInnerNewsModuleCallback(p_sId);
BaseAjax._xArgs.requestType = "GET";
BaseAjax.makeAjaxCall(AJAX_URL);

},1000*60);  // in 1 minute
},

toggleText:function(element,block){
if($(element).html() == 'More' ){
if(block == 0){
$(element).parents(".subhead").find(".hid").show();
$(element).parents(".subhead").find(".ellipsis").html('');
}else{
$(element).parents(".html").find(".hid").show();
$(element).parents(".html").find(".ellipsis").html('');
}
$(element).html('Close');
}else{
if(block == 0){
$(element).parents(".subhead").find(".hid").hide();
$(element).parents(".subhead").find(".ellipsis").html('...');
}else{
$(element).parents(".html").find(".hid").hide();
$(element).parents(".html").find(".ellipsis").html('...');
}
$(element).html('More');
}
}

}

 _xDisplay = {
displayComments:function(response, p_sIsTypeYesNo){
 var l_sPLK_Final_Template = "";
 var l_sPLKYesTemplate = '';
//get type of comment, yes or no.
 var p_nType = p_sIsTypeYesNo.split(g_sDelimiter);
 //iterate to all comments received in the response
 //Pickup Appropriate div, either yes or no
if(p_nType[2] == 1){
  l_sPLKYesTemplate = $('#plk_comments_yes_template').html();
}
if(p_nType[2] == 0){
  l_sPLKYesTemplate = $('#plk_comments_no_template').html();
    }

//Check if comments exist, addup comments.
if(document._xPluckIsNotPagination){
    var l_nTotalComments = parseInt(document._xPluckCommentCount) + parseInt(response.NumberOfComments);
  document._xPluckCommentCount = l_nTotalComments;
$('#plck-comment-count').removeClass("plck-comment-count-class").addClass("commentcount");
$('#plck-comment-count').html(l_nTotalComments);

}
 
var i = 0;
for(i = 0; i < response.Comments.length; i++){
  
  var l_sTemplate = '';
  var l_sTemplate = l_sPLKYesTemplate.toString();
  //get commentData object
  var commentData = response.Comments[i];
  //Additional css to first comment only
  if(i == 0){
 l_sTemplate = l_sTemplate.replace(/~extraclass~/, "comment_first");
   }
   if(i > 0){
 l_sTemplate = l_sTemplate.replace(/~extraclass~/, "");
   }
   
    l_sTemplate = l_sTemplate.replace(/~fire-up-id~/, "fireup-"+i);
   //break date time to place in appropriate html
   var l_sPostDateTime = commentData.PostedAtTime;
   var l_aPostDateTime = l_sPostDateTime.split(" ");
   
   l_sTemplate = l_sTemplate.replace(/~byline~/,"By <a href=" + commentData.Author.PersonaUrl + ">" + commentData.Author.DisplayName + "</a> @ <span>" + l_aPostDateTime[0] + "</span> at " + l_aPostDateTime[1] +"" + l_aPostDateTime[2].toLowerCase() );
   l_sTemplate = l_sTemplate.replace(/~comment~/,commentData.CommentBody);
   
   //Check if user has already flagged
   if(commentData.CurrentUserHasReportedAbuse == 'True'){
 l_sTemplate = l_sTemplate.replace(/~extraclass-flag-selected~/, "sprite_selected");
 l_sTemplate = l_sTemplate.replace(/~flag-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");

}else{
  l_sTemplate = l_sTemplate.replace(/~extraclass-flag-selected~/, "");
  l_sTemplate = l_sTemplate.replace(/~flag-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:reportAbuse(\"" + commentData.CommentKey.Key + "\", \"comment\", \"comment\", \"comment\", this);'/>");

   }
   
   //check if user has already recommended
   if(commentData.CurrentUserHasRecommended == 'True'){
 l_sTemplate = l_sTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sTemplate = l_sTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
  
   }else{
   l_sTemplate = l_sTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sTemplate = l_sTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + commentData.CommentKey.Key + "\", \"comment\", this);'/>");
   }
   
   
   //append current changes to final template
   l_sPLK_Final_Template += l_sTemplate;
  
}
//select appropriate div and place final template data
   
if(p_nType[2] == 1){
$('#plk_comments_yes_template_final').html(l_sPLK_Final_Template);
}
if(p_nType[2] == 0){
$('#plk_comments_no_template_final').html(l_sPLK_Final_Template);
}

//pagination for comments
if(response.NumberOfComments > 2){
if(parseInt(response.NumberOfComments) > parseInt(response.NumberPerPage)){
 l_aPaginationInfo = _xPagination.modComments(response.OnPage, response.NumberOfComments, response.NumberPerPage, response.ArticleKey.Key, "getComments");
       
l_sPaginationTemplate = $('#plck_pagi_'+p_nType[2]).html();
  l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-left~/,"<div class= 'mod_pagination_left sprite " + l_aPaginationInfo['left_class'] + "'><a " + l_aPaginationInfo['left_string'] +  "><span>Left</span></a></div>");               
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-right~/,"<div class= 'mod_pagination_right sprite  " + l_aPaginationInfo['right_class'] + "'><a " + l_aPaginationInfo['right_string'] + "><span>Right</span></a></div>");
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~page-numbers~/, "" + l_aPaginationInfo['item_display'] + " of <b> " + l_aPaginationInfo['total_count'] + "</b>");
$('#plck_pagi_final_'+p_nType[2]).html(l_sPaginationTemplate);
}

}

},

BeTheFirstToComment:function(response, p_sIsTypeYesNo){
var p_nType = p_sIsTypeYesNo.split(g_sDelimiter);
if(p_nType[2] == 1){
$('#plk_comments_yes_template_final').html('<a href="#addcomment" class="no_comments"></a>');
}
if(p_nType[2] == 0){
$('#plk_comments_no_template_final').html('<a href="#addcomment" class="no_comments"></a>');
}

},


displayRecentFeedModule:function(feedActivity){
//initialize templates
var l_sPLKBaseTemplate = '';
var l_sPLKForumPostTemplate = '';
    var l_sPLKBlogPostTemplate = '';
    var l_sPLKForumDiscussionTemplate = '';
var l_sPLKPhotoTemplate = '';
var l_sVideoTemplate = '';
    var l_sPLK_Final_Template = '';
//Pickup base template
l_sPLKBaseTemplate = $('#plck_feeds_base_template').html();
//check for number of activities
var feedIteration = feedActivity.NumberOfActivities
   //handle special case where number of activities per page is greater than the number of activities.
  if((feedActivity.NumberPerPage) < (feedActivity.NumberOfActivities)){
//alert("no per page is less than no of activities");
var feedIteration = feedActivity.NumberPerPage;    
   }


   for (var i = 0; i < feedActivity.GroupActivities.length; i++) {
    //get all group activities from feeds
var activity = feedActivity.GroupActivities[i];
//get base template for each content type
var l_sTemplate = '';
  var l_sTemplate = l_sPLKBaseTemplate.toString();
//replace url in image
l_sTemplate = l_sTemplate.replace(/plck-base-image/, activity.LiteUserResponse.ImageUrl);
//replace alt in image
l_sTemplate = l_sTemplate.replace(/~base-image-alt~/, activity.LiteUserResponse.DisplayName);
//accomodate html for different activity types
//calculate time uploaded
l_sTimeUploaded = getActivityTime(activity.ActivityDate); 
switch(activity.ActivityType){


case 'ForumPost':
var l_aTextInfo = { c:'000000',type:'b','bg':'ffffff',tran:true,s:20,t: '"'+activity.Abstract+'"', w:410, 'bb':'9px' }
l_sForumQuote = makeCustomImage(l_aTextInfo);
l_sActivityTitle = activity.Title.replace("Re:", "");
l_sPLKForumPostTemplate = $("#plck_feeds_forum_post_template").html();
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/plck-forum-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/~forum-owner-name~/, activity.LiteUserResponse.DisplayName);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/~forum-activity~/, activity.ActivityAction);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/plck-forum-group-url/, "");
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/~forum-group-title~/, l_sActivityTitle);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/~forum-time~/, l_sTimeUploaded);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/plck-forum-quote-image-text/, l_sForumQuote);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/plck-forum-quote-text/, activity.Abstract);
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/plck-forum-url/, "");//activity.TargetKey
l_sPLKForumPostTemplate = l_sPLKForumPostTemplate.replace(/~forum-title~/, l_sActivityTitle);
l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKForumPostTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'BlogPost':
var l_aTextInfo = { c:'000000',type:'b','bg':'ffffff',tran:true,s:20,t: '"'+activity.Abstract+'"', w:410, 'bb':'9px' }
l_sBlogQuote = makeCustomImage(l_aTextInfo);
l_sPLKBlogPostTemplate = $("#plck_feeds_blog_post_template").html();
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~blog-owner-name~/, activity.LiteUserResponse.DisplayName);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~blog-activity~/, activity.ActivityAction);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-group-url/, "");
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~blog-group-title~/, activity.Title);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~blog-time~/, l_sTimeUploaded);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-quote-image-text/,l_sBlogQuote);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-quote-text/,activity.Abstract);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~blog-title~/, activity.Title);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-url/, "/community/blog/"+activity.TargetKey+"/");

l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKBlogPostTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'ForumDiscussion':
l_sPLKForumDiscussionTemplate = $("#plck_feeds_discussion_template").html();
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/plck-discussion-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-owner-display-name~/, activity.LiteUserResponse.DisplayName);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-activity~/, activity.ActivityAction);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/plck-discussion-group-url/, "");
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-group-title~/, activity.Title);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-time~/, l_sTimeUploaded);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/plck-discussion-url/, "");
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-title~/, activity.Title);
l_sPLKForumDiscussionTemplate = l_sPLKForumDiscussionTemplate.replace(/~discussion-description~/, activity.Abstract);
l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKForumDiscussionTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'Photo':
   l_sPLKPhotoTemplate = $("#plck_feeds_photo_template").html();
//_xCore.getPhotoDetail(activity.TargetKey);
//get gallery description
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-owner-display-name~/, activity.LiteUserResponse.DisplayName);
        l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-activity~/, activity.ActivityAction);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-group-url/, "");
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-group-title~/, activity.Title);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-time~/, l_sTimeUploaded);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-thumbnail/, activity.Image.Medium);
        l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-url-tnholder/, "/community/photo/"+activity.TargetKey+"/");
        l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-url/, "/community/photo/"+activity.TargetKey+"/");
        l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-title~/, activity.Title );
        l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-description~/, activity.Abstract);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photos-in-gallery~/, "");
l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKPhotoTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'Video':
l_sPLKVideoTemplate = $("#plck_feeds_video_template").html();
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-owner-display-name~/, activity.LiteUserResponse.DisplayName);
        l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-activity~/, activity.ActivityAction);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-group-url/, "");
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-group-title~/, activity.Title);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-time~/, l_sTimeUploaded);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-thumbnail/, activity.Image.Small);
        l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-url-tnholder/, "/community/video/"+activity.TargetKey+"/");
        l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-url/, "/community/video/"+activity.TargetKey+"/");
        l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-title~/, activity.Title );
        l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-description~/, activity.Abstract);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-duration~/, "");
l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKVideoTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'Event':
    l_sEventTime = _xUtils.displayModifiedDate(activity.ActivityDate);
l_sPLKEventTemplate = $("#plck_feeds_events_template").html();
l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/plck-events-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/~events-owner-name~/, activity.LiteUserResponse.DisplayName);
        l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/~events-activity~/, activity.ActivityAction);
l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/~events-time~/, l_sTimeUploaded);
l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/~events-title~/, activity.Title);
    l_sPLKEventTemplate = l_sPLKEventTemplate.replace(/~events-description~/, activity.Abstract);
l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKEventTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
case 'Comment':
    l_sEventTime = _xUtils.displayModifiedDate(activity.ActivityDate);
l_sPLKCommentTemplate = $("#plck_feeds_comments_template").html();
l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/plck-comments-owner-url/, activity.LiteUserResponse.PersonaUrl);
l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/~comments-owner-name~/, activity.LiteUserResponse.DisplayName);
        l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/~comments-activity~/, activity.ActivityAction);
l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/~comments-time~/, l_sTimeUploaded);
l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/comments-description/, activity.Abstract);
l_sPLKCommentTemplate = l_sPLKCommentTemplate.replace(/~comments-title~/, activity.Title);

l_sTemplate = l_sTemplate.replace(/~feeds-template-type~/, l_sPLKCommentTemplate);
l_sPLK_Final_Template += l_sTemplate;
break;
}
}
 
$('#plck_feeds_template_final').html(l_sPLK_Final_Template); 

if((parseInt(feedActivity.NumberOfActivities)) > (parseInt(feedActivity.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNumRecentFeed(feedActivity.OnPage, feedActivity.NumberOfActivities, feedActivity.NumberPerPage, feedActivity.CommunityGroupKey.Key, "_xCommunity.getRecentActivityFeedModule", 10);
        $('#plck-pagination-final').html(l_sPaginationTemplate);
     }

}, 

displayNoContentImage: function(l_sDivId){
  
  $('#'+l_sDivId).addClass("no_content");
  switch(l_sDivId){
   case 'home_no_content':
     $('#plck-no-content-links').css("padding-left", "28px").html(
                                                          '<div class="be_first_photo sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'upload\',\'image\')"><span>Add Your Photos!</span></a></div>'+
                          '<div class="be_first_video sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'upload\',\'video\')"><span>Add Your Videos!</span></a></div>'+
                                                          '<div class="be_first_blog sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'create\',\'blog\')"><span>Create Your Blog!</span></a></div>'+
                                                          '<div class="be_first_event sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'create\',\'event\')"><span>Create an Event!</span></a></div>');
   break;
   case 'plck_picture_page_template_final':
       $('#plck-no-content-links').css("padding-left", "240px").html('<div class="be_first_photo sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'upload\',\'image\')"><span>Add Your Photos!</span></a></div>');
   break;
   case 'plck_video_page_template_final':
       $('#plck-no-content-links').css("padding-left", "240px").html('<div class="be_first_video sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'upload\',\'video\')"><span>Add Your Videos!</span></a></div>');
   break;
   case 'plck_events_page_template_upcoming_events_final':
       $('#plck-no-content-links').css("padding-left", "240px").html('<div class="be_first_event sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'create\',\'event\')"><span>Create an Event!</span></a></div>');
   break;
   case 'plck_blog_page_template_final':
       $('#plck-no-content-links').css("padding-left", "240px").html('<div class="be_first_blog sprite"><a href="javascript:void(0)" onclick="_xTruebox.makePopup(\'create\',\'blog\')"><span>Create Your Blog!</span></a></div>');
   break;
   
  }
  
},


displayCommunityTabModule:function(l_sImageURL, l_sGroupTitle, l_sGroupDescription, l_sCommunityKey, l_sMembershipTier){
//imagify group title:
var l_aTextInfo = { c:'FFFFFF',type:'b','bg':'0F0F0F',tran:true,s:20,t: l_sGroupTitle, w:410, 'bb':'9px' }
l_sGroupTitleImage = makeCustomImage(l_aTextInfo);
//get grouptabmodule template
l_sPLKTabModuleTemplate = $('#plck_groups_tab_module_template').html();
//replace with data.
l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/plck-groups-hero-img/, l_sImageURL.replace("Small", "Large"));
l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/plck-generated-image-title/, l_sGroupTitleImage);
l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/plck-group-title/, l_sGroupTitle);
    l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/~plck-group-description~/, l_sGroupDescription);
//jam into html


if(l_sMembershipTier == "NonMember"){
//get cookie, if cookie exists, get userkey
    var l_sCurrentCookie = _xValidate.getCookie("at");
if(l_sCurrentCookie){
    //get userkey from cookie
    l_aCookieInfo = l_sCurrentCookie.split("%26");
l_aUserKey = l_aCookieInfo[0].split("=");
l_sUserKeyInfo = l_aUserKey[1];
l_sUserKeySplit = l_sUserKeyInfo.split("%3D");
l_sUserKey = l_sUserKeySplit[1];

l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/~plck-join-button-div~/, "<div id = 'plck_jointhisgroup' class = 'sprite btn_jointhisgroup'><a onclick= 'javascript:_xCore.requestCommunityGroupMembership(\"" + l_sCommunityKey + "\", \"" + l_sUserKey + "\");'><span>Join This Group</span></a></div>");
    } else{
        l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/~plck-join-button-div~/,"");
    }

}else{
     l_sPLKTabModuleTemplate = l_sPLKTabModuleTemplate.replace(/~plck-join-button-div~/,"");
}

$('#plck_groups_tab_module_template_final').html(l_sPLKTabModuleTemplate);

                    },

displayCommunityBadgeModule:function(l_nMemberCount, l_sType){
                var l_sPLKBadgeModuleTemplate = '';
var l_sGroupBadgeCount = '';
//get badge template:
l_sPLKBadgeModuleTemplate = $('#plck-badge-count-template').html();
l_aMemberCount = l_nMemberCount.split("");
//l_sGroupBadgeCount = l_sPLKBadgeModuleTemplate.replace(/~group-badge-count-image~/, "<img src='/image/groups_badge_num_" + l_aMemberCount[i] + ".gif?v=213' alt='"  + l_aMemberCount[i] + "' />"
if(l_aMemberCount.length == 0){
       l_sGroupBadgeCount += "<img src='/image/groups_badge_num_0.gif?v=213' alt='0' />";
}else{
for(i = 0; i < l_aMemberCount.length; i++){
    l_sGroupBadgeCount += "<img src='/image/groups_badge_num_" + l_aMemberCount[i] + ".gif?v=213' alt='"  + l_aMemberCount[i] + "' />";
}
}
l_sPLKBadgeModuleTemplate = l_sPLKBadgeModuleTemplate.replace(/~group-badge-count-image~/, l_sGroupBadgeCount);


$('#plck-badge-count-template-final').html(l_sPLKBadgeModuleTemplate);

}, 


displayGroupPreviousEvents: function(response){
var l_sPLKEventsPageTemplate = '';
var l_sPLKFinalEventsPageTemplate = '';
var l_sPaginationTemplate = '';

l_sPLKTitleEventsPageTemplate = $('#plck_events_page_template_title').html();
l_sPLKTitleEventsPageTemplate = l_sPLKTitleEventsPageTemplate.replace(/~events-title~/, "<div class='hr'></div><div class='gap40'></div><div class='txt_recentevents txt'>Recent Events</div>");
$('#plck_events_page_template_upcoming_events_title_final').html(l_sPLKTitleEventsPageTemplate);

//loop thru response
for(i = 0; i < response.Events.length; i++){
 var eventData = response.Events[i];
//alert("start date"+

//get events template
l_sPLKEventsPageTemplate = $('#plck_events_page_template').html();
//replace events template with pluck data
    l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-base-image/, eventData.Author.ImageUrl);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~base-image-alt~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-events-owner-url/, "");
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-owner-name~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-owner-name~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-events-group-url/, "");
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-group-title~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-title~/, eventData.Title);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-start-date~/, eventData.StartDate_UTC);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-end-date~/, eventData.EndDate_UTC);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-description~/, eventData.Description);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~event-location~/, eventData.Location);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/event-bookmark-url/, eventData.BookmarkUrl);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~event-bookmark-name~/, eventData.BookmarkName);

l_sPLKFinalEventsPageTemplate += l_sPLKEventsPageTemplate;
}
//jam it into html
$('#plck_events_page_template_upcoming_events_final').html('');
$('#plck_events_page_template_upcoming_events_final').html(l_sPLKFinalEventsPageTemplate);

if((parseInt(response.NumberOfEvents)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNum(response.OnPage, response.NumberOfEvents, response.NumberPerPage, response.EventSetKey.Key, "_xCommunityEvents.getRecentEventsModule", 10);
        $('#plck-pagination-final-upcoming-events').html(l_sPaginationTemplate);
     } else{
        $('#plck-pagination-final-upcoming-events').html('');
     }
 
},

displayGroupUpcomingEvents: function(response){
    var l_sPLKEventsPageTemplate = '';
var l_sPLKFinalEventsPageTemplate = '';
var l_sPaginationTemplate = '';

l_sPLKTitleEventsPageTemplate = $('#plck_events_page_template_title').html();
l_sPLKTitleEventsPageTemplate = l_sPLKTitleEventsPageTemplate.replace(/~events-title~/, "<div class='hr'></div><div class='gap40'></div><div class='txt_upcomingevents txt'>Upcoming Events</div>");
$('#plck_events_page_template_upcoming_events_title_final').html(l_sPLKTitleEventsPageTemplate);

//loop thru response
for(i = 0; i < response.Events.length; i++){
 var eventData = response.Events[i];
//get events template
l_sPLKEventsPageTemplate = $('#plck_events_page_template').html();
//replace events template with pluck data
    l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-base-image/, eventData.Author.ImageUrl);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~base-image-alt~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-events-owner-url/, "");
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-owner-name~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-owner-name~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/plck-events-group-url/, "");
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-group-title~/, eventData.Author.DisplayName);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-title~/, eventData.Title);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-start-date~/, eventData.StartDate_UTC);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-end-date~/, eventData.EndDate_UTC);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~events-description~/, eventData.Description);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~event-location~/, eventData.Location);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/event-bookmark-url/, eventData.BookmarkUrl);
l_sPLKEventsPageTemplate = l_sPLKEventsPageTemplate.replace(/~event-bookmark-name~/, eventData.BookmarkName);

l_sPLKFinalEventsPageTemplate += l_sPLKEventsPageTemplate;
}

//jam it into html
    $('#plck_events_page_template_upcoming_events_final').html('');
$('#plck_events_page_template_upcoming_events_final').html(l_sPLKFinalEventsPageTemplate);

if((parseInt(response.NumberOfEvents)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNum(response.OnPage, response.NumberOfEvents, response.NumberPerPage, response.EventSetKey.Key, "_xCommunityEvents.getUpcomingEventsModule", 10);
        $('#plck-pagination-final-upcoming-events').html(l_sPaginationTemplate);
     }else{
        $('#plck-pagination-final-upcoming-events').html('');
     }
 
},

displayCommunityGroupPictures: function(response){
var l_sPLKPicturesTemplate = '';
var l_sPLKFinalPicturesTemplate = '';

for(i = 0; i < response.Photos.length; i++){
  var photoData = response.Photos[i];
  //get picture tamplate
  l_sPLKPicturesTemplate = $('#plck_picture_page_template').html();
          //replace with pluck data
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/plck-picture-tn/, photoData.Image.Medium);
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/plck-picture-alt-title/, photoData.Title);
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/~plck-picture-title~/, photoData.Title);
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/plck-picture-detail-url/, "/community/photo/"+photoData.PhotoKey.Key+"/");
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/plck-photo-tn-url/, "/community/photo/"+photoData.PhotoKey.Key+"/");
  l_sPLKPicturesTemplate = l_sPLKPicturesTemplate.replace(/~plck-picture-timestamp~/, photoData.CreatedOn);
  l_sPLKFinalPicturesTemplate += l_sPLKPicturesTemplate;
}

$('#plck_picture_page_template_final').html(l_sPLKFinalPicturesTemplate);

if((parseInt(response.NumberOfPhotos)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNum(response.OnPage, response.NumberOfPhotos, response.NumberPerPage, response.GalleryKey.Key, "_xCommunityPhotos.getPhotosModule", 10);
        $('#plck-pagination-final').html(l_sPaginationTemplate);
}
},

displayCommunityGroupVideos: function(response){
           var l_sPLKVideosTemplate = '';
   var l_sPLKFinalVideosTemplate = '';
   
   for(i = 0; i < response.Videos.length; i++){
var videoData = response.Videos[i];
var l_sVideoCreated = videoData.CreatedOn;
var l_aVideoTimeStamp = l_sVideoCreated.split(" ");
var l_sVideoDate = l_aVideoTimeStamp[0];
//get videos template
 l_sPLKVideosTemplate = $('#plck_video_page_template').html();
 //replace with pluck data:
 l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/plck-video-tn/, videoData.VideoThumbnail);
 l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/plck-video-alt-title/, videoData.Title);
   l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/~plck-video-title~/, videoData.Title);
 l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/plck-video-detail-url/, "/community/video/"+videoData.VideoKey.Key+"/");
   l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/video-tn-url/, "/community/video/"+videoData.VideoKey.Key+"/");
   l_sPLKVideosTemplate = l_sPLKVideosTemplate.replace(/~plck-video-timestamp~/, l_sVideoDate);
 l_sPLKFinalVideosTemplate += l_sPLKVideosTemplate;
   }
   
   $('#plck_video_page_template_final').html(l_sPLKFinalVideosTemplate);
   
if((parseInt(response.NumberOfVideos)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNum(response.OnPage, response.NumberOfVideos, response.NumberPerPage, response.GalleryKey.Key, "_xCommunityVideos.getVideosModule", 10);
        $('#plck-pagination-final').html(l_sPaginationTemplate);
}
}, 


displayCommunityGroupBlogs: function(response){
        var l_sPLKBlogsTemplate = '';
    var l_sPLKFinalBlogsTemplate = '';

  for(i = 0; i < response.BlogPosts.length; i++){
     
     var blogData = response.BlogPosts[i];
   l_sTimeUploaded = getActivityTime(blogData.PostDate);
                                       l_sPLKBlogsTemplate = $('#plck_blog_page_template').html();
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-title~/, blogData.PostTitle);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-blog-url/, "/community/blog/"+blogData.BlogPostKey.Key+"/");
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-description~/, blogData.PostBody);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-author~/, blogData.PostAuthor.DisplayName);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-url/, blogData.PostAuthor.ImageUrl);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-persona-url/, blogData.PostAuthor.PersonaUrl);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-display-name/, blogData.PostAuthor.DisplayName);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~plck-blog-post-date~/, l_sTimeUploaded);
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~plck-blog-tags~/, blogData.PostTags);
   //Number of comments will have to be pulled from the article comments as comments for any content type are tied to an article.
   //l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~plck-blog-number-of-comments~/, blogData.NumberOfComments);
   if(blogData.CurrentUserHasRecommended == 'True'){
 l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
  }else{
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + blogData.BlogPostKey.Key + "\", \"blog-post\", this);'/>");
   }
   
   l_sPLKFinalBlogsTemplate += l_sPLKBlogsTemplate;
  }
  
  $('#plck_blog_page_template_final').html(l_sPLKFinalBlogsTemplate);
  
  if((parseInt(response.NumberOfBlogPosts)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNum(response.OnPage, response.NumberOfBlogPosts, response.NumberPerPage, response.BlogKey.Key, "_xCommunityBlogs.getBlogsModule", 10);
        $('#plck-pagination-final').html(l_sPaginationTemplate);
 }
},


displayCommunityGroupPageAggregate: function(response){
 var l_sPLKGroupAggregateTemplate = '';
 var l_sPLKFinalGroupAggregateTemplate = '';
 

for(i = 0; i < response.CommunityGroups.length; i++){
 var groupData = response.CommunityGroups[i];
 var groupTitle = groupData.Title;
 if(groupTitle.length > 30){
      groupTitle = groupTitle.substring(0, 300);
  groupTitle = groupTitle.replace(/\w+$/, '');
  groupTitle = groupTitle + "...";
 }
 var groupDescription = groupData.Description;
 if(groupDescription.length > 300){
      groupDescription = groupDescription.substring(0, 300);
  groupDescription = groupDescription.replace(/\w+$/, '');
  groupDescription = groupDescription + "...";
 }

 var l_sSmallAvatarImage = groupData.AvatarImageUrl;
 var l_sMediumAvatarImage = l_sSmallAvatarImage.replace("Small", "Medium"); 
 var l_sCreatedDate = groupData.CreatedDate.split(" ");
 var l_sEstablished = l_sCreatedDate[0]; 
 
 l_sPLKGroupAggregateTemplate = $('#plck_group_aggregate_template').html();
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/plck-group-aggregate-link/, "/community/group/" + groupData.CommunityGroupKey.Key + "/");
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/plck-group-aggregate-link-title/, "/community/group/" + groupData.CommunityGroupKey.Key + "/");
 l_sPLKGroupAggregateTemplate =  l_sPLKGroupAggregateTemplate.replace(/plck-group-aggregate-image/, l_sMediumAvatarImage);
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~plck-group-aggregate-title~/, groupTitle);
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/plck-group-aggregate-title/, groupTitle);
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~plck-group-aggregate-description~/, groupDescription);
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~plck-group-aggregate-fire-count~/, groupData.NumberOfRecommendations);
 l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~plck-group-aggregate-established~/, l_sEstablished);
 
 if((i % 2) == 0){
    l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~div-class-clear~/, ""); 
 }else{
    l_sPLKGroupAggregateTemplate = l_sPLKGroupAggregateTemplate.replace(/~div-class-clear~/, '<div class = "clear"></div>');
 }
 
 l_sPLKFinalGroupAggregateTemplate += l_sPLKGroupAggregateTemplate; 
}
l_sPLKFinalGroupAggregateTemplate += '<div class="clear"></div>';
$('#plck-group-aggregate-template-final').css('height','auto');
$('#plck-group-aggregate-template-final').html(l_sPLKFinalGroupAggregateTemplate);

 if((parseInt(response.NumberOfCommunityGroups)) > (parseInt(response.NumberPerPage))){
        l_sPaginationTemplate = _xPagination.tallNumAggregate(response.NumberOfCommunityGroups, response.NumberPerPage, response.OnPage, "All", response.Sort, "_xCommunity.getGroupPageAggregateModule");
        $('#plck-pagination-final').html(l_sPaginationTemplate);
}


},

displayUserActivity: function(response, l_sDivId){
   var l_nVideos = 0;
   var l_nPhotos = 0;
   var l_nComments = 0;
   var l_nBlogPosts = 0;
   var l_nDiscussions = 0;
   
   for(var i = 0; i < response.length; i ++){
      if(response[i].Video){
   l_nVideos += 1;
   }
   if(response[i].Photo){
   l_nPhotos += 1;
   }
   if(response[i].BlogPosts){
   l_nBlogPosts += 1;
   }
   if(response[i].Comments){
   l_nComments += 1;
   }
   if(response[i].Discussions){
   l_nDiscussions += 1;
   }
}
   
        l_sRecentActivityTemplate =   
"<div class='txtholder' style='float:right'>"+
"<b>Recent Activity</b>"+
"<p>"+l_nVideos+" Videos | "+l_nPhotos+" Photos | "+l_nBlogPosts+" Posts</p>"+
"<p>"+l_nComments+" Comments | "+l_nDiscussions+" Discussions</p>"+
 "</div>";
 
 $('#'+l_sDivId).html(l_sRecentActivityTemplate);

},
 


 displayDiscoverContentGroupLandingModule: function(discoveredContent){
var p_aContentType = new Array("PublicVideo", "BlogPost", "PublicPhoto", "CommunityGroup" , "Persona", "Discussion");

for(var x = 0; x < discoveredContent.Responses.length; x++){
  var init_response = discoveredContent.Responses[x];
var init_discoveredResponse = init_response.DiscoverContentAction.DiscoveredContent;
var l_sStyleWidth = init_discoveredResponse.length*208;
   
    switch(p_aContentType[x]){

case "PublicVideo":
        $('#video_reel_inner').css('width', l_sStyleWidth); 
break;
case "BlogPost":
        $('#blogposts_reel_inner').css('width', init_discoveredResponse.length*600); 
break;
case "PublicPhoto":
        //TODO: Vishal: figure out why the width calculation is not accurate for photos
$('#photo_reel_inner').css('width', (l_sStyleWidth + 208)); 
break;
case "CommunityGroup":
        $('#group_reel_inner').css('width', l_sStyleWidth); 
break;
case "Persona":
        $('#member_reel_inner').css('width', l_sStyleWidth); 
break;
case "Discussion":
         $('#discussion_reel_inner').css('width', l_sStyleWidth); 
break;

}
 

    }


    for(var i = 0; i < discoveredContent.Responses.length; i++){
   var response = discoveredContent.Responses[i];
var discoveredResponse = response.DiscoverContentAction.DiscoveredContent;
   
   if(discoveredResponse.length != 0){
   switch(p_aContentType[i]){
   case "PublicVideo":
   
$('#plck-videos-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,3,'videos' ) )

var l_sPLK_Final_Video_Template = '';
for(var j = 0; j < discoveredResponse.length; j++){
 if(discoveredResponse[j].AssociatedCommunityGroupKey){ 
var l_sPLKVideoTemplate = '';
l_sTimeUploaded = getActivityTime(discoveredResponse[j].CreatedOn);
l_sPLKVideoTemplate = $("#plck_landing_video_holder_template").html();
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-set-width/, discoveredResponse.length);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-holder-url/, "/community/video/" +discoveredResponse[j].VideoKey.Key+"/");
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-holder-url-title/, "/community/video/" +discoveredResponse[j].VideoKey.Key+"/");
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-title/, discoveredResponse[j].Title);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-title-alt/, discoveredResponse[j].Title);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~plk-video-title~/, discoveredResponse[j].Title);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/plck-video-thumbnail/, discoveredResponse[j].VideoThumbnail);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/video-author-url/, discoveredResponse[j].Author.PersonaUrl);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-author-display-name~/, discoveredResponse[j].Author.DisplayName);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/~video-created-on~/, l_sTimeUploaded);
l_sPLKVideoTemplate = l_sPLKVideoTemplate.replace(/video-group-url/, "/community/group/" +discoveredResponse[j].AssociatedCommunityGroupKey.Key+"/");
l_sPLK_Final_Video_Template += l_sPLKVideoTemplate;
 }
}

$('#plck_landing_video_holder_template_final').html(l_sPLK_Final_Video_Template);


   break;
   case "BlogPost":

$('#plck-blog-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,1,'blog' ) )
   var l_sPLK_Final_BlogPost_Template = '';
   for(var j = 0; j < discoveredResponse.length; j++){
      if(discoveredResponse[j].AssociatedCommunityGroupKey){
var l_sPLKBlogPostTemplate = '';
l_sPLKBlogPostTemplate = $("#plck_landing_blogpost_holder_template").html();
l_sTimeUploaded = getActivityTime(discoveredResponse[j].PostDate);

 var l_sAbstractText = discoveredResponse[j].PostBody;
 if(l_sAbstractText.length > 150){
  l_sAbstractText = l_sAbstractText.substring(0, 150);
  l_sAbstractText = l_sAbstractText.replace(/\w+$/, '');
  l_sAbstractText = l_sAbstractText + "...";
 }

var l_aTextInfo = { c:'666666',type:'b','bg':'0F0F0F',tran:true,s:20,t: '"'+l_sAbstractText+'"', w:600, 'bb':'9px'}
l_sAbstractImage = makeCustomImage(l_aTextInfo);

l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-image-url/, l_sAbstractImage);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-abstract-text/, discoveredResponse[j].PostBody);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blogpost-author-url/, discoveredResponse[j].PostAuthor.PersonaUrl);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blog-post-user-avatar-img-url/, discoveredResponse[j].PostAuthor.ImageUrl);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~plck-blogpost-author-name~/, discoveredResponse[j].PostAuthor.DisplayName);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~plck-blogpost-title~/, discoveredResponse[j].PostTitle);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/plck-blogpost-url/, discoveredResponse[j].Url);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/~plck-time-posted~/, l_sTimeUploaded);
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/blog-post-url/, "/community/blog/"+discoveredResponse[j].BlogPostKey.Key+"/");
l_sPLKBlogPostTemplate = l_sPLKBlogPostTemplate.replace(/blog-group-url/, "/community/group/" +discoveredResponse[j].AssociatedCommunityGroupKey.Key+"/");

l_sPLK_Final_BlogPost_Template += l_sPLKBlogPostTemplate;
  }
}

$('#plck_landing_blogpost_holder_template_final').html(l_sPLK_Final_BlogPost_Template);

   break;
   case "PublicPhoto":
        $('#plck-photos-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,3,'photos' ) )
var l_sPLK_Final_Photo_Template = '';
for(var j = 0; j < discoveredResponse.length; j++){
if(discoveredResponse[j].AssociatedCommunityGroupKey){
var l_sPLKPhotoTemplate = '';
l_sTimeUploaded = getActivityTime(discoveredResponse[j].CreatedOn);
l_sPLKPhotoTemplate = $("#plck_landing_photo_holder_template").html();
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-holder-url/, "/community/photo/" +discoveredResponse[j].PhotoKey.Key+"/");
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-title/, discoveredResponse[j].Title);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-title-alt/, discoveredResponse[j].Title);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~plk-photo-title~/, discoveredResponse[j].Title);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/plck-photo-thumbnail/, discoveredResponse[j].Image.Medium);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/photo-author-url/, discoveredResponse[j].Author.PersonaUrl);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-author-display-name~/, discoveredResponse[j].Author.DisplayName);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/~photo-created-on~/, l_sTimeUploaded);
l_sPLKPhotoTemplate = l_sPLKPhotoTemplate.replace(/photo-group-url/, "/community/group/" +discoveredResponse[j].AssociatedCommunityGroupKey.Key+"/");
l_sPLK_Final_Photo_Template += l_sPLKPhotoTemplate;
}

}

$('#plck_landing_photo_holder_template_final').html(l_sPLK_Final_Photo_Template);

   break;
   case "Discussion":
   
   
$('#plck-discussions-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,3,'discussions' ) )
   
var l_sPLK_Final_Discussion_Template = '';
for(var j = 0; j < discoveredResponse.length; j++){
if(discoveredResponse[j].AssociatedCommunityGroupKey){
var l_sPLKDiscussionTemplate = '';
l_sPLKDiscussionTemplate = $("#plck_landing_discussion_holder_template").html();
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/~plck-discussion-title~/, discoveredResponse[j].DiscussionTitle);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/plck-discussion-url/, discoveredResponse[j].DiscussionUrl);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/~plck-discussion~/, discoveredResponse[j].DiscussionBody);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/plck-discussion-author-url-image/, discoveredResponse[j].LiteUser.ImageUrl);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/plck-discussion-author-url/, discoveredResponse[j].LiteUser.PersonaUrl);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/~plck-discussion-author-name~/, discoveredResponse[j].LiteUser.DisplayName);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/plck-discussion-group-url/, "/community/group/"+discoveredResponse[j].AssociatedCommunityGroupKey.Key+"/");
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/~plck-discussion-author-displayname~/, discoveredResponse[j].LiteUser.DisplayName);
l_sPLKDiscussionTemplate = l_sPLKDiscussionTemplate.replace(/~discussion-created-date~/, discoveredResponse[j].LastPostDate);
l_sPLK_Final_Discussion_Template += l_sPLKDiscussionTemplate;
}
}

$('#plck_landing_discussion_holder_template_final').html(l_sPLK_Final_Discussion_Template);

   break;
   case "Persona":
$('#plck-persona-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,4,'persona' ) )
var l_sPLK_Final_Member_Template = '';
for(var j = 0; j < discoveredResponse.length; j++){
if(discoveredResponse[j].AssociatedCommunityGroupKey){
var l_sPLKMemberTemplate = '';
l_sPLKMemberTemplate = $("#plck_landing_member_holder_template").html();
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/plck-member-url/, discoveredResponse[j].ImageUrl);
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/plck-member-image-url/, discoveredResponse[j].ImageUrl);
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/~plck-member-display-name~/, discoveredResponse[j].DisplayName);
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/group-member-joined/, discoveredResponse[j].LastUpdated);
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/~joined-group-display-name~/, "");
l_sPLKMemberTemplate = l_sPLKMemberTemplate.replace(/~date-member-joined~/, "");
l_sPLK_Final_Member_Template += l_sPLKMemberTemplate;
}

}

$('#plck_landing_member_holder_template_final').html(l_sPLK_Final_Group_Template);

   break;
   case "CommunityGroup":
$('#plck-groups-pagination').html(_xPagination.createcommunitylandingmod( 1, discoveredResponse.length,3,'groups' ) )
  var l_sPLK_Final_Group_Template = '';
for(var j = 0; j < discoveredResponse.length; j++){
if(discoveredResponse[j].CommunityGroupKey){
var l_sPLKGroupTemplate = '';
l_sTimeUploaded = getActivityTime(discoveredResponse[j].CreatedDate);
var l_sSmallAvatarImage = discoveredResponse[j].AvatarImageUrl;
var l_sMediumAvatarImage = l_sSmallAvatarImage.replace("Small", "Medium"); 
l_sPLKGroupTemplate = $("#plck_landing_group_holder_template").html();
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-url-image/, "/community/group/"+discoveredResponse[j].CommunityGroupKey.Key+ "/");
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-url-group/, "/community/group/"+discoveredResponse[j].CommunityGroupKey.Key+ "/");
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/~plck-group-display-name~/, discoveredResponse[j].Title);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-title-img/, discoveredResponse[j].CommunityGroupUrl);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-img-src/, l_sMediumAvatarImage);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-url-title/, discoveredResponse[j].CommunityGroupUrl);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-title-title/, discoveredResponse[j].Title);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/~plck-group-title~/, discoveredResponse[j].Title);
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/~plck-group-owner-display-name~/, "");
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/plck-group-owner-url/, "");
l_sPLKGroupTemplate = l_sPLKGroupTemplate.replace(/~plck-created-date~/, l_sTimeUploaded);
l_sPLK_Final_Group_Template += l_sPLKGroupTemplate;
}
}

$('#plck_landing_group_holder_template_final').html(l_sPLK_Final_Group_Template);

   break;
   }
   }
}

}, 

displayArticleDetail:function(articleData){
  var l_sPLKArticleDetailMetaTemplate = '';
l_sPLKArticleDetailMetaTemplate = $('#article-detail-meta-template_1').html();
if(l_sPLKArticleDetailMetaTemplate != null){
l_sPLKArticleDetailMetaTemplate = l_sPLKArticleDetailMetaTemplate.replace(/plck-fire-count/, "firecount" );
l_sPLKArticleDetailMetaTemplate = l_sPLKArticleDetailMetaTemplate.replace(/~plck-number-of-recommendations~/, articleData.Article.Recommendations.NumberOfRecommendations);
$('#article-detail-meta-template-final_1').html(l_sPLKArticleDetailMetaTemplate);
}

var l_sPLKArticleDetailFireUpTemplate = '';
var l_sPLKArticleDetailFireUpTemplate = $('#article-detail-fireup-template_1').html();
    if(l_sPLKArticleDetailFireUpTemplate != null){
if(articleData.Article.Recommendations.CurrentUserHasRecommended == 'True'){
 l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
}else{
   l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + articleData.Article.ArticleKey.Key + "\", \"article\", this);'/>");
}
$('#article-detail-fireup-template-final_1').html(l_sPLKArticleDetailFireUpTemplate);
}
}, 

displayArticleDetailFake: function(){
        var l_sPLKArticleDetailMetaTemplate = '';
l_sPLKArticleDetailMetaTemplate = $('#article-detail-meta-template_1').html();
if(l_sPLKArticleDetailMetaTemplate != null){
l_sPLKArticleDetailMetaTemplate = l_sPLKArticleDetailMetaTemplate.replace(/plck-fire-count/, "firecount" );
l_sPLKArticleDetailMetaTemplate = l_sPLKArticleDetailMetaTemplate.replace(/~plck-number-of-recommendations~/, "0");
$('#article-detail-meta-template-final_1').html(l_sPLKArticleDetailMetaTemplate);
}

var l_sPLKArticleDetailFireUpTemplate = '';
var l_sPLKArticleDetailFireUpTemplate = $('#article-detail-fireup-template_1').html();
    if(l_sPLKArticleDetailFireUpTemplate != null){
   l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKArticleDetailFireUpTemplate = l_sPLKArticleDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"0000\", \"article\", this);'/>");
$('#article-detail-fireup-template-final_1').html(l_sPLKArticleDetailFireUpTemplate);
}
},

 

displayCommunityGroupPictureDetail:function(photoData){
  var l_sPLKPhotoDetailImageTemplate = '';
l_sPLKPhotoDetailImageTemplate = $('#photo-detail-image-template').html();
var l_sPLKPhotoDetailImageTemplate = l_sPLKPhotoDetailImageTemplate.replace(/plck-photo-detail-image/, photoData.Image.Large);
$('#photo-detail-image-template-final').html(l_sPLKPhotoDetailImageTemplate);

var l_sPLKPhotoDetailMetaTemplate = '';
var l_sPLKPhotoDetailMetaTemplate = $('#photo-detail-meta-template').html();
var l_aTextInfo = { c:'000000',type:'bl','bg':'E1E1E1',tran:true,s:22,t: ''+photoData.Title.toUpperCase()+'', w:375, lh:6 }
l_sAbstractImage = makeCustomImage(l_aTextInfo);
                               l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/plck-photo-detail-title-image/, l_sAbstractImage);
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/plck-photo-detail-title-text/, photoData.Title.toUpperCase());
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/~plck-photo-created~/, photoData.CreatedOn);
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/plck-fire-count/, "firecount" );
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/~plck-number-of-recommendations~/, photoData.NumberOfRecommendations);
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/~plck-comment-count~/, '<div id = "plck-comment-count" class="plck-comment-count-class"><span></span></div>');
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/~plck-photo-detail-description~/, photoData.Description);
l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/~plck-user-added-display-name~/, photoData.Author.DisplayName);
    l_sPLKPhotoDetailMetaTemplate = l_sPLKPhotoDetailMetaTemplate.replace(/plck-user-added-url/, photoData.Author.PersonaUrl);
    
$('#photo-detail-meta-template-final').html(l_sPLKPhotoDetailMetaTemplate);


var l_sPLKPhotoDetailFireUpTemplate = '';
var l_sPLKPhotoDetailFireUpTemplate = $('#photo-detail-fireup-template').html();

if(photoData.CurrentUserHasRecommended == 'True'){
 l_sPLKPhotoDetailFireUpTemplate = l_sPLKPhotoDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sPLKPhotoDetailFireUpTemplate = l_sPLKPhotoDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
}else{
   l_sPLKPhotoDetailFireUpTemplate = l_sPLKPhotoDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKPhotoDetailFireUpTemplate = l_sPLKPhotoDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + photoData.PhotoKey.Key + "\", \"photo\", this);'/>");
}

$('#photo-detail-fireup-template-final').html(l_sPLKPhotoDetailFireUpTemplate);

}, 

displayCommunityGroupVideoDetail:function(videoData){
            //video player
var flashvars = {p_sURL:videoData.VideoUrl};
var params = { menu:false, wmode:'transparent', bgcolor:'000000', allowFullScreen:true};
var attributes = {};
swfobject.embedSWF("/_site/swf/VersusVideoPlayer.swf", "videoplayer-detail", "614", "368", "9.0.0","_site/swf/expressInstall.swf", flashvars, params, attributes);
//video metadata
var l_sPLKVideoDetailMetaTemplate = '';
var l_sPLKVideoDetailMetaTemplate = $('#video-detail-meta-template').html();
var l_aTextInfo = { c:'000000',type:'bl','bg':'E1E1E1',tran:true,s:22,t: ''+videoData.Title.toUpperCase()+'', w:375, lh:6 }
l_sAbstractImage = makeCustomImage(l_aTextInfo);
                               l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/plck-video-detail-title-image/, l_sAbstractImage);
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/plck-video-detail-title-text/, videoData.Title.toUpperCase());
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/~plck-photo-created~/, videoData.CreatedOn);
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/plck-fire-count/, "firecount" );
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/~plck-number-of-recommendations~/, videoData.NumberOfRecommendations);
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/~plck-comment-count~/, '<div id = "plck-comment-count" class="plck-comment-count-class"><span></span></div>');
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/~plck-video-detail-description~/, videoData.Description);
l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/~plck-user-added-display-name~/, videoData.Author.DisplayName);
    l_sPLKVideoDetailMetaTemplate = l_sPLKVideoDetailMetaTemplate.replace(/plck-user-added-url/, videoData.Author.PersonaUrl);
   
    $('#video-detail-meta-template-final').html(l_sPLKVideoDetailMetaTemplate);


var l_sPLKVideoDetailFireUpTemplate = '';
var l_sPLKVideoDetailFireUpTemplate = $('#video-detail-fireup-template').html();


if(videoData.CurrentUserHasRecommended == 'True'){
 l_sPLKVideoDetailFireUpTemplate = l_sPLKVideoDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sPLKVideoDetailFireUpTemplate = l_sPLKVideoDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
  
   }else{
   l_sPLKVideoDetailFireUpTemplate = l_sPLKVideoDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKVideoDetailFireUpTemplate = l_sPLKVideoDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + videoData.VideoKey.Key + "\", \"video\", this);'/>");
}

$('#video-detail-fireup-template-final').html(l_sPLKVideoDetailFireUpTemplate);

},

displayCommunityBlogDetail:function(blogData){
var l_sBlogAuthorDisplayName = blogData.PostAuthor.DisplayName.toUpperCase()+"'s Blog";
var l_aTextInfo = {c:'000000',type:'b', 'bg':'FCB316','tran':true, s:14, t:l_sBlogAuthorDisplayName, w:410, 'bb':'9px'};
                            var l_sImageUrl = makeCustomImage(l_aTextInfo); 
                                        
l_sPLKBlogsTemplate = $('#plck-blog-detail-template').html();
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-blog-author-name-image/, l_sImageUrl);
    l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-title~/, blogData.PostTitle);
    l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-description~/, blogData.PostBody);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/group-blog-author/, blogData.PostAuthor.DisplayName);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~group-blog-post-date~/, blogData.PostDate);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-url/, blogData.PostAuthor.ImageUrl);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-persona-url/, blogData.PostAuthor.PersonaUrl);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/plck-group-blog-author-display-name/, blogData.PostAuthor.DisplayName);
l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~plck-blog-tags~/, blogData.PostTags);

var l_sPLKBlogDetailFireUpTemplate = '';
var l_sPLKBlogDetailFireUpTemplate = $('#blog-detail-fireup-template').html();

if(blogData.CurrentUserHasRecommended == 'True'){
 l_sPLKBlogDetailFireUpTemplate = l_sPLKBlogDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "sprite_selected");
 l_sPLKBlogDetailFireUpTemplate = l_sPLKBlogDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick=''/>");
  
   }else{
   l_sPLKBlogDetailFireUpTemplate= l_sPLKBlogDetailFireUpTemplate.replace(/~extraclass-fireup-selected~/, "");
   l_sPLKBlogDetailFireUpTemplate = l_sPLKBlogDetailFireUpTemplate.replace(/~fireup-a-tag~/,"<a href='javascript:void(0)' onclick='javascript:recommend(\"" + blogData.BlogPostKey.Key + "\", \"blog-post\", this);'/>");
}

l_sPLKBlogsTemplate = l_sPLKBlogsTemplate.replace(/~blog-detail-fireup-template-final~/, l_sPLKBlogDetailFireUpTemplate);

$('#plck-blog-detail-template-final').html(l_sPLKBlogsTemplate);
}, 

displayAvatarPhoto: function(avatarPhotoUrl){
      $('#plck-avatar-photo-url').html(avatarPhotoUrl);
}

};


_xDisplayMiniModules = {
            displayModeratorModule:function(userData){
        var l_sPLKMiniModeratorTemplate = '';
var l_sPLKFinalMiniModeratorTemplate = '';
l_sPLKMiniModeratorTemplate = $('#plck-moderator-info-template').html();
l_sPLKMiniModeratorTemplate = l_sPLKMiniModeratorTemplate.replace(/plck-moderator-image/, userData.AvatarPhotoUrl); 
l_sPLKMiniModeratorTemplate = l_sPLKMiniModeratorTemplate.replace(/~plck-moderator-display-name~/, userData.DisplayName);
l_sPLKMiniModeratorTemplate = l_sPLKMiniModeratorTemplate.replace(/plck-user-url/, userData.PersonaUrl);
$('#plck-moderator-info-template_final').html(l_sPLKMiniModeratorTemplate);
},

displayCommunityTitleandYear:function(l_sTitle, l_sYear){
    l_aMonths = new Array("Zero", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
    l_sYearSplit = l_sYear.split("/");
l_sPluckMonth = l_sYearSplit[0];
l_sMonth = l_aMonths[l_sPluckMonth];
l_sPluckYearTime = l_sYearSplit[2].split(" ");
l_sYear = l_sPluckYearTime[0];

l_sGroupStartedString = "Started on "+ l_sYearSplit[1] +" "+ l_sMonth +", "+ l_sYear +"";
$('#plck_date_started').html(l_sGroupStartedString);

var l_sPLKTitleYearTemplate = '';
var l_sPLKFinalTitleYearTemplate = '';
l_sPLKTitleYearTemplate = $('#plck-moderation-info-group-template').html();
l_sPLKTitleYearTemplate = l_sPLKTitleYearTemplate.replace(/~plck-group-name~/, l_sTitle); 
l_sPLKTitleYearTemplate = l_sPLKTitleYearTemplate.replace(/~plck-group-year-founded~/, l_sYear);
$('#plck-moderation-info-group-template_final').html(l_sPLKTitleYearTemplate);

}, 

displaySimilarContent:function(l_sThumbnailUrl, l_sTitle, l_nMemberCount, l_sGroupURL){
   var l_sPLKFinal_SimilarGroupsTemplate = '';
   var l_sStyleWidth = l_sGroupURL.length*140;
   $('#similar_groups_reel_inner').css('width', l_sStyleWidth); 
   $('#plck-discovery-pagination').html(_xPagination.createcommunitylandingmod( 1, l_sGroupURL.length,2,'discovery' ) )
   
   for(var i = 1; i < l_sGroupURL.length; i ++){
    var l_sPLKSimilarGroupsTemplate = '';
l_sPLKSimilarGroupsTemplate = $('#plck-similar-groups-template').html();
l_sPLKSimilarGroupsTemplate = l_sPLKSimilarGroupsTemplate.replace(/plck-group-url-image/, l_sThumbnailUrl[i]); 
l_sPLKSimilarGroupsTemplate = l_sPLKSimilarGroupsTemplate.replace(/plck-group-url/, "/community/group/"+l_sGroupURL[i]+ "/");
l_sPLKSimilarGroupsTemplate = l_sPLKSimilarGroupsTemplate.replace(/~plck-group-title~/, l_sTitle[i]);
l_sPLKSimilarGroupsTemplate = l_sPLKSimilarGroupsTemplate.replace(/~plck-no-of-members~/, l_nMemberCount[i]);
l_sPLKSimilarGroupsTemplate = l_sPLKSimilarGroupsTemplate.replace(/~plck-no-of-members~/, l_nMemberCount[i]);
l_sPLKFinal_SimilarGroupsTemplate += l_sPLKSimilarGroupsTemplate; 
}

   $('#plck-similar-groups-template-final').html(l_sPLKFinal_SimilarGroupsTemplate);
}, 

displayEventsMiniModule: function(response){
 var l_sPLKMemberships_Template_Final = '';
     for(var i = 0; i < response.Events.length; i++){
  
  var EventsData = '';
  var EventsData = response.Events[i];
  var l_sSplitDateTime = EventsData.StartDate_UTC.split(" ");
  var l_nFinalDate = l_sSplitDateTime[1];
  var l_sFinalMonth = l_sSplitDateTime[2];
  var l_sDatePrintTemplate = '';
  for(var j = 0; j < l_nFinalDate.length; j++){
l_sDatePrintTemplate += "<img src='/image/groups_cal_num_" + l_nFinalDate[j] + ".gif?v=213' alt='"  + l_nFinalDate[j] + "' />";
  }
 
  l_sMonthNameImage = generateImageFromText(l_sFinalMonth, '940005', 'FFFFFF');
  l_nDateNumber = i + 1; 
  var l_sPLKDateHolderTemplate = '';
  l_sPLKDateHolderTemplate = $('#plck_date_holder_template').html();
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/plck-datenumber/, "date date"+l_nDateNumber); 
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/plck-generated-image-month/, l_sMonthNameImage); 
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/plck-text-month/, l_sFinalMonth);
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/~date~/, l_sDatePrintTemplate);
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/~event-title~/, EventsData.Title);
  l_sPLKDateHolderTemplate = l_sPLKDateHolderTemplate.replace(/~event-location~/, EventsData.Location);
  $('#plck_date_holder_template_'+i).html(l_sPLKDateHolderTemplate);
}

 if((parseInt(response.NumberOfEvents)) > (parseInt(response.NumberPerPage))){
        l_aPaginationInfo = _xPagination.mod(response.OnPage, response.NumberOfEvents, response.NumberPerPage, response.EventSetKey.Key, "_xCommunityEvents.getRecentEventsMiniModule", response.Sort);
        l_sPaginationTemplate = $('#plck_pagi_moderation').html();
  l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-left~/,"<div class= 'mod_pagination_left sprite " + l_aPaginationInfo['left_class'] + "'><a " + l_aPaginationInfo['left_string'] +  "><span>Left</span></a></div>");               
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-right~/,"<div class= 'mod_pagination_right sprite  " + l_aPaginationInfo['right_class'] + "'><a " + l_aPaginationInfo['right_string'] + "><span>Right</span></a></div>");
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~page-numbers~/, "" + l_aPaginationInfo['item_display'] + " of <b> " + l_aPaginationInfo['total_count'] + "</b>");
$('#plck_pagi_final_events').html(l_sPaginationTemplate);
}
},

 displayGroupMemberships: function(response){
                             
 var l_sPLKMemberships_Template_Final = '';

 for(var i = 0; i < response.CommunityGroupMemberships.length; i++){
  var l_sPLKMemberships_Template = '';
   var l_sPLKMemberships_Template = $('#plck-group-memberships-template').html();
   var membershipData = '';
  var membershipData = response.CommunityGroupMemberships[i];
  var l_sPlkJoinedDate = membershipData.CreatedDate_UTC;
  var l_sPLkJoinedDateSplit = l_sPlkJoinedDate.split(" ");
  var l_sJoinString = "Joined on "+l_sPLkJoinedDateSplit[0]+" "+l_sPLkJoinedDateSplit[1]+" "+l_sPLkJoinedDateSplit[2]+" "+l_sPLkJoinedDateSplit[3]+"";
  
  if(i == 0){
    l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/~memberfirst~/, "member_first");
l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/~plck-membership-activity~/, '<div id = "plck_membership_user_activity_1"></div>');
//get activitues for first user
_xCore.getActivitiesForUserMembershipOne(membershipData.User.UserKey.Key);
  }
  
  if(i == 1){
    l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/~plck-membership-activity~/, '<div id = "plck_membership_user_activity_2"></div>');
    //get activities for second user
_xCore.getActivitiesForUserMembershipTwo(membershipData.User.UserKey.Key);
  }
 
  
  l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/user-image-url/, membershipData.User.ImageUrl);
  l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/~plck-join-date~/, l_sJoinString);
  l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/user-url/, membershipData.User.PersonaUrl);
  l_sPLKMemberships_Template = l_sPLKMemberships_Template.replace(/~plck-user-display-name~/, membershipData.User.DisplayName);
      l_sPLKMemberships_Template_Final += l_sPLKMemberships_Template;
}

$('#plck-group-memberships-template-final').html(l_sPLKMemberships_Template_Final);

 if((parseInt(response.NumberOfCommunityGroupMemberships)) > (parseInt(response.NumberPerPage))){
        l_aPaginationInfo = _xPagination.mod(response.OnPage, response.NumberOfCommunityGroupMemberships, response.NumberPerPage, response.Key.CommunityGroupKey.Key, "_xCore.getGroupMembershipPage", response.Sort);
        l_sPaginationTemplate = $('#plck_pagi_moderation').html();
  l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-left~/,"<div class= 'mod_pagination_left sprite " + l_aPaginationInfo['left_class'] + "'><a " + l_aPaginationInfo['left_string'] +  "><span>Left</span></a></div>");               
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-right~/,"<div class= 'mod_pagination_right sprite  " + l_aPaginationInfo['right_class'] + "'><a " + l_aPaginationInfo['right_string'] + "><span>Right</span></a></div>");
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~page-numbers~/, "" + l_aPaginationInfo['item_display'] + " of <b> " + l_aPaginationInfo['total_count'] + "</b>");
$('#plck_pagi_final_moderation').html(l_sPaginationTemplate);
}
},

 displayGroupAdminMemberships: function(response){
                          // $('#group-members-link').addClass("plk_always_hide");
  // $('#banned-members-link').removeClass("plk_always_hide");
var l_sPLKAdminMemberships_Template_Final = '';

 for(var i = 0; i < response.CommunityGroupMemberships.length; i++){
  var l_sPLKAdminMemberships_Template = '';
   var l_sPLKAdminMemberships_Template = $('#plck-groupmemberdir').html();
   var membershipData = '';
  var membershipData = response.CommunityGroupMemberships[i];
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-image-url/, membershipData.User.ImageUrl);
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-membership-tier/, membershipData.MembershipTier);
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-persona-url/, membershipData.User.PersonaUrl);
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-member-display-name~/, membershipData.User.DisplayName);
      l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-number-of-friends/, membershipData.User.NumberOfFriends +" Friends");
      l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-member-display-name~/, membershipData.User.DisplayName);
      l_sCommunityGroupKey = $('#plck-group-key-set').html();
  if(membershipData.MembershipTier == "Member"){
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-promote-members~/, "<a onclick='javascript:_xCore.updateCommunityGroupMembership(\""+l_sCommunityGroupKey+"\", \""+membershipData.User.UserKey.Key+"\", \"Manager\", false, this);'>Promote Member</a>");
    l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-ban-members~/, "<a onclick='javascript:_xCore.updateCommunityGroupMembership(\""+l_sCommunityGroupKey+"\", \""+membershipData.User.UserKey.Key+"\", \"Member\", true, this);'>Ban Member</a>");
    l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-tools~/, "Admin Tools");
l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~space~/, "|");
  }
  if(membershipData.MembershipTier == "Manager"){
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-promote-members~/, "<a onclick='javascript:_xCore.updateCommunityGroupMembership(\""+l_sCommunityGroupKey+"\", \""+membershipData.User.UserKey.Key+"\", \"Member\", false, this);'>Demote Member</a>");
    l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-ban-members~/, "<a onclick='javascript:_xCore.updateCommunityGroupMembership(\""+l_sCommunityGroupKey+"\", \""+membershipData.User.UserKey.Key+"\", \"Member\", true, this);'>Ban Member</a>");
    l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-tools~/, "Admin Tools");
l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~space~/, "|");
  }
  if(membershipData.MembershipTier == "GroupAdmin"){
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-promote-members~/, "");
    l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-ban-members~/, "");
l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-tools~/, "");
l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~space~/, "");
  }
  
  
  
  
  l_sPLKAdminMemberships_Template_Final += l_sPLKAdminMemberships_Template;
}


$('#plck-groupmemberdir-final').html(l_sPLKAdminMemberships_Template_Final);

if((parseInt(response.NumberOfCommunityGroupMemberships)) > (parseInt(response.NumberPerPage))){
        l_aPaginationInfo = _xPagination.mod(response.OnPage, response.NumberOfCommunityGroupMemberships, response.NumberPerPage, response.Key.CommunityGroupKey.Key, "_xCore.getGroupMembershipAdminPage", response.Sort);
        l_sPaginationTemplate = $('#plck_pagi_admin_membership').html();
  l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-left~/,"<div class= 'mod_pagination_left sprite " + l_aPaginationInfo['left_class'] + "'><a " + l_aPaginationInfo['left_string'] +  "><span>Left</span></a></div>");               
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-right~/,"<div class= 'mod_pagination_right sprite  " + l_aPaginationInfo['right_class'] + "'><a " + l_aPaginationInfo['right_string'] + "><span>Right</span></a></div>");
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~page-numbers~/, "" + l_aPaginationInfo['item_display'] + " of <b> " + l_aPaginationInfo['total_count'] + "</b>");
$('#plck_pagi_admin_membership_final').html(l_sPaginationTemplate);
} else{
$('#plck_pagi_admin_membership_final').html("");
}


_xTruebox.makeMemberDirectory($('#memberdirectory_template').html());


},

 displayGroupBannedMemberships: function(response){
                            // $('#banned-members-link').addClass("plk_always_hide");
// $('#group-members-link').removeClass("plk_always_hide");
 var l_sPLKAdminMemberships_Template_Final = '';

 for(var i = 0; i < response.BannedUsers.length; i++){
  var l_sPLKAdminMemberships_Template = '';
   var l_sPLKAdminMemberships_Template = $('#plck-groupmemberdir').html();
   var membershipData = '';
  var membershipData = response.BannedUsers[i];
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-image-url/, membershipData.UserResponse.ImageUrl);
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-membership-tier/, "Banned");
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-persona-url/, membershipData.UserResponse.PersonaUrl);
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-member-display-name~/, membershipData.UserResponse.DisplayName);
      l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/plck-admin-member-number-of-friends/, membershipData.UserResponse.NumberOfFriends+ " Friends");
      l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-member-display-name~/, membershipData.UserResponse.DisplayName);
      l_sCommunityGroupKey = $('#plck-group-key-set').html();
  
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-promote-members~/, "");
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-ban-members~/, "<a onclick='javascript:_xCore.updateCommunityGroupMembership(\""+l_sCommunityGroupKey+"\", \""+membershipData.UserResponse.UserKey.Key+"\", \"Member\", false, this);'>Unban Member</a>");
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~plck-admin-tools~/, "");
  l_sPLKAdminMemberships_Template = l_sPLKAdminMemberships_Template.replace(/~space~/, "");
  l_sPLKAdminMemberships_Template_Final += l_sPLKAdminMemberships_Template;
}


$('#plck-groupmemberdir-final').html(l_sPLKAdminMemberships_Template_Final);

if((parseInt(response.NumberOfCommunityGroupBannedUsers)) > (parseInt(response.NumberPerPage))){
        l_aPaginationInfo = _xPagination.mod(response.OnPage, response.NumberOfCommunityGroupMemberships, response.NumberPerPage, response.Key.CommunityGroupKey.Key, "_xCore.getGroupMembershipAdminPage", response.Sort);
        l_sPaginationTemplate = $('#plck_pagi_admin_membership').html();
  l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-left~/,"<div class= 'mod_pagination_left sprite " + l_aPaginationInfo['left_class'] + "'><a " + l_aPaginationInfo['left_string'] +  "><span>Left</span></a></div>");               
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~mod-pagi-right~/,"<div class= 'mod_pagination_right sprite  " + l_aPaginationInfo['right_class'] + "'><a " + l_aPaginationInfo['right_string'] + "><span>Right</span></a></div>");
l_sPaginationTemplate = l_sPaginationTemplate.replace(/~page-numbers~/, "" + l_aPaginationInfo['item_display'] + " of <b> " + l_aPaginationInfo['total_count'] + "</b>");
$('#plck_pagi_admin_membership_final').html(l_sPaginationTemplate);
} else{
   $('#plck_pagi_admin_membership_final').html("");
}



_xTruebox.makeMemberDirectory($('#memberdirectory_template').html());


},

displayGroupNoMemberships:function(){
alert("display group no memberships!");

$('#plck-groupmemberdir-final').html("No users yet");
_xTruebox.makeMemberDirectory($('#memberdirectory_template').html());


}

};



 
 
 
 


   var l_aValidVideoFileFormats = new Array("mp4", "VOB", "MPG", "3GP", "AVI", "ASF", "WMV", "MOV", "FLV");
  var l_aValidPhotoFileFormats = new Array("jpeg", "gif", "png", "jpg", "bmp");
 


  function handleErrorsType($p_xType, responseBatch) {
var s = '';
for (var i = 0; i < responseBatch.Messages.length; i++) {
s = s + responseBatch.Messages[i].Message + '\n\n';
}
alert(s);
}

function handleErrors(responseBatch) {
var s = '';
for (var i = 0; i < responseBatch.Messages.length; i++) {
s = s + responseBatch.Messages[i].Message + '\n\n';
}
alert(s);
}

   _xValidate = {
              validateAvatarPhoto: function(l_sFileName){
var l_bIsValid = false;
$('#error').html('false');
splitName = l_sFileName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
for(var i = 0; i < l_aValidPhotoFileFormats.length; i++){
if(fileType == l_aValidPhotoFileFormats[i]){
   l_bIsValid = true;
   $('#error').html('false');
    }
}

if(l_bIsValid == false){
      $('#invalid_file_format').html("Invalid File Format");
   $('#error').html('true');
}
else{
  $('#invalid_file_format').html("");
      _xPluckPhoto.uploadAvatarPhoto();
}
  },
  
  validateMedia: function(l_sFileName, p_sType){
var l_bIsValid = false;
  $('#error').html('false');

  splitName = l_sFileName.split(".");
  fileType = splitName[1];
  fileType = fileType.toLowerCase();

  switch(p_sType){
  case 'image':
 for(var i = 0; i < l_aValidPhotoFileFormats.length; i++){
     if(fileType == l_aValidPhotoFileFormats[i].toLowerCase()){
l_bIsValid = true;
   $('#error').html('false');

}
}
  break;
  case 'video':
  for(var i = 0; i < l_aValidVideoFileFormats.length; i++){
     if(fileType == l_aValidVideoFileFormats[i].toLowerCase()){
l_bIsValid = true;
   $('#error').html('false');
}
}
  break;
  }
  
  if(l_bIsValid == false){
       $('#invalid_file_format').html("Invalid File Format");
   $('#error').html('true');
   } else{
           $('#invalid_file_format').html("");
}

  }, 
  
  validateCreateGroupForm:function(){
l_aErrors = Array();
var l_bIsValid = false;
$('#error').html('false');
  
 if($('#title').val()){
   l_bIsValid = true;
    $('#invalid_title').html("");
 }else{
 l_aErrors.push("Please Enter Title");
 $('#invalid_title').html("Please enter Title.");
 $('#error').html('true');
 l_bIsValid = false;
 }
 
if($('#group_section_list').val()){
  l_bIsValid = true;
 }else{
 l_aErrors.push("Please enter your sport Name.");
 $('#error').html('true');
 l_bIsValid = false;
 }
 
if($('#avatarphotokey').html() == "null"){
 var l_bIsMediaValid = false;
 $('#invalid_media').html("Please Upload Group Image.");
 }else{
 $('#invalid_media').html("");
 l_bIsMediaValid = true;
 }
 
 var l_sAvatarKey = $('#avatarphotokey').html();
 
 if(l_sAvatarKey.indexOf("Anonymous") != -1){
var l_bIsMediaValid = false;
$('#invalid_media').html("Anonymous user is not allowed to upload photos. Please login!");
 }
 
 
 
 if(l_bIsValid && l_bIsMediaValid){
      return true;
  }else{
 return false;
 }
 
 
 
 
  },
  
  validateMediaForm:function(){
      l_aErrors = Array();
  var l_bIsValid = true;
  
  if($('#title').val()){
  $('#invalid_title').html("");
}else{
 l_bIsValid = false; 
 $('#invalid_title').html("Please enter title");
}
  
 if($('#error').html() == 'true'){
 l_bIsValid = false;       
$('#invalid_file_format').html("Please upload media");
 }else{
   $('#invalid_file_format').html("");
 }
 
 if(l_bIsValid){
 return true;
  }else{
 return false;
 }
 
 
 
  },
  
  validateBlogForm:function(){
  
  l_aErrors = Array();
  var l_bIsValid = true;
  
  if($('#title').val()){
    $('#invalid_title').html("");
}else{
 l_bIsValid = false; 
 $('#invalid_title').html("Please enter title.");
 }
  
 if($('#desc').val()){
  $('#invalid_desc').html("");
}else{
 l_bIsValid = false; 
   $('#invalid_desc').html("Please enter post.");
}
 
 if(l_bIsValid){
 return true;
  }else{
 return false;
 }
  },
  
  validateEventForm:function(){
     l_aErrors = Array();
  var l_bIsValid = true;
  
  if($('#title').val()){
  $('#invalid_title').html("");
}else{
 l_bIsValid = false; 
 $('#invalid_title').html("Please enter Title");
  }
  
  if($('#desc').val()){
  $('#invalid_desc').html("");
}else{
 l_bIsValid = false; 
   $('#invalid_desc').html("Please enter Description.");
  }
  
  if($('#loc').val()){
  $('#invalid_loc').html("");
}else{
 l_bIsValid = false; 
      $('#invalid_loc').html("Please enter valid location.");

  }
 
  if($('#start_time_picker').val()){
    $('#invalid_sdate').html("");
}else{
 l_bIsValid = false; 
 $('#invalid_sdate').html("Please enter Start Date.");
  }
  
     
  if($('#start_time_entry').val()){
  $('#invalid_stime').html("");
  }else{
 l_bIsValid = false;
   $('#invalid_stime').html("Please enter Start Time.");
 }
  
  if($('#end_time_picker').val()){
  $('#invalid_edate').html("");
  }else{
 l_bIsValid = false; 
  $('#invalid_edate').html("Please enter End Date.");
  
}
   
if($('#end_time_entry').val()){
  $('#invalid_etime').html("");
    }else{
 l_bIsValid = false; 
   $('#invalid_etime').html("Please enter End Time.");

}

if($('#url').val()){
  $('#invalid_url').html("");
  }else{
 l_bIsValid = false;
   $('#invalid_url').html("Please enter valid url.");
 }
 
  if($('#name').val()){
  $('#invalid_urlname').html("");
    }else{
 l_bIsValid = false; 
   $('#invalid_urlname').html("Please enter valid url name.");

}
 
 
  
 if(l_bIsValid){
 return true;
  }else{
return false;
 }
  }, 
  
  isEmpty: function(aTextField) {
   if ((aTextField.value.length==0) ||(aTextField.value==null)) {
      return true;
   }
   else { return false; }
 },
 
 getCookie:function(name) {
var theCookies = document.cookie.split(/[; ]+/);
for (var i = 0 ; i < theCookies.length; i++) {
var aName = theCookies[i].substring(0,theCookies[i].indexOf('='));
if (aName == name) {
return theCookies[i];
}
}
}, 

validateCookie:function(name){
var theCookies = document.cookie.split(/[; ]+/);
for (var i = 0 ; i < theCookies.length; i++) {
var aName = theCookies[i].substring(0,theCookies[i].indexOf('='));
if (aName == name) {
return theCookies[i];
}
}
}

   
   }


var p_xResponseBatch = "";
var p_xResponsebatch = "";
function callbackPublicPhotoGalleryModule(p_xResponseBatch){
_xCallback.callback('public-photo-gallery',p_xResponseBatch);
}

function callbackPublicVideoGalleryModule(p_xResponseBatch){
_xCallback.callback('public-video-gallery',p_xResponseBatch);
}

function callbackSimilarContent(p_xResponseBatch){
_xCallback.callback('similar-content-module',p_xResponseBatch);
}

function callbackDiscoverContentGroupLandingModule(p_xResponsebatch){
  _xCallback.callback('discover-content-group-landing',p_xResponsebatch);
   
}
function callbackMostPopularGroups(p_xResponsebatch){
     _xCallback.callback('most-popular-groups', p_xResponsebatch);
}

function callbackNewestGroups(p_xResponseBatch){
     _xCallback.callback('newest-groups', p_xResponseBatch);
}

function callbackMostActiveGroupsFilter(p_xResponseBatch){
     _xCallback.callback('most-active-groups-filter', p_xResponseBatch);
}

function callbackRecentActivityFeedModule(p_xResponsebatch){
_xCallback.callback('recent-activity-feed',p_xResponsebatch);
}

function callbackMostCommentedPhotos(p_xResponsebatch){
      _xCallback.callback('most-recommended-photos',p_xResponsebatch);
}

function callbackGetCommunityGroupPageAggregate(p_xResponseBatch){
   _xCallback.callback('community-group-page-aggregate',p_xResponseBatch);
}

function callbackCommunitySearchResultsModule(p_xResponseBatch){
    _xCallback.callback('community-search-results',p_xResponseBatch);
}

function callbackGroupStatsModule(p_xResponseBatch){
       _xCallback.callback('community-group-stats',p_xResponseBatch);
}

function callbackGroupTabModule(p_xResponseBatch){
                _xCallback.callback('community-group-tab-module', p_xResponseBatch);
_xHandleFunctionCallback.callback('group-id-set', p_xResponseBatch);
                    _xHandleFunctionCallback.callback('moderator-info', p_xResponseBatch);
_xHandleFunctionCallback.callback('similar-content-info', p_xResponseBatch);
_xHandleFunctionCallback.callback('recent-events-info', p_xResponseBatch);
_xHandleFunctionCallback.callback('group-membership', p_xResponseBatch);
                    _xInitCallback.loadData(p_xResponseBatch);
}

function callbackPictureDetail(p_xResponseBatch){
_xHandleFunctionCallback.callback('photo-detail-id-set', p_xResponseBatch);
    }



//Group Photos
function callbackGroupPhotosSubModule(p_xResponseBatch){
      _xCallback.callback('sub-module-group-photos',p_xResponseBatch);
}
function callbackPhotoDetail(p_xResponseBatch){
      _xCallback.callback('photo-detail',p_xResponseBatch);
}
//Group Videos
function callbackGroupVideosSubModule(p_xResponseBatch){
      _xCallback.callback('sub-module-group-videos',p_xResponseBatch);
}

        function callbackVideoDetail(p_xResponseBatch){
      _xCallback.callback('video-detail',p_xResponseBatch);
}

//Group Events
function callbackGroupEventsBadgeModule(p_xResponseBatch){
            _xCallback.callback('sub-module-group-events',p_xResponseBatch);
}

    function callbackUpcomingEventsModule(p_xResponseBatch){
            _xCallback.callback('upcoming-events-module',p_xResponseBatch);
}

function callbackRecentEventsModule(p_xResponseBatch){
                          _xCallback.callback('recent-events-module',p_xResponseBatch);
}

//Group Blogs
function callbackSubModuleBlogs(p_xResponseBatch){
_xCallback.callback('sub-module-group-blogs',p_xResponseBatch);
}

//Group Forums
function callbackSubModuleForums(p_xResponseBatch){
_xCallback.callback('sub-module-group-forums',p_xResponseBatch);
}

//Comments Widget
function callbackComments(p_xResponseBatch){
 document._nCommentSent = false;
_xCallback.callback('comments',p_xResponseBatch);
}

function callbackCommentsYesNo(p_xResponseBatch){
    document._nCommentSent = false;
_xCallback.callback('comments-yes-no',p_xResponseBatch);
$('#plck_comment_body').val("Type your smack here...");
}

function callbackJoinedGroup(p_xResponseBatch){
_xCallback.callback('joined-group', p_xResponseBatch);
}

function callbackGeneric(responseBatch) {
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}


        }

function callbackActionYesNoComments(responseBatch){
//console.log(responseBatch);
if(document._nCommentSent){
   getComments(document._nCommentSent,2, 1, "TimeStampDescending", "", "article"); 
   l_nAddCount = parseInt($('#plck-comment-count').html()) + 1;
   $('#plck-comment-count').html(l_nAddCount)
   
}

if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}


}

function callbackEmailSent(p_xResponseBatch){
    if (p_xResponseBatch.Responses.length == 0) {
if (p_xResponseBatch.Messages.length == 1 && p_xResponseBatch.Messages[0].Message == 'ok'){
$('#groupeditor_content').removeClass('groupeditor_content').addClass('plk_always_hide');
$('#thankyou').removeClass('plk_always_hide').addClass('groupeditor_content');

var l_sStartText = 'YOUR EMAIL IS SENT!';
var l_aTextInfo = { c:'000000',type:'med','bg':'ffffff',tran:true,s:14,w:238,cen:true,t:l_sStartText}
var l_sImageUrl = makeCustomImage(l_aTextInfo);
$('#thankyou').append( '<img class="finishtext" src="'+l_sImageUrl+'" >'  );
 
}else{
handleErrors(p_xResponseBatch);
return;
}
}

}

function callbackGetCommunity(p_xResponsebatch){
      //console.log(p_xResponsebatch);
  if (p_xResponsebatch.Responses.length == 0) {
if (p_xResponsebatch.Messages.length == 1 && p_xResponsebatch.Messages[0].Message == 'ok') return;
handleErrors(p_xResponsebatch);
return;
  }
}

function callbackGroupModeratorModule(p_xResponseBatch){
      _xCallback.callback('group-moderator-module',p_xResponseBatch);
}

function callbackGroupRecentEventsMiniModule(p_xResponseBatch){
  _xCallback.callback('recent-events-mini-module',p_xResponseBatch);
}

function callbackUserExists(p_xResponseBatch){
   if (p_xResponseBatch.Responses[0].User.DisplayName == p_xResponseBatch.Responses[0].User.UserKey.Key) {
      $('#persona_not_exist').css('display', 'inline');
}else{
    $('#persona_exist').css('display', 'inline');
}
}

function callbackRecommend(p_xResponseBatch){
        if (p_xResponseBatch.Responses.length == 0) {
if (p_xResponseBatch.Messages.length == 1 && p_xResponseBatch.Messages[0].Message == 'ok'){
 var f = document._xRecommend;
 $(f.parentNode).removeClass("fireitup_button sprite").addClass("fireitup_button sprite sprite_selected");
 
 if(document._xIncrementRecommend){
 l_nFireCount = parseInt($(".firecount").html());
 l_nFireCount += 1;
 $(".firecount").html(l_nFireCount);
 document._xIncrementRecommend = false;
 document._bIncrementRecommendForShows = true;
 }
}else{
handleErrors(p_xResponseBatch);
return;
}
}
}

function callbackReportAbuse(p_xResponseBatch){
        if (p_xResponseBatch.Responses.length == 0) {
if (p_xResponseBatch.Messages.length == 1 && p_xResponseBatch.Messages[0].Message == 'ok'){
 var f = document._xAbuse;
 $(f.parentNode).removeClass("flag_button sprite").addClass("flag_button sprite sprite_selected");
}else{
handleErrors(p_xResponseBatch);
return;
}
}

}

function callbackUserAvatarPhoto(p_xResponseBatch){
    _xCallback.callback('user-avatar-photo', p_xResponseBatch);
}

function callbackUserActivityModeration(p_xResponseBatch){
 _xCallback.callback('user-activity-moderation',p_xResponseBatch);
}

function callbackUserActivityMembershipOne(p_xResponseBatch){
 _xCallback.callback('user-activity-membership-1',p_xResponseBatch);
}

function callbackUserActivityMembershipTwo(p_xResponseBatch){
 _xCallback.callback('user-activity-membership-2',p_xResponseBatch);
}

function callbackCommunityUserMembership(p_xResponseBatch){
 _xCallback.callback('user-membership',p_xResponseBatch);
}


        _xInitCallback = {
            

loadData:function(responseBatch){
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}
//console.log(responseBatch);

//get type
//TODO: FIND BETTER WAY OF GETTING GET VALUES
var l_aGet = window.location.href.split("/");
var l_sType = l_aGet[6];
//get response data
var response = responseBatch.Responses[0];
//Load data based on content type
 switch(l_sType){
case '':
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
_xInit.initGroupHome(response.CommunityGroup.CommunityGroupKey.Key);
} 
break;
case 'events':
if (response.CommunityGroup.EventSetKey.Key != null) {
_xInit.initGroupEvents(response.CommunityGroup.EventSetKey.Key);
}
break;
case 'forum':
if (response.CommunityGroup.ForumKey.Key != null) {
_xInit.initGroupForums(response.CommunityGroup.ForumKey.Key);
}
break;
case 'videos':
if (response.CommunityGroup.VideoGalleryKey.Key != null) {
_xInit.initGroupVideos(response.CommunityGroup.VideoGalleryKey.Key);
}
break;
case 'pictures':
if (response.CommunityGroup.PhotoGalleryKey.Key != null) {
_xInit.initGroupPictures(response.CommunityGroup.PhotoGalleryKey.Key);
}
break;
case 'blogs':
if (response.CommunityGroup.BlogKey.Key != null) {
_xInit.initGroupBlogs(response.CommunityGroup.BlogKey.Key);
}
break;
 }
}
};




_xCallback = {

callback:function(p_sType,responseBatch){
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

 switch (p_sType){
case 'recent-activity-feed':
for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.RecentMiniFeedActivity.NumberOfActivities != "0") {
_xDisplay.displayRecentFeedModule(response.RecentMiniFeedActivity);
} else {
_xDisplay.displayNoContentImage('home_no_content');
}
}
  break;
 case 'discover-content-group-landing':
  _xDisplay.displayDiscoverContentGroupLandingModule(responseBatch);
 break; 
 case 'most-popular-groups':
      for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.DiscoverContentAction.DiscoveredContent != null) {
 displayMostPopularGroups(response.DiscoverContentAction);
    } 
  }
 break;
 case 'newest-groups':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.DiscoverContentAction.DiscoveredContent != null) {
 displayNewestGroups(response.DiscoverContentAction);
    } 
  }
 break;
 case 'most-recommended-photos':
      for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.DiscoverContentAction.DiscoveredContent != null) {
 displayMostRecommendedPhotos(response.DiscoverContentAction);
    } 
  }
 break;
 case 'community-group-page-aggregate':
for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroupPage.CommunityGroups != null) {
_xDisplay.displayCommunityGroupPageAggregate(response.CommunityGroupPage);
} 
}
  break;
 case 'most-active-groups-filter':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.DiscoverContentAction.DiscoveredContent != null) {
 displayMostActiveGroupsFilter(response.DiscoverContentAction);
    } 
  }
  break;
  case 'community-search-results':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.SearchResult.SearchResults != null) {
 displayCommunitySearchResults(response);
    } 
  }
  break;
  case 'community-group-stats':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
_xDisplay.displayCommunityBadgeModule(response.CommunityGroup.CommunityGroupStats.MemberCount, "home");
} 

  }
   break;
  case 'community-group-tab-module':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup != null) {
_xDisplay.displayCommunityTabModule(response.CommunityGroup.AvatarImageUrl, 
response.CommunityGroup.Title, 
response.CommunityGroup.Description, 
response.CommunityGroup.CommunityGroupKey.Key,
response.CommunityGroup.RequestingUsersMembershipTier);

_xDisplayMiniModules.displayCommunityTitleandYear(response.CommunityGroup.Title, 
  response.CommunityGroup.CreatedDate);
 } 
  }
  break;
  case 'upcoming-events-module':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.EventsPage.NumberOfEvents != "0") {
 _xDisplay.displayGroupUpcomingEvents(response.EventsPage);
    } 
  }
  break;
  case 'recent-events-module':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.EventsPage.NumberOfEvents != "0") {
 _xDisplay.displayGroupPreviousEvents(response.EventsPage);
    } 
  }
  break;
  case 'public-photo-gallery':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
//if (response.EventsPage.NumberOfEvents != "0") {
 //displayPublicPhotoGallery(response.EventsPage);
    //} 
  }
  break;
  case 'public-video-gallery':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
//if (response.EventsPage.NumberOfEvents != "0") {
 //displayPublicVideoGallery(response.EventsPage);
    //} 
  }
  break;
  case 'sub-module-group-photos':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.PhotoPage.NumberOfPhotos != "0") {
 _xDisplay.displayCommunityGroupPictures(response.PhotoPage);
}else {
_xDisplay.displayNoContentImage('plck_picture_page_template_final');
}
_xDisplay.displayCommunityBadgeModule(response.PhotoPage.NumberOfPhotos, "pictures");
  }
  break;
  case 'photo-detail':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.Photo != null) {
 _xDisplay.displayCommunityGroupPictureDetail(response.Photo);
} 
  }
  break;
  case 'sub-module-group-videos':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.VideoPage.NumberOfVideos != "0") {
 _xDisplay.displayCommunityGroupVideos(response.VideoPage);
}else {
_xDisplay.displayNoContentImage('plck_video_page_template_final');
}
_xDisplay.displayCommunityBadgeModule(response.VideoPage.NumberOfVideos, "videos");
  }
  break;
  case 'video-detail':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.Video != null) {
 _xDisplay.displayCommunityGroupVideoDetail(response.Video);
    } 
  }
  break;
  case 'sub-module-group-events':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.EventsPage.NumberOfEvents != "0") {
 _xDisplay.displayCommunityBadgeModule(response.EventsPage.NumberOfEvents, "events");
}

  }
  break;
  case 'sub-module-group-blogs':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.BlogPostPage.NumberOfBlogPosts != "0") {
 _xDisplay.displayCommunityGroupBlogs(response.BlogPostPage);
}else {
_xDisplay.displayNoContentImage('plck_blog_page_template_final');
}
_xDisplay.displayCommunityBadgeModule(response.BlogPostPage.NumberOfBlogPosts, "blogs");
  }
  break;
  case 'sub-module-group-forums':
    for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.ForumDiscussionsPage.NumberOfDiscussions != "0") {
//POST LAUNCH TODO :if time permits: Replace Forum template with DAPPI forums
 //_xDisplay.displayCommunityGroupForums(response.BlogPostPage);
}

_xDisplay.displayCommunityBadgeModule(response.ForumDiscussionsPage.NumberOfDiscussions, "forums");
  }
  break;
  
  case 'comments-yes-no':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = "";
var response = responseBatch.Responses[i];
if (response.CommentPage.NumberOfComments != "0") {
 _xDisplay.displayComments(response.CommentPage, response.CommentPage.ArticleKey.Key);
} 
else{
 _xDisplay.BeTheFirstToComment(response.CommentPage, response.CommentPage.ArticleKey.Key);
}
  }
  break;
 case 'user-activity-moderation':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.RecentUserActivity.UserActivities != null) {
 _xDisplay.displayUserActivity(response.RecentUserActivity.UserActivities, "plck_moderator_activity");
} 
  }
 
  break;
  case 'user-activity-membership-1':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.RecentUserActivity.UserActivities != null) {
 _xDisplay.displayUserActivity(response.RecentUserActivity.UserActivities, "plck_membership_user_activity_1");
} 
  }
 
  break;
  case 'user-activity-membership-2':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.RecentUserActivity.UserActivities != null) {
 _xDisplay.displayUserActivity(response.RecentUserActivity.UserActivities, "plck_membership_user_activity_2");
} 
  }
 
  break;

  case 'comments':
  for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommentPage.NumberOfComments != "0") {
 displayComments(response.CommentPage, null);
} 
  }
  break;
  case 'group-moderator-module':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.User.UserKey.Key != "0") {
 _xDisplayMiniModules.displayModeratorModule(response.User);
_xCore.getActivitiesForUser(response.User.UserKey.Key, "callbackUserActivityModeration");
} 
  }
 break;
  case 'similar-content-module':
   var l_aAvatarImageUrl = new Array();
   var l_aTitle = new Array();
   var l_aMemberCount = new Array();
   var l_aCommunityGroupUrl = new Array();
   var l_bSimilarContent = false;
   if (responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent != null) {
   l_bSimilarContent = true;
   for (var i = 0; i < responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent.length; i++) {
l_aAvatarImageUrl.push(responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent[i].AvatarImageUrl);
l_aTitle.push(responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent[i].Title);
l_aMemberCount.push(responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent[i].CommunityGroupStats.MemberCount);
l_aCommunityGroupUrl.push(responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent[i].CommunityGroupKey.Key);
   }
       if(l_bSimilarContent){
      _xDisplayMiniModules.displaySimilarContent(l_aAvatarImageUrl,l_aTitle,l_aMemberCount,l_aCommunityGroupUrl);
   }
   }

  break;
  case 'recent-events-mini-module':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.EventsPage.NumberOfEvents != "0") {
$('#plk-recent-events-module').removeClass("plk_always_hide");
_xDisplayMiniModules.displayEventsMiniModule(response.EventsPage);
}
  }
  break;
  case 'user-membership':
    for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroupMembershipPage.CommunityGroupMemberships != "0") {
 _xDisplayMiniModules.displayGroupMemberships(response.CommunityGroupMembershipPage);
    } 
  }
   
  break;
  case 'joined-group':
    for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroupMembershipKey.Key) {
    //remove join button
$('#plck_jointhisgroup').css('display','none');
//refresh newest members module
if($('#plck-group-key-set').html()){
_xCore.getGroupMembershipPage($('#plck-group-key-set').html(), 2, 1, "TimeStampDescending");
    //refresh stats module
_xCore.getStats($('#plck-group-key-set').html(), "community");
}
//alert("Thank you for joining this group!");

} 
  }
  break;
  case 'user-avatar-photo':
    for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.User.UserKey.Key != "0") {
 _xDisplay.displayAvatarPhoto(response.User.AvatarPhotoUrl);
} 
}
  break;

}

}

 };
 
 
 ////////HANDLE FORM UPDATES CALLBACK/////////////////////
 //////////////////////////////////////////////////
 function callbackUpdateCommunityGroup(p_xResponsebatch){
       _xUpdateFormsCallback.callback('update-community-group',p_xResponsebatch);
}

function callbackUpdateBlog(p_xResponsebatch){
_xUpdateFormsCallback.callback('update-blog',p_xResponsebatch);
}

function callbackUpdateGallery(p_xResponseBatch){
_xUpdateFormsCallback.callback('update-gallery',p_xResponseBatch);
}

function callbackUpdateGroupSubModuleEvents(p_xResponseBatch){
 _xUpdateFormsCallback.callback('update-community-event',p_xResponseBatch);
}

function callbackUpdateForumPost(p_xResponsebatch){
     _xUpdateFormsCallback.callback('update-forum-post',p_xResponsebatch);
}

function callbackAddForumPost(p_xResponsebatch){
     _xCallback.callback('add-forum-post',p_xResponsebatch);
}

_xUpdateFormsCallback = {
callback:function(p_sType,responseBatch){
//console.log(responseBatch);

if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

 switch (p_sType){
case 'update-community-group':
      for (var i = 0; i < responseBatch.Responses.length; i++) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') {
}else{
$('#asseteditor_content').removeClass('asseteditor_content').addClass('plk_always_hide');
$('#asseteditor').addClass('image_error');
handleErrors(responseBatch);
}

var response = responseBatch.Responses[i];
if (response.CommunityGroupKey.Key != null) {
 $('#groupeditor_content').removeClass('groupeditor_content').addClass('plk_always_hide');
$('#groupeditor').addClass('thankyou_generic');
alert("Thank you!! Your group is created! Taking you to your group");
_xCore.pageRedirect("/community/group/" + response.CommunityGroupKey.Key + "/");
} 
}
break;
case 'update-blog':
  alert("Your Blog is updated/created Successfully!");
break;
case 'update-community-event':
  alert("Your Event is updated/created Successfully!");
break;
case 'update-gallery':
  alert("Your Gallery is updated/created Successfully!");
break;
case 'update-forum-post':
      alert("Forum Post is successfully updated");
break;
case 'add-forum-post':
      alert("Forum Post is successfully added");
break;
 }
}
};
 
 
 
 
 ////////HANDLE FORMS EDIT CALLBACK////////////////
 //////////////////////////////////////////////////
function callbackEditGroupEvent(p_xResponseBatch){
                _xEditFormsCallback.callback('edit-group-event',p_xResponseBatch);
}

function callbackEditBlog(p_xResponseBatch){
                _xEditFormsCallback.callback('edit-blog',p_xResponseBatch);
}

function callbackEditGroup(p_xResponseBatch){
                _xEditFormsCallback.callback('edit-group',p_xResponseBatch);
}

function callbackEditGroup(p_xResponseBatch){
                _xEditFormsCallback.callback('edit-group',p_xResponseBatch);
}


function callbackEditPhoto(p_xResponseBatch){
                _xEditFormsCallback.callback('edit-photo',p_xResponseBatch);
}





_xEditFormsCallback = {
callback:function(p_sType,responseBatch){
//console.log(responseBatch);

if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

 switch (p_sType){
case 'edit-group-event':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.Event.EventKey != null) {
postEventData(response.Event);
} 
 }
 break;
case 'edit-blog':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.BlogPost.BlogPostKey != null) {
postBlogData(response.BlogPost);
} 
 }
 break;
 case 'edit-group':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey != null) {
postGroupData(response.CommunityGroup);
} 
 }
 break;
 case 'edit-photo':
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.Photo.PhotoKey != null) {
postPhotoData(response.Photo);
} 
 }
 break;
 
 
 
 
 
 }
}
};


//////HANDLE FUNCTION CALLBACK/////////////
///////////////////////////////////////////
_xHandleFunctionCallback = {
callback:function(p_sType,responseBatch){
//console.log(responseBatch);

if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

 switch (p_sType){
case 'get-upcoming-events-module':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.EventSetKey != null) {
 getUpcomingEventsModule(response.CommunityGroup.EventSetKey.Key);
    } 
  }
   
break;
case 'group-id-set':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
 $('#plck-group-photo-gallery-key-set').html(response.CommunityGroup.PhotoGalleryKey.Key);
$('#plck-group-video-gallery-key-set').html(response.CommunityGroup.VideoGalleryKey.Key);
$('#plck-group-event-set-key-set').html(response.CommunityGroup.EventSetKey.Key);
$('#plck-group-blog-key-set').html(response.CommunityGroup.BlogKey.Key);
$('#plck-group-forum-key-set').html(response.CommunityGroup.ForumKey.Key)
$('#plck-group-owner-key-set').html(response.CommunityGroup.Owner);
$('#plck-group-key-set').html(response.CommunityGroup.CommunityGroupKey.Key);
$('#plck-group-membership-tier').html(response.CommunityGroup.RequestingUsersMembershipTier);

} 
  }
   
break;
case 'photo-detail-id-set':
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.EventSetKey != null) {
 setNumberOfComments(response.Photo.NumberOfComments);
    } 
  }
break;
case 'moderator-info':
        for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
  _xCommunity.getModeratorInfo(response.CommunityGroup.Owner);
}
}
break;
case 'similar-content-info':
           //get page type
   //TODO: FIND BETTER WAY OF GETTING GET VALUES
   var l_aGet = window.location.href.split("/");
   var l_sPageType = l_aGet[6];
   for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
  _xCommunity.getSimilarContent(response.CommunityGroup.Categories, response.CommunityGroup.Section, l_sPageType);
}
}
break;
    case 'recent-events-info':
           for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
  _xCommunityEvents.getRecentEventsMiniModule(response.CommunityGroup.EventSetKey.Key, 2, 1, "TimeStampDescending");
}
}
break;
case 'group-membership':
          for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.CommunityGroupKey.Key != null) {
  _xCore.getGroupMembershipPage(response.CommunityGroup.CommunityGroupKey.Key, 2, 1, "TimeStampDescending");
}
}
break;


}


}
};


function customCallbackForPhotoDetail(p_xResponseBatch){
        if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}
 for (var i = 0; i < responseBatch.Responses.length; i++) {
var response = responseBatch.Responses[i];
if (response.CommunityGroup.EventSetKey != null) {
 setGroupOwnerKey(response.CommunityGroup.Owner);
    } 
 }

}

function callbackHandleCommentUrlFromUserPersona(responseBatch){
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}
//parse community key and get article key and type
var response = responseBatch.Responses[0].Comment;
var l_sCommunityKey = response.CommentedOnKey;
var l_aCommunityKey = l_sCommunityKey.split("_");
var l_sArticleKey = l_aCommunityKey[0];
var l_sArticleItemType = l_aCommunityKey[1]; 

if(g_aPluckArticleItemTypes[l_sArticleItemType]){
   window.location.href = "/community/"+g_aPluckArticleItemTypes[l_sArticleItemType]+"/"+l_sArticleKey+"/";
} else {
   window.location.href = "/community/";
}
}

function callbackArticleExists(p_xResponseBatch){
   if (p_xResponseBatch.Messages.length == 1 && p_xResponseBatch.Messages[0].Message == 'ok'){
    for (var i = 0; i < p_xResponseBatch.Responses.length; i++) {
var response = p_xResponseBatch.Responses[i];
if (response.Article.ArticleKey != null) {
 _xDisplay.displayArticleDetail(response);
    } 
}

   }else{
    //call update Article here: 
//FOR DEBUG:
//alert(l_sCMSArticleSlug); //=> From CMS Data
//alert(l_sCMSArticleTitle); //=> From CMS Data
//alert(l_aCMSArticleIds["yes"]); //=> From _xCore.getYesNoCommentIds
    //alert(l_aCMSArticleIds["no"]); //=> From _xCore.getYesNoCommentIds
//alert(l_aCMSArticleIds["article_key"]); //=> From _xCore.getYesNoCommentIds
    //alert(l_sCMSArticleSection); //=>From Article Template
//alert(l_aCMSArticleTags); // =>From Article Template
if(document._bArticleFromShows){
 _xCore.updateArticle(document.l_aCMSArticleIds["yes"], document.l_sCMSArticleSlug, "I'm in! ... "+document.l_sCMSArticleTitle, document.l_sCMSArticleSection, document.l_aCMSArticleTags);
_xCore.updateArticle(document.l_aCMSArticleIds["no"], document.l_sCMSArticleSlug, "No Way! ... "+document.l_sCMSArticleTitle, document.l_sCMSArticleSection, document.l_aCMSArticleTags);
_xCore.updateArticle(document.l_aCMSArticleIds["article_key"], document.l_sCMSArticleSlug, document.l_sCMSArticleTitle, document.l_sCMSArticleSection, document.l_aCMSArticleTags);
 document._bArticleFromShows = false;
 
}
}
}

function callbackUpdateArticleForItems(p_xResponseBatch){
 if (p_xResponseBatch.Messages.length == 1 && p_xResponseBatch.Messages[0].Message == 'ok'){
    for (var i = 0; i < p_xResponseBatch.Responses.length; i++) {
var response = p_xResponseBatch.Responses[i];
if (response.Article.ArticleKey != null) {
 _xDisplay.displayArticleDetail(response);
    } 
}

   }else{
   _xDisplay.displayArticleDetailFake();
}

}
 
 
 
 

         
_xCore = {
 getStats: function(p_sKey, p_sType){
 switch(p_sType){
case 'community':
var p_sStatKey = new CommunityGroupKey(p_sKey);
break;
case 'events':
var p_sStatKey = new EventSetKey(p_sKey);
break;
case 'forum':
var p_sStatKey = new ForumKey(p_sKey);
break;
case 'photo':
var p_sStatKey = new GalleryKey(p_sKey);
break;
case 'video':
var p_sStatKey = new GalleryKey(p_sKey);
break;
case 'blog':
   var p_sStatKey = new BlogKey(p_sKey);
break;
}
sendToServer(p_sStatKey, callbackGroupStatsModule);
 },
 getUserInfo:function(p_sUserKey){
    var p_sUserKeyAction = new UserKey(p_sUserKey);
return p_sUserKeyAction;
 }, 
 
  updateArticle: function(p_sArticleKey, p_nOnPageUrl, p_nOnPageTitle, p_sSection, p_sCategories){
  if(p_sCategories.indexOf(",") == -1){
var l_aArticleCategories = new Category(p_sCategories);
}else{
l_aCategories = p_sCategories.split(",");
var l_aArticleCategories = new Array();
for(var i = 0; i < l_aCategories.length; i++){
l_aArticleCategories[i] = new Category(l_aCategories[i]);
      }
}
   
var updateArticleAction = new UpdateArticleAction(new ArticleKey(p_sArticleKey), p_nOnPageUrl, p_nOnPageTitle, new Section(p_sSection),l_aArticleCategories);
sendToServer(updateArticleAction, callbackGeneric);
  },
 
 sendEmailViaPluck: function(){
       //Sample for testing
   //requestBatch.AddToRequest(new EmailContentAction("vishal@codeandtheory.com", "An interesting gallery", "Hello, Joe! One of our users thought you would like this gallery:http://www.newspaper.com/galleries/puppies"));  
   var l_sTo = $('#to').val();
   var l_sEmailSplit = l_sTo.split(",");
   for(var i=0; i<l_sEmailSplit.length;i++){
   var l_sToEach = l_sEmailSplit[i];
var l_sSubject = $('#subject').val();
   var l_sUserBody = $('#user_body').val();
   var l_sVersusBody = $('#versus_body').val();
   var l_sBody = l_sVersusBody+"'"+l_sUserBody+"'";
   var emailAction = new EmailContentAction(l_sToEach, l_sSubject, l_sBody);  
   sendToServer(emailAction, callbackEmailSent);
   }
   },
 
 ///////////////Search/////////////////////////
/////////////////////////////////////////////
discoverContent:function(p_sSections, p_sCategories, p_sActivity, p_sContentType, p_nAge, p_nNumItemsToGet){

var l_aSearchSections = p_sSections;

if(p_sCategories.indexOf(",") == -1){
var l_aSearchCategories = new Category(p_sCategories);
}
else{
p_aCategories = p_sCategories.split(",");
var l_aSearchCategories = new Array();
for(var i = 0; i < p_aCategories.length; i++){
l_aSearchCategories[i] = new Category(p_aCategories[i]);
}
 
}

var l_aSearchContributors = new Array();    
l_aSearchContributors[0] = new UserTier("Standard");    
l_aSearchContributors[1] = new UserTier("Staff");    
l_aSearchContributors[2] = new UserTier("Editor");  

var l_sActivity = new Activity(p_sActivity);
var l_sContentType = new ContentType(p_sContentType);
var l_nAge = p_nAge;    
var l_nNumItemsToGet = p_nNumItemsToGet; 


var discoveryAction = new DiscoverContentAction(l_aSearchSections,
l_aSearchCategories,
l_aSearchContributors,    
l_sActivity,  
l_sContentType,
l_nAge,    
l_nNumItemsToGet);

return discoveryAction;
},
 
 pageRedirect: function(l_sSlug){
 window.location.href = l_sSlug;
 },
 
 updateCommunityGroup: function(l_sCommunityGroupKey){
  if(_xValidate.validateCreateGroupForm()){
if(l_sCommunityGroupKey != "null"){
var groupKey = l_sCommunityGroupKey;
}else{
var groupKey = null;
}

var title = $('#title').val();
var description = $('#desc').val();
var tags = $('#tags').val();


if($('#group_section_list').val() == "Own"){
          var section = $('#user_own_section_text').val();
}else{
var section = $('#group_section_list:selected').text(); 
}

var photoKey = $('#avatarphotokey').html();

var createGroupAction = updateCommunityGroup(groupKey, title, description, tags, "Public", "bookmark", section, photoKey);
sendToServer(createGroupAction, callbackUpdateCommunityGroup);
}
  }, 

   updateCommunityBlog: function(l_sBlogKey){
           if(_xValidate.validateBlogForm()){     
var title = $('#title').val();
var description = $('#desc').val();
var tags = $('#tags').val();
var published = $('#create_blog_list').val();
var updateBlogAction = updateBlogPost(l_sBlogKey,title,description,tags,published, "new");
      sendToServer(updateBlogAction, callbackUpdateBlog);
   }
   }, 
   
   updateGroupEvent: function(l_sEventKey){
      if(_xValidate.validateEventForm()){  
var l_sTitle = $('#title').val();
var l_sDescription = $('#desc').val();
var l_sLocation = $('#loc').val();
var l_sStartDate = $('#start_time_picker').val();
var l_sEndDate = $('#end_time_picker').val();
var l_sStartTime = $('#start_time_entry').val();
var l_sEndTime = $('#end_time_entry').val();
var l_sBookmarkname = $('#name').val();
var l_sBookmarklink = $('#url').val();
var l_sStartDateTime = ""+l_sStartDate+" "+l_sStartTime+" GMT";
var l_sEndDateTime = ""+l_sEndDate+" "+l_sEndTime+" GMT";
var UTCOffset = 0;

    var updateEventAction = updateEvent(l_sEventKey, l_sTitle, l_sDescription, l_sLocation, l_sBookmarkname,l_sBookmarklink, l_sStartDateTime, l_sEndDateTime, "new");
    sendToServer(updateEventAction, callbackUpdateGroupSubModuleEvents);
}
   }, 
   
   checkUser: function(l_sUserKey){
            var l_sUserInstKey = new UserKey(l_sUserKey);
sendToServer(l_sUserInstKey, callbackUserExists);
   }, 
   
   checkIfArticleExists: function(p_sArticleKey){
     var articleAction = new ArticleKey(p_sArticleKey);
      sendToServer(articleAction, callbackArticleExists);
    },

   getActivitiesForUser: function(p_sUserKey){
   var userActivityAction = new RecentUserActivity(new UserKey(p_sUserKey));
   sendToServer(userActivityAction, callbackUserActivityModeration);
   },
   
   getActivitiesForUserMembershipOne: function(p_sUserKey){
   var userActivityAction = new RecentUserActivity(new UserKey(p_sUserKey));
   sendToServer(userActivityAction, callbackUserActivityMembershipOne);
   },
   
   getActivitiesForUserMembershipTwo: function(p_sUserKey){
   var userActivityAction = new RecentUserActivity(new UserKey(p_sUserKey));
   sendToServer(userActivityAction, callbackUserActivityMembershipTwo);
   },
   
   
   
   getGroupMembershipPage: function(l_sCommunityKey, l_sNumberPerPage, l_sOnPage, l_sSortBy){
       var membershipAction = new CommunityGroupMembershipPage(new CommunityGroupKey(l_sCommunityKey), l_sNumberPerPage, l_sOnPage, l_sSortBy);
   sendToServer(membershipAction, callbackCommunityUserMembership);
   }, 
   
   requestCommunityGroupMembership: function(p_sCommunityKey, p_sUserKey){
    var inviteAction = new RequestCommunityGroupMembershipAction(new CommunityGroupKey(p_sCommunityKey),  new UserKey(p_sUserKey));  
sendToServer(inviteAction, callbackJoinedGroup);
  }, 
  
  requestCommunityGroupMembershipOnRegistration: function(p_sCommunityKey, p_sUserKey){
      var inviteAction = new RequestCommunityGroupMembershipAction(new CommunityGroupKey(p_sCommunityKey),  new UserKey(p_sUserKey));  
  sendToServer(inviteAction, callbackGeneric);
  }, 
  
  getVideoDetail: function(p_sVideoKey){
var videoKeyAction = new VideoKey(p_sVideoKey);
sendToServer(videoKeyAction, callbackVideoDetail);
  }, 
  
  getPhotoDetail: function(p_sPhotoKey){
var photoKeyAction = new PhotoKey(p_sPhotoKey);
sendToServer(photoKeyAction, callbackPhotoDetail);
  },
  
   getYesNoCommentIds: function(l_sArticleId, l_sCMSItemType){
   
//TODO:Obfuscate the Article Keys as they are too transparent and can cause security issues.
var l_sConstructArticleKey = ""+l_sArticleId+""+g_sDelimiter+""+l_sCMSItemType+""+g_sDelimiter+"";
var l_sConstructYesKey = ""+l_sArticleId+""+g_sDelimiter+""+l_sCMSItemType+""+g_sDelimiter+""+ g_sYesKey +"";
var l_sConstructNoKey = ""+l_sArticleId+""+g_sDelimiter+""+l_sCMSItemType+""+g_sDelimiter+""+ g_sNoKey +"";

var l_aYesNoCommentIds = new Array();
l_aYesNoCommentIds["article_key"] = l_sConstructArticleKey;
l_aYesNoCommentIds["yes"] = l_sConstructYesKey;
l_aYesNoCommentIds["no"] =  l_sConstructNoKey;

return l_aYesNoCommentIds;
   
  }
  
  
};


_xServer = {
       
   sendMultipleRequestsToServer: function(l_aRequests){
   for(i = 0; i < l_aRequests.length; i++){
 requestBatch.AddToRequest(l_aRequests[i]);
   }
      requestBatch.BeginRequest(g_xServerUrl, l_xCallbackFunction);
   }
}

_xUtils = {
        displayModifiedDate: function(p_sDate){
   l_aMonths = new Array("Zero", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")

   l_sYear = p_sDate;
   l_sYearSplit = l_sYear.split("/");
   l_sPluckMonth = l_sYearSplit[0];
   l_sMonth = l_aMonths[l_sPluckMonth];
   l_sPluckYearTime = l_sYearSplit[2].split(" ");
   l_sYear = l_sPluckYearTime[0];
   l_sModifiedTime = ""+ l_sYearSplit[1] +" "+ l_sMonth +", "+ l_sYear +"";

return l_sModifiedTime;
}

}

_xPluckUser = {
       getAvatarPhoto: function(p_sUserKey){
      var userInfoAction = _xCore.getUserInfo(p_sUserKey);
  sendToServer(userInfoAction, callbackUserAvatarPhoto);
   }
}


     
function isArray( obj ) {
    return toString.call(obj) === "[object Array]";
}



function sendToServer(l_sRequest, l_sCallbackFunction){
    var requestBatch = new RequestBatch();   
requestBatch.AddToRequest(l_sRequest);     
requestBatch.BeginRequest(g_xServerUrl, l_sCallbackFunction);
}




////////////////Forums///////////////////////////
/////////////////////////////////////////////////
function updateForumDiscussion(p_sForumKey, p_sTitle, p_sDesc, p_sIsQuestion, p_sSection, p_sCategory, p_sPoll){
var l_sForumKey = new ForumKey(p_sForumKey);
var l_sTitle = p_sTitle;
var l_sDesc = p_sDesc;
var l_sIsQuestion = p_sIsQuestion;
var l_sSection = p_sSection;
var l_sCategory = p_sCategory;
var l_sPoll = p_sPoll;

var updateForumDiscussionAction = new UpdateForumDiscussionAction(new ForumKey(l_sForumKey), l_sTitle, l_sDesc, l_sIsQuestion, l_sSection, l_sCategory, l_sPoll);

return updateForumDiscussionAction;

}

function addForumDiscussionPost(p_sDiscussionKey, p_sTitle, p_sDesc, p_sIsQuestion){
var l_sDiscussionKey = new DiscussionKey(p_sDiscussionKey);
var l_sTitle = p_sTitle;
var l_sDesc = p_sDesc;
            var l_sIsQuestion = p_sIsQuestion;

var addForumPostAction = new UpdateForumPostAction(l_sDiscussionKey, l_sTitle, l_sDesc, l_sIsQuestion)

return addForumPostAction;

}

function updateForumDiscussionPost(p_sForumPostKey, p_sTitle, p_sDesc, p_sIsQuestion){
var l_sForumPostKey = new ForumPostKey(p_sForumPostKey);
var l_sTitle = p_sTitle;
var l_sDesc = p_sDesc;
            var l_sIsQuestion = p_sIsQuestion;

var editForumPostAction = new UpdateForumPostAction(l_sForumPostKey, l_sTitle, l_sDesc, l_sIsQuestion)

return editForumPostAction;
}

function getCommunityForumsPage(p_sCommunityForumKey, p_nNoPerPage, p_nOnPage, p_sSort){
var l_sCommunityForumKey = new ForumKey(p_sCommunityForumKey); 
var getForumsAction = new ForumDiscussionsPage(l_sCommunityForumKey, p_nNoPerPage, p_nOnPage, p_sSort);
return getForumsAction;
}


////////////////////Blogs///////////////////////
////////////////////////////////////////////////
function updateBlogPost(p_xBlogKey,p_sTitle,p_sDescription,p_sTags,p_sPublished, p_sActionType){
   if (p_sActionType == "update"){ 
var l_xBlogKey = new BlogPostKey(p_xBlogKey);
   }else{
var l_xBlogKey = new BlogKey(p_xBlogKey);
   }
var l_sTitle = p_sTitle;
var l_sDescription = p_sDescription;
var l_sTags = p_sTags;
var l_sPublished = p_sPublished;
var l_sPostDate = new Date();
            var l_sGMTPostDate = l_sPostDate.toGMTString();

var updateBlogPostAction = new UpdateBlogPostAction(l_xBlogKey,l_sTitle,l_sDescription,l_sTags, l_sGMTPostDate, l_sPublished)

return updateBlogPostAction;
}

function getCommunityBlogsPage(p_sCommunityBlogKey, p_nNoPerPage, p_nOnPage, p_sSort){
var l_sCommunityBlogKey = new BlogKey(p_sCommunityBlogKey); 
var getBlogsAction = new BlogPostPage(l_sCommunityBlogKey, p_nNoPerPage, p_nOnPage, p_sSort);
return getBlogsAction;
}

/////////////////Gallery////////////////////////
////////////////////////////////////////////////
function updateGallery(p_sGalleryKey, p_sGalleryType, p_sMediaType, p_sTitle,  p_sDesc, p_sTags, p_sSection){
var l_sGalleryKey = new GalleryKey(p_sGalleryKey);
var l_sGalleryType = new GalleryType(p_sGalleryType);
var l_sMediaType = new MediaType(p_sMediaType);
var l_sTitle = p_sTitle;
var l_sDesc = p_sDesc;
var l_sTags = p_sTags;
var l_sSection = new Section(p_sSection);

var updateAction = new UpdateGalleryAction(l_sGalleryKey, l_sGalleryType, l_sMediaType, l_sTitle, l_sDesc, l_sTags, l_sSection);
return updateAction;
}

function publicGalleryPage(p_nNoPerPage, p_nOnPage, p_sMediaType){
    var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;
var l_sMediaType = new MediaType(p_sMediaType);

var pageAction = new PublicGalleryPage(l_nNoPerPage, l_nOnPage, l_sMediaType);
return pageAction;
}

////////////////////Videos/////////////////////
//////////////////////////////////////////////
function getCommunityGroupPhotos(p_sGroupPhotoKey, p_nNoPerPage, p_nOnPage, l_sSortBy){
var l_sGroupPhotoKey = new GalleryKey(p_sGroupPhotoKey);
var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;

var photoKeyAction = new PhotoPage(l_sGroupPhotoKey, l_nNoPerPage, l_nOnPage, l_sSortBy);
return photoKeyAction;
}


///////////////////Photos/////////////////////
//////////////////////////////////////////////
function getCommunityGroupVideos(p_sGroupVideoKey, p_nNoPerPage, p_nOnPage, l_sSortBy){
var l_sGroupVideoKey = new GalleryKey(p_sGroupVideoKey);
var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;

var videoKeyAction = new VideoPage(l_sGroupVideoKey, l_nNoPerPage, l_nOnPage, l_sSortBy);
return videoKeyAction;
}

function editPhoto(p_sPhotoKey){
var photoKeyAction = new PhotoKey(p_sPhotoKey);
sendToServer(photoKeyAction, callbackEditPhoto);

}


//////////////////Recommend//////////////////
/////////////////////////////////////////////
function recommend(p_sKey, p_sType, f) {
  if(_xUser.getCookie("")){
 var l_bEnableFireUpCount = true;
 document._xRecommend = f;
  switch(p_sType){ 
   case 'blog-post':
var recKey = new BlogPostKey(p_sKey);
   break;
   case 'photo':
   document._xIncrementRecommend = true;
var recKey = new PhotoKey(p_sKey);
   break;
   case 'video':
   document._xIncrementRecommend = true;
var recKey = new VideoKey(p_sKey);
   break;
   case 'comment':
var recKey = new CommentKey(p_sKey);
   break;
   case 'review':
var recKey = new ReviewKey(p_sKey);
   break;
   case 'gallery':
var recKey = new GalleryKey(p_sKey);
   break;
   case 'article':
 if(document._xIncrementRecommend != false || document._bIncrementRecommendForShows == true){
 document._xIncrementRecommend = true;
 var recKey = new ArticleKey(p_sKey);
 } else {
 l_bEnableFireUpCount = false;
 }
   break;
}
   
   if(l_bEnableFireUpCount){
var recommendAction = new RecommendAction(recKey);
sendToServer(recommendAction, callbackRecommend);
   }
  // var recommendAction = new RecommendAction(recKey);
   //return recommendAction;
   //sendToServer(recommendAction, callbackRecommend);
  }else{
    _xTruebox._sUserFiresUp = true;
_xTruebox._sRecommendationKey = p_sKey;
_xTruebox._sRecommendationType = p_sType;
_xTruebox._sRecommendationLoc = f;
  _xTruebox.makeSignupRegister();
    }
   
}

/////////////////////Report Abuse///////////////
////////////////////////////////////////////////
function reportAbuse(p_sKey, p_sReason, p_sDesc, p_sKeyType, f){
document._xAbuse = f;
switch(p_sKeyType){
case 'comment':
    var abuseKey = new CommentKey(p_sKey);
break;
case 'community':
    var abuseKey = new CommunityGroupKey(p_sKey);
break;
}
  
   var abuseAction = new ReportAbuseAction(abuseKey, p_sReason, p_sDesc);
   //return abuseAction;
    sendToServer(abuseAction, callbackReportAbuse);
}

/////////////////////Comments///////////////////
////////////////////////////////////////////////
function makeComment(p_nKey, p_sPageUrl, p_sPageTitle, p_sCommentBody, p_sKeyType){
 if(_xUser.getCookie("")){
if(!document._nCommentSent){
document._nCommentSent = p_nKey;
var p_sCommentBody = document.getElementById("plck_comment_body").value;

if(p_sCommentBody == "Type your smack here..." || p_sCommentBody == ""){
 return;
}


switch (p_sKeyType){
case 'article':
commentKey = new ArticleKey(p_nKey);
break;
case 'gallery':
commentKey = new GalleryKey(p_nKey);
break;
case 'photo':
commentKey = new PhotoKey(p_nKey);
break;
case 'video':
commentKey = new VideoKey(p_nKey);
break;
case 'blogpost':
commentKey = new BlogPostKey(p_nKey);
break;
}

var commentAction = new CommentAction(commentKey, p_sPageUrl, p_sPageTitle, p_sCommentBody); 
sendToServer(commentAction, callbackActionYesNoComments);
//call update article
updateArticle(commentKey, p_sPageUrl, p_sPageTitle, "", "");
}
}
else{
_xTruebox.makeSignupRegister();
}
}

function getComments(p_nKey, p_nNoPerPage, p_nOnPage, p_sSortType, p_sFindCommentKey, p_sKeyType, p_bNotPagination){
           if(p_bNotPagination == true){
document._xPluckIsNotPagination = true;
}else{
document._xPluckIsNotPagination = false;
}

switch (p_sKeyType){
case 'article':
var commentKey = new ArticleKey(p_nKey);
break;
case 'gallery':
var commentKey = new GalleryKey(p_nKey);
break;
case 'photo':
var commentKey = new PhotoKey(p_nKey);
break;
case 'video':
var commentKey = new VideoKey(p_nKey);
break;
case 'blogpost':
var commentKey = new BlogPostKey(p_nKey);
break;
}

var commentPageAction = new CommentPage(commentKey, p_nNoPerPage, p_nOnPage, p_sSortType,  p_sFindCommentKey);  
if(p_sKeyType == "article"){
sendToServer(commentPageAction, callbackCommentsYesNo);
}else{
sendToServer(commentPageAction, callbackComments);
}


}

/////////////////////Article////////////////////
////////////////////////////////////////////////
function getArticle(p_sArticleKey){
     var articleAction = new ArticleKey(p_sArticleKey);
     sendToServer(articleAction, callbackGeneric);
}

function updateArticle(p_sArticleKey, p_nOnPageUrl, p_nOnPageTitle, p_sSection, p_aCategories){
var updateArticleAction = new UpdateArticleAction(p_sArticleKey, p_nOnPageUrl, p_nOnPageTitle, new Section(p_sSection),p_aCategories);
sendToServer(updateArticleAction, callbackGeneric);
}

/////////////////////Community//////////////////
////////////////////////////////////////////////
function updateCommunityGroup(p_xCommunityKey, p_sTitle, p_sDescription, p_sTags, p_sVisibility, p_sBookMarks, p_sSections, p_xPhotoKey){
        if(p_xCommunityKey != null){
var l_xCommunityKey = new CommunityGroupKey(p_xCommunityKey);
}else{
var l_xCommunityKey = p_xCommunityKey;
}

var l_sTitle = p_sTitle;
var l_sDescription = p_sDescription;
var l_sTags = p_sTags;
var l_sVisibility = new CommunityGroupVisibility(p_sVisibility);  
var l_sBookMarks = new Bookmark(p_sBookMarks);
var l_sSections = new Section(p_sSections);
var l_xPhotoKey = new PhotoKey(p_xPhotoKey);

var updateGroupAction = new UpdateCommunityGroupAction(l_xCommunityKey, l_sTitle, l_sDescription, l_sTags, l_sVisibility, l_sBookMarks, l_sSections, l_xPhotoKey);

return updateGroupAction;
}

function editCommunityGroup(p_sCommunityGroupKey){
formHTML = displayGroupForm();
document.getElementById('thickbox').innerHTML = formHTML;
sendToServer(new CommunityGroupKey(p_sCommunityGroupKey), callbackEditGroup);
}

function getCommunity(p_xCommunityKey){
      var l_xCommunityGroupKeyAction = new CommunityGroupKey(p_xCommunityKey);
  return l_xCommunityGroupKeyAction;
}

function getCommunityGroupPage(p_nNoPerPage, p_nOnPage, p_sSectionName, p_sSortType){
var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;
var l_sSectionName =  p_sSectionName;
var l_sSortType = p_sSortType;

var communityGroupPageAction = new CommunityGroupPage(l_nNoPerPage, l_nOnPage, l_sSortType, l_sSectionName);

return communityGroupPageAction;
}


function recentFeedActivity(_xCommunityGroupKey, p_nOnPage, p_nNoPerPage){
var _xCommunityGroupKey = new CommunityGroupKey(_xCommunityGroupKey);
var l_nOnPage = p_nOnPage;
var l_nNoPerPage = p_nNoPerPage;
var recentMiniFeedActivity = new RecentMiniFeedActivity(_xCommunityGroupKey, l_nOnPage, l_nNoPerPage);
return recentMiniFeedActivity;
}

//Post Edit Community Events:
function updateEvent(p_xEventKey,p_sTitle,p_sDescription,p_sLocation, p_sBookmarkName, p_sBookmarkLink, p_sStartDate,p_sEndDate, p_sActionType){
if (p_sActionType == "update"){ 
var l_xEventKey = new EventKey(p_xEventKey);
}else{
var l_xEventKey = new EventSetKey(p_xEventKey);
}
var l_sTitle = p_sTitle;
var l_sDescription = p_sDescription;
var l_sLocation = p_sLocation;
var l_sBookmarkName = p_sBookmarkName;
var l_sBookmarkLink = p_sBookmarkLink;
var l_sStartDate = p_sStartDate;
var l_sEndDate = p_sEndDate;
var UTCOffset = 0;

var updateEventAction = new UpdateEventAction(l_xEventKey, l_sTitle, l_sDescription, l_sLocation, l_sBookmarkName, l_sBookmarkLink , l_sStartDate, l_sEndDate, UTCOffset);  

return updateEventAction;
}

 function searchCommunityGroup(p_sCommunityGroupKey, p_sSearchType, p_sSearchString, p_nNoPerPage, p_nOnPage ){
var l_sCommunityGroupKey = new CommunityGroupKey(p_sCommunityGroupKey); //f0e71460-8b4b-493d-9620-aea11b58c0b6
var l_sSearchType = p_sSearchType;  
var l_sSearchString = p_sSearchString; 
var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;

var searchAction = new CommunityGroupSearchAction(l_sCommunityGroupKey, l_sSearchType,l_sSearchString, l_nNoPerPage, l_nOnPage);  
return searchAction;

}

function getCommunityGroupStats(p_sCommunityGroupKey){
    var l_sCommunityGroupKey = new CommunityGroupKey(p_sCommunityGroupKey); 
var statsAction = l_sCommunityGroupKey; 
return statsAction;
 
}




function getCommunityEventsPage(p_sCommunityEventKey, p_sStartDate, p_sEndDate, p_nNoPerPage, p_nOnPage, p_sSortBy){
var l_sCommunityEventKey = new EventSetKey(p_sCommunityEventKey);
var l_sStartDate = p_sStartDate;
var l_sEndDate = p_sEndDate;
var l_nNoPerPage = p_nNoPerPage;
var l_nOnPage = p_nOnPage;

var getEventsAction = new EventsPage(l_sCommunityEventKey, l_sStartDate, l_sEndDate, l_nNoPerPage, l_nOnPage, p_sSortBy);

return getEventsAction;

}

////////////Forms and Moderation////////////
//////////////////////////////////
//Invite User
function addUserToCommunityGroup(p_sCommunityKey){
formHTML = requestCommunityGroupMembershipForm(p_sCommunityKey);
document.getElementById('thickbox').innerHTML = formHTML;
}



//Report Abuse:
function reportAbuseAction(l_sCommunityKey,  p_sType){
formHTML = reportAbuseForm(l_sCommunityKey, p_sType);
document.getElementById('thickbox').innerHTML = formHTML;
}

function reportGroupAbuse(p_sKey, p_sKeyType){
var p_sReason = document.getElementById("reason").value;
var p_sDesc = document.getElementById("description").value;

switch(p_sKeyType){
case 'comment':
    var abuseKey = new CommentKey(p_sKey);
break;
case 'community':
    var abuseKey = new CommunityGroupKey(p_sKey);
break;
}
  
   var abuseAction = new ReportAbuseAction(abuseKey, p_sReason, p_sDesc);
   //return abuseAction;
    sendToServer(abuseAction, callbackGeneric);
}

function requestGroupDeleteAction(l_sCommunityKey){
formHTML = requestGroupDeleteForm(l_sCommunityKey);
document.getElementById('thickbox').innerHTML = formHTML;
}

function requestGroupDelete(l_sCommunityKey){
var p_sReason = document.getElementById("reason").value;
var requestGroupDeleteAction = RequestDeleteCommunityGroupAction(l_sCommunityKey, p_sReason);  
sendToServer(requestGroupDeleteAction, callbackGeneric);
}

function updateCommunityGroupMembership(l_sCommunityKey, l_sUserKey, l_sMembershipTier, l_sIsBanned){
     var updateGroupMembershipAction = new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(l_sCommunityKey), new UserKey(l_sUserKey), new MembershipTier(l_sMembershipTier), l_sIsBanned);
 sendToServer(updateGroupMembershipAction, callbackGeneric);
}

function updateGroupAction(l_sCommunityGroupKey){
formHTML = displayGroupForm(l_sCommunityGroupKey);
document.getElementById('thickbox').innerHTML = formHTML;
if(l_sCommunityGroupKey != null){
sendToServer(new CommunityGroupKey(l_sCommunityGroupKey), callbackEditGroup);
}
}


   function generateImageFromText(l_sText, l_sColor, l_sBg){
   var l_aTextInfo = { c:''+l_sColor+'',type:'b','bg':''+l_sBg+'',tran:true,s:20,t:l_sText, js:true }
var l_simagEd = makeCustomImage(l_aTextInfo);
return l_simagEd;
   }


function updateEventAction(l_sEventKey, p_sType){
formHTML = displayEventForm(l_sEventKey, p_sType);
document.getElementById('thickbox').innerHTML = formHTML;
if(p_sType == "update"){
sendToServer(new EventKey(l_sEventKey), callbackEditGroupEvent);
}
}

function updateGroupEvent(l_sEventKey, p_sType){
var l_sPostDate = new Date();
var l_sGMTPostDate = l_sPostDate.toGMTString();
var l_sStartDate = l_sPostDate.toGMTString(); //"Wed, 21 0ct 2009 23:58:42 GMT";
var title = document.getElementById("addevent_title").value;
var description = document.getElementById("addevent_desc").value;
var location = document.getElementById("addevent_location").value;
var bookmarkname = document.getElementById("addevent_bookmarkname").value;
var bookmarklink = document.getElementById("addevent_bookmarklink").value;
var UTCOffset = 0;

    var updateEventAction = updateEvent(l_sEventKey, title, description, location, bookmarkname, bookmarklink, l_sStartDate, l_sGMTPostDate, p_sType);
    sendToServer(updateEventAction, callbackUpdateGroupSubModuleEvents);
}

   function pageRedirect(p_sKey, p_sUrl){
  window.location.href = "" + p_sUrl + "" + p_sKey; 
}

function userOwnSection(){
 if($('#group_section_list').val() == "Own"){
$('#user_own_section').removeClass("plk_always_hide").addClass("plk_show");
} else{
   $('#user_own_section').removeClass("plk_show").addClass("plk_always_hide");
}
}

function getActivityTime(l_sActivity){
 var l_sTodaysDate=new Date();
 l_sTodaysJSTime= l_sTodaysDate.getTime();
 l_sDateUploaded = l_sActivity.split("/");
l_sYearSplit = l_sDateUploaded[2].split(" ");
l_sYear = l_sYearSplit[0];
l_sTimeSplit = l_sYearSplit[1];
l_sTime = l_sTimeSplit.split(":");
l_sUploadDate = new Date();
l_sUploadDate.setMonth(l_sDateUploaded[0] - 1);
l_sUploadDate.setDate(l_sDateUploaded[1]);
l_sUploadDate.setYear(l_sYear);
l_sUploadDate.setHours(l_sTime[0]);
l_sUploadDate.setMinutes(l_sTime[1]);
l_sUploadDate.setSeconds(l_sTime[2]);
l_sUploadedJSTime = l_sUploadDate.getTime();
//Subtract time taken
l_sTimeTaken = l_sTodaysJSTime - l_sUploadedJSTime;

    //Calculate days taken
var l_nRawDays = l_sTimeTaken/ (1000*60*60*24);
var l_nNumDays = Math.floor(l_nRawDays);
//calculate hrs
if (l_nNumDays <= 0) {
  l_sFloorRawDays = Math.floor(l_nRawDays);
  l_sSubtractRawDays = l_nRawDays - l_sFloorRawDays;
  l_nRawHrs = l_sSubtractRawDays*24;
  l_nNumHrs = Math.floor(l_nRawHrs);
} else{
if(l_nNumDays == 1){
l_sReturnDays = ""+l_nNumDays+" day ago.";
} else {
   l_sReturnDays = ""+l_nNumDays+" days ago.";
}
return l_sReturnDays;
}

//calculate minutes  
if (l_nNumHrs <= 0 ) {
   l_nRawMins = (l_nRawHrs - Math.floor(l_nNumHrs)) * 60;
   l_nNumMins = Math.floor(l_nRawMins);
} else{
if(l_nNumHrs == 1){
l_sReturnHours = ""+l_nNumHrs+" hour ago.";
} else{
    l_sReturnHours = ""+l_nNumHrs+" hours ago.";
}

return l_sReturnHours;
}

//calculate seconds
    if (l_nNumMins <= 0 ) {
l_nRawSecs = (l_nRawMins - Math.floor(l_nRawMins)) * 60;
l_nNumSecs = Math.floor(l_nRawSecs);
} else{
      if(l_nNumMins == 1){  
  l_sReturnMinutes = ""+l_nNumMins+" minute ago.";
  } else{
  l_sReturnMinutes = ""+l_nNumMins+" minutes ago.";
  }
  
  return l_sReturnMinutes;
   }
   
   if(l_nNumSecs == 1){
    l_nReturnSeconds = ""+l_nNumSecs+" second ago.";
   }else{
   l_nReturnSeconds = ""+l_nNumSecs+" seconds ago.";
   }
   return l_nReturnSeconds;
}



















// JavaScript Document
  //the column number is set in the document to show/hide the join group buttons based on whether the user belongs to the group.
  document._aColumnNumber = new Array(false, false, false);
  document._aJoinGroupModule = new Array(false, false, false);
  document._aColumnNumberForums = new Array(false, false, false);
  


_xUGCContent = {
      
  upload: function(p_sAction, p_sContentType, p_sFunctionName, p_sGroupKey, p_sTags){
    //Set required values to document so we can get these values on callback from pluck
 document.uploadMediaAction = p_sAction;
 document.uploadMediaContentType = p_sContentType;
 document.uploadMediaFunctionName = p_sFunctionName;
 document.uploadMediaGroupKey = p_sGroupKey;
 document.uploadMediaTags = p_sTags;
 
 if(_xUser.getCookie("")){
 //Make Request for communitykey
 var requestBatch = new RequestBatch();
 requestBatch.AddToRequest(new CommunityGroupKey(p_sGroupKey));
 requestBatch.BeginRequest(g_xServerUrl, contentCallBack);
}else{
_xTruebox._sGroupUploadKey = p_sGroupKey
  _xTruebox.makeSignupRegister();
  }
 
  },
  
  joinGroup: function(p_sAction, p_sContentType, p_sFunctionName, p_sGroupKey){
      if(_xUser.getCookie("")){
  
  var l_sCurrentCookie = _xValidate.getCookie("at");
  if(l_sCurrentCookie){
//get userkey from cookie
l_aCookieInfo = l_sCurrentCookie.split("%26");
l_aUserKey = l_aCookieInfo[0].split("=");
l_sUserKeyInfo = l_aUserKey[1];
l_sUserKeySplit = l_sUserKeyInfo.split("%3D");
l_sUserKey = l_sUserKeySplit[1];

  
$('#truebox').addClass('truebox_joinugcgroup');
  
var l_sText = 'YOU MUST BE A MEMBER OF THIS GROUP TO UPLOAD CONTENT HERE. JOIN THIS GROUP?';
var l_aTextInfo = { c:'000000',type:'med','bg':'ffffff',tran:true,s:13,lh:4,w:230,cen:true,t:l_sText}
var l_sImageUrl = makeCustomImage(l_aTextInfo);
    var l_sModuleTypeMedia = "media";

var l_sHtml = "";
l_sHtml +=  '<div class="png txt txt_joingroup">Join Group</div>'+
  '<div class="forgotpw_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div class="gap20"></div>'+
'<img src="'+l_sImageUrl+'" style="margin: 20px 0 20px 44px;" />'+
'<div class="yesbtn sprite"><a href="javascript:void(0)" onclick="javascript:'+p_sFunctionName+'(\'' + p_sGroupKey + '\', \'' + l_sUserKey + '\', \'' + l_sModuleTypeMedia + '\')"><span>Yes</span></a></div>'+
'<div class="nobtn sprite"><a href="javascript:void(0)" onclick="_xTruebox.closePopup();"><span>No</span></a></div>'+
 '</div>';
  
$('#truebox').html(l_sHtml);
  
   }

  }else{
  _xTruebox.makeSignupRegister();
        } 
  },
  
  displayUGCForms: function(p_sAction, p_sContentType, p_sFunctionName, p_sGroupKey, p_sTags){
  if(p_sContentType == 'image' || p_sContentType == 'video'){
$('#truebox').addClass('truebox_asseteditor');
var l_sHtml = ''+
'<div class="png txt txt_'+p_sAction+p_sContentType+'">'+p_sAction+' '+p_sContentType+'</div>'+
'<div id = "asseteditor" >'+
'<div id = "asseteditor_content" class="asseteditor_content">'+
'<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
'<div id = "plck-media-content">'+
'<form id="uploadassetform" class="uploadassetform" method="post" action="" enctype="multipart/form-data">'+
'<input id="galleryKey" type="hidden" name="galleryKey" value="" />'+
'<input type="file" id="assetupload" class="assetupload" name="Filedata" onChange="_xValidate.validateMedia(this.value, \'' +p_sContentType+ '\' )"/>'+
'</form>'+
'<div id = "invalid_file_format" class= "invalid_file_format"></div>'+

'<div class="hr_twin_light"></div>'+
'<div class="txt txt_title">Title</div>'+
'<div id = "invalid_title" class="invalid"></div>'+
'<input type="text" class="text" id="title" />'+
'<div class="txt txt_description">Description</div>'+
'<textarea class="text" id="desc" ></textarea>'+
'<div class="txt txt_tags">Tags</div>'+
'<input type="text" class="text" id="tags" />'+
'<div class="gap20"></div>'+
'<div id = "error" class = "plk_always_hide">true</div>'+
'<div id = "action" class = "plk_always_hide">'+p_sAction+'</div>'+

'<div class="'+p_sAction+'btn sprite"><a onclick = "javascript:'+p_sFunctionName+'(\''+p_sContentType+'\', \''+p_sTags+'\')" ><span>'+p_sAction+'</span></a></div>'+
'<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>'+
'</div>'+
'<div id = "media-loading" class="plk_always_hide"><div class="video_loading_text">Loading...</div></div>'+
'<div id = "confirm-thankyou"></div>'+
'<div id = "confirm-error"></div>'+

'</div>'+
'</div>';


$('#truebox').html(l_sHtml);
  //}else{
//_xTruebox.makeSignupRegister();
 // }
 
 }
 
 if(p_sContentType == 'blog'){
 
// if(_xUser.getCookie("")){       
   
   $('#truebox').addClass('truebox_community');
 var l_sHtml = "";
  
 l_sHtml +=  '<div class="png txt txt_postblog">Post to Blog</div>'+
  '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
   '<div id = "groupeditor">'+
 '<div id = "groupeditor_content" class="groupeditor_content">';
  
  l_sHtml +=    '<form id="uploadassetform" name = "create_blog_form" method="post" action="" enctype="multipart/form-data">';
  
  l_sHtml +=   '<label for="title" class="first_label">Title*:<span id="invalid_title" class="invalid"></span></label>'+
   '<input class = "text" type="text" id="title" name="title" />';

  l_sHtml +=   '<label for="desc">Body*:<span id="invalid_desc" class="invalid"></span></label>'+
   '<textarea class="tinymce_textarea" id="desc"></textarea>';

  l_sHtml +=   '<label for="tags">Tags:</label>'+
   '<input class="text" type="text" id="tags" name="tags" />';
   
   l_sHtml +=   '<label for="create_blog_list">Published: </label>';
   l_sHtml +=   '<div class="group_secondarytext" id="form">';
   l_sHtml +=   '<select id="create_blog_list" name="create_blog_list">';
   l_sHtml +=  '<option value="True">Yes'+
 '<option value="False">No';
   l_sHtml +=   '</select>'; 
   l_sHtml += '</div>'+
  '<div class="gap20"></div>'+
  '<div id="error" class="plk_always_hide">false</div>';

 l_sHtml +='<div class="postbtn sprite"><a onclick="_xUserContent.updateBlog(\'' + p_sTags + '\')" ><span>Post</span></a></div>'+
'<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>';

l_sHtml += "</form>";

l_sHtml +=  "</div></div>";

l_sHtml += '<div id = "thankyou" class = "plk_always_hide">'+
'<div class = "thankyou_generic"></div>'+
         '<div id = "takemetocontent"></div>'+
'</div>';
   
   

 $('#truebox').html(l_sHtml);
}
  },
  
  checkifUserBelongsToGroup: function(p_sGroupKey, p_nColumnNumber){
   document._aColumnNumber[p_nColumnNumber - 1] = true;
   var requestBatch = new RequestBatch();
   requestBatch.AddToRequest(new CommunityGroupKey(p_sGroupKey));
   requestBatch.BeginRequest(g_xServerUrl, callbackJoinGroup);
  }, 
  
  getForumDiscussionData: function(p_sForumKey, p_nColumnNumber){
   document._aColumnNumberForums[p_nColumnNumber - 1] = true;
   var requestBatch = new RequestBatch();
   requestBatch.AddToRequest(new ForumDiscussionsPage(new ForumKey(p_sForumKey), 10, 1, "TimeStampDescending"));  
   requestBatch.BeginRequest(g_xServerUrl, callbackFromTheBoards);
   
  }
  
  
};


_xMedia = {

upload: function(p_sContentType, p_sTags){

if(_xValidate.validateMediaForm()){
$('#plck-media-content').addClass('plk_always_hide');
$('#media-loading').removeClass('plk_always_hide').addClass('video_loading');
switch(p_sContentType){
case 'image':
    var galleryKey = document._sPluckCommunityPhotoGalleryKey;
    //alert(galleryKey);
document.getElementById('uploadassetform').action = g_xPhotoUploadUrl;
        document.getElementById('galleryKey').value = galleryKey;
break;
case 'video':
var galleryKey = document._sPluckCommunityVideoGalleryKey;
    document.getElementById('uploadassetform').action = g_xVideoUploadUrl;
        document.getElementById('galleryKey').value = galleryKey;
break;
}
// grab the form 
var form = document.getElementById('uploadassetform'); 
// submit the form in an iframe through PORK.iframe 
new iframe(form, {onComplete: function(request) {
updateMedia(request.responseText, p_sContentType, p_sTags); } 
}, uploadFormCounter) 
// increment for uniqueness 
uploadFormCounter++; 
}

}

};

_xUserContent = {
         updateBlog: function(p_sTags){
      if(_xValidate.validateBlogForm()){     
var l_sBlogKey = document._sPluckBlogKey;
var title = $('#title').val();
var description = $('#desc').val();
var l_sUserTags = $('#tags').val();
var l_sAppendTags = ""+l_sUserTags+","+p_sTags+"";
document._sContentType = "blog";

var published = $('#create_blog_list').val();
var updateBlogAction = updateBlogPost(l_sBlogKey,title,description,l_sAppendTags,published, "new");
      sendToServer(updateBlogAction, callbackUpdateBlog);
}
 }
};
function updateMedia(p_sKeyString,p_sContentType, p_sTags){
var title = document.getElementById('title').value;  
var desc = document.getElementById('desc').value;
var l_sUserTags = document.getElementById('tags').value;
                                var l_sAppendTags = ""+l_sUserTags+","+p_sTags+"";
//set document type 
document._sContentType = p_sContentType;


switch(p_sContentType){
case 'image':
var l_sUpdateKey = new PhotoKey(p_sKeyString);
 var update = new UpdatePhotoAction(l_sUpdateKey,title,desc,l_sAppendTags);
break;
case 'video':
    var l_sUpdateKey = new VideoKey(p_sKeyString);
var update = new UpdateVideoAction(l_sUpdateKey,title,desc,l_sAppendTags);
break;
}


var requestBatch = new RequestBatch();
requestBatch.AddToRequest(update);
requestBatch.AddToRequest(l_sUpdateKey);
requestBatch.BeginRequest(g_xServerUrl, mediaCallBack);
}

function mediaCallBack(responseBatch){
$('#media-loading').removeClass('video_loading').addClass('plk_always_hide');
switch(document._sContentType){
  case 'image':
   var l_sConfirmClass = 'image_uploaded';
   var l_sErrorClass = 'image_error';
   var l_xMediaData = responseBatch.Responses[0].Photo;
  break;
  case 'video':
   var l_sConfirmClass = 'video_uploaded';
   var l_sErrorClass = 'video_error';
   var l_xMediaData = responseBatch.Responses[0].Video;
  break;
}

//TO REFRESH CONTENT AFTER MEDIA IS UPLOADED: START//////////////////////////////////
var l_sCurrentLoc = window.location.href;
var l_sCommunitySlug = "/community/";
if(l_sCurrentLoc.match(l_sCommunitySlug) && l_xMediaData.GalleryKey.Key && l_xMediaData.AssociatedCommunityGroupKey.Key){
var l_aGet = l_sCurrentLoc.split("/");
var l_sMediaSlug = l_aGet[6];
switch(l_sMediaSlug){
case '':
//update group feeds with media(photo or video)
if(document._sContentType == 'image' || document._sContentType == 'video'){
_xCommunity.getRecentActivityFeedModule(l_xMediaData.AssociatedCommunityGroupKey.Key, 1, 10);
}
break;
case 'pictures':
//update Photos tab with photo
if(document._sContentType == 'image'){
_xCommunityPhotos.getPhotosModule(l_xMediaData.GalleryKey.Key, 10, 1, 'TimeStampDescending');
}
break;
case 'videos':
//update Videos tab with video
if(document._sContentType == 'video'){
_xCommunityVideos.getVideosModule(l_xMediaData.GalleryKey.Key, 10, 1, 'TimeStampDescending');
}
break;
}
}
document._sContentType = null;
//TO REFRESH CONTENT AFTER MEDIA IS UPLOADED: END//////////////////////////////////


if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') {
$('#confirm-thankyou').addClass(l_sConfirmClass);
}else{
$('#confirm-error').addClass(l_sErrorClass);
handleErrors(responseBatch);
}
}

function contentCallBack(responseBatch){

if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

var response = responseBatch.Responses[0];

if(response.CommunityGroup.RequestingUsersMembershipTier == "Member" || response.CommunityGroup.RequestingUsersMembershipTier == "Manager" 
   || response.CommunityGroup.RequestingUsersMembershipTier == "GroupAdmin"){
 //user is member of group
 _xUGCContent.displayUGCForms(document.uploadMediaAction, document.uploadMediaContentType, document.uploadMediaFunctionName, document.uploadMediaGroupKey, document.uploadMediaTags);
} else{
   //ask user to join group 
  _xUGCContent.joinGroup('join', 'group', 'requestCommunityGroupMembershipOnUGCModules', response.CommunityGroup.CommunityGroupKey.Key);
}

if (response.CommunityGroup.CommunityGroupKey.Key != null) {
document._sPluckCommunityPhotoGalleryKey = response.CommunityGroup.PhotoGalleryKey.Key;
document._sPluckCommunityVideoGalleryKey = response.CommunityGroup.VideoGalleryKey.Key;
document._sPluckBlogKey = response.CommunityGroup.BlogKey.Key;
}
}



function requestCommunityGroupMembershipOnUGCModules(p_sCommunityKey, p_sUserKey, p_sType, p_nColumnNumber){
//var inviteAction = new RequestCommunityGroupMembershipAction(new CommunityGroupKey(p_sCommunityKey),  new UserKey(p_sUserKey));  
//sendToServer(inviteAction, callbackGeneric);
 
 var requestBatch = new RequestBatch();
 requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(p_sCommunityKey),  new UserKey(p_sUserKey)));
 if(p_sType == "media"){
    var p_sCallbackFunctionName = 'callbackRequestCommunityGroupMembershipOnUGCModules';
 BaseAjax._xArgs.data = 'a=AssociateUserWithGroup';
BaseAjax._xArgs.data += '&CommunityKey='+p_sCommunityKey;
BaseAjax._xArgs.data  += '&CallbackFunctionName='+p_sCallbackFunctionName;
//Tempoararily commented out newsletter checkbox.
//BaseAjax._xArgs.data += '&newsletter=0';
BaseAjax._xArgs.requestType = "POST";
BaseAjax._xArgs.returnDiv = '#returndiv';
BaseAjax.makeAjaxCall(AJAX_URL);
 } else{
   document._aJoinGroupModule[p_nColumnNumber - 1] = true; 
   requestBatch.BeginRequest(g_xServerUrl, callbackRequestCommunityGroupMembershipGeneric);
 }
}

function callbackRequestCommunityGroupMembershipOnUGCModules(responseBatch){
  //check if response is ok
  if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
  }

 $('#truebox').removeClass('truebox_joinugcgroup');
 _xUGCContent.displayUGCForms(document.uploadMediaAction, document.uploadMediaContentType, document.uploadMediaFunctionName, document.uploadMediaGroupKey, document.uploadMediaTags);
 //refresh newest members module if group key exists
  if($('#plck-group-key-set').html()){
 _xCore.getGroupMembershipPage($('#plck-group-key-set').html(), 2, 1, "TimeStampDescending");
 //refresh stats module
 _xCore.getStats($('#plck-group-key-set').html(), "community");
 $('#plck_jointhisgroup').hide();
  }
 document.uploadMediaAction = null;
 document.uploadMediaContentType = null;
 document.uploadMediaFunctionName = null;
 document.uploadMediaGroupKey = null;
 document.uploadMediaTags = null;
  
}

function callbackRequestCommunityGroupMembershipGeneric(responseBatch){
  
  if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
_xTruebox.closePopup();
  return;
  }
  _xTruebox.closePopup();
  
  for(var i = 0; i < document._aJoinGroupModule.length; i++){
if(document._aJoinGroupModule[i] == true){
var columnDivJoinGroup = i + 1;
$('#plck_join_group_'+columnDivJoinGroup).hide();    
    }
  }

}

function callbackJoinGroup(responseBatch){
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
//handleErrors(responseBatch);
return;
}

var response = responseBatch.Responses[0];

if(response.CommunityGroup.RequestingUsersMembershipTier == "Member" || response.CommunityGroup.RequestingUsersMembershipTier == "Manager" || response.CommunityGroup.RequestingUsersMembershipTier == "GroupAdmin"){
 //hide join group buttom
for(var i = 0; i < document._aColumnNumber.length; i++){
   if(document._aColumnNumber[i] == true){
 var columnDivCommJoinGroup = i + 1; 
 $('#plck_join_group_'+columnDivCommJoinGroup).hide();    
   }
}
    }
}

function callbackFromTheBoards(responseBatch){
if (responseBatch.Responses.length == 0) {
if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
handleErrors(responseBatch);
return;
}

var response = responseBatch.Responses[0].ForumDiscussionsPage.Discussions;
var l_sPLKFinalForumTemplate = "";

//Hardcoding showing only the top two responses.
for(var i= 0; i < 2; i++){
var l_sPLKForumTemplate = $('#plck-from-the-boards-module-template').html();
var l_sCategoryKey = response[i].ForumCategoryKey.Key; //TODO Get Category key name
var l_sDiscussionPostedDateTime = response[i].FirstPostDate;
var l_aDiscussionPostDateTime = l_sDiscussionPostedDateTime.split(" ");
var l_sDiscussionPostedDate = l_aDiscussionPostDateTime[0];
var l_sDiscussionPostDateTimeTrim = l_aDiscussionPostDateTime[1].substring(0, l_aDiscussionPostDateTime[1].length - 3); 
var l_sDiscussionPostedTime = l_sDiscussionPostDateTimeTrim + l_aDiscussionPostDateTime[2];
        var l_nNumberOfReplies = response[i].PostCount - 1; // need to dimage this
var l_sForumReplies = ""+l_nNumberOfReplies+" REPLIES"
//limit discussion body to 150 characters.
if(response[i].DiscussionBody.length > 150){
var l_sDiscussionBody = response[i].DiscussionBody.substring(0, 150);
    l_sDiscussionBody = l_sDiscussionBody + "...";
} else {
l_sDiscussionBody = response[i].DiscussionBody.substring(0);
}

l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~discussion-title~/, response[i].DiscussionTitle);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~discussion-description~/, l_sDiscussionBody);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/discussion-url/, response[i].DiscussionUrl);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~discussion-posted-date~/, l_sDiscussionPostedDate);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~discussion-posted-time~/, l_sDiscussionPostedTime);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~author-name~/, response[i].LiteUser.DisplayName);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/author-url/, response[i].LiteUser.PersonaUrl);
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~reply-count-image~/, l_sForumReplies);
if(i == 0){
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~category-divider~/, '<div class="hr_single_light full_line"></div>');
            l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~category-name~/, '<div class="hr_twin_light boards_twin_top"></div>');
}else{
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/cms-category/, 'plk_always_hide');
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~category-name~/, '');
l_sPLKForumTemplate = l_sPLKForumTemplate.replace(/~category-divider~/, '');
}

l_sPLKFinalForumTemplate += l_sPLKForumTemplate;

if(i == 0){

var l_sPLKForumCategoryTemplate = $('#plck-forum-category-url-template').html();
l_sPLKForumCategoryTemplate = l_sPLKForumCategoryTemplate.replace(/forum-category-url/, "/community/forums/?plckForumPage=ForumCategory&plckCategoryId="+l_sCategoryKey);

}

}

for(var i = 0; i < document._aColumnNumberForums.length; i++){
   if(document._aColumnNumberForums[i] == true){
  var columnDivForums = i + 1;  
  
  $('#plck-from-the-boards-module-template-final_'+columnDivForums).html(l_sPLKFinalForumTemplate);
  $('#plck-forum-category-url-template-final_'+columnDivForums).html(l_sPLKForumCategoryTemplate);
  document._aColumnNumberForums[i] == false;
   }
}

}
  




// JavaScript Document


_xForms = {
              
   displayGroupForm: function(l_sCommunityGroupKey){
      
  
   if(_xUser.getCookie("")){
  
    $('#truebox').addClass('truebox_community');
  var l_sHtml = "";
  
  l_sHtml += '<div class="png txt txt_creategroup">Create a Group</div>'+
   '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
   '<div id="groupeditor">'+
 '<div id="groupeditor_content" class="groupeditor_content">';
 
l_sHtml +=    '<form id="uploadassetform" name = "create_group_form" method="post" action="" enctype="multipart/form-data">';
l_sHtml +=  '<label for="title" class="first_label"> Title*:<span id="invalid_title" class="invalid"></span></label>'+
'<input class="text" type="text" id="title" name="title" />';

l_sHtml +=   '<label for="desc">Description</label>'+
'<textarea class="cg_textarea" id="desc"></textarea>';

l_sHtml +=   '<label for="tags">Tags:</label>'+
'<input class="text" type="text" id="tags" name="tags" />';

l_sHtml +=   '<label for="photoUpload">Upload Photo*<span id="invalid_media" class="invalid"></span><span id="invalid_file_format" class= "invalid_file_format"></span></label>'+
 '<input type="file" id="photoUpload" name="Filedata" onChange="_xValidate.validateAvatarPhoto(this.value)" />'+
 '<div id="avatarphotokey" class="plk_always_hide">null</div>';

   
l_sHtml +=   '<label for="group_section_list">Sport:</label>';
l_sHtml +=   "<div class='inputholder_left' id='form'>";
  l_sHtml +=  "<SELECT ID='group_section_list' NAME='group_section_list' onchange='userOwnSection()'>";
  l_sHtml += "<OPTION VALUE='NHL'>NHL";
  l_sHtml += "<OPTION VALUE='Cycling'>Cycling";
  l_sHtml += "<OPTION VALUE='Hunting'>Hunting";
  l_sHtml += "<OPTION VALUE='Fishing'>Fishing";
  l_sHtml += "<OPTION VALUE='Mixed Martial Arts'>Mixed Martial Arts";
  l_sHtml += "<OPTION VALUE='College Football'>College Football";
  l_sHtml += "<OPTION VALUE='Indycar'>Indycar";
  l_sHtml += "<OPTION VALUE='Bull Riding'>Bull Riding";
  l_sHtml +=   "</SELECT>";
  l_sHtml +=   "</div>";
 
 l_sHtml +=    '<div id="user_own_section" class="plk_always_hide">'+
'<div class="inputholder_right">'+
'<input class="sm_text" type="text" id="user_own_section_text" name="tags" />'+
'</div>'+
'<div id="error" class="plk_always_hide">false</div>'+
'</div>';

 l_sHtml += '<div class="submitcol">'+
'<div class="createbtn sprite"><a onclick="_xCore.updateCommunityGroup(\'' + l_sCommunityGroupKey + '\')" ><span>Create</span></a></div>'+
'</div>';

l_sHtml += '</form>'+
   '</div></div>'; //end of #groupeditor and .groupeditor_content

l_sHtml += '<div id="thankyou" class="plk_always_hide">'+
'<div class="thankyou_generic"></div>'+
         '<div id="takemetocontent" style="padding-left:140px"></div>'+
'</div>';
  
 
 $('#truebox').html(l_sHtml);
  }else{
  _xTruebox.makeSignupRegister();
    }

   },
   
   displayThankYouMessage: function(){
      var l_sGroupTitle = $('#plck-group-title').html();
  
  
  var l_sStartText = 'FOR JOINING '+l_sGroupTitle.toUpperCase()+'!';
  var l_aTextInfo = { c:'000000',type:'med','bg':'ffffff',tran:true,s:13,w:230,cen:true,t:l_sStartText}
  var l_sImageUrl = makeCustomImage(l_aTextInfo);

  
  $('#truebox').addClass('truebox_community');
  
  var l_sHtml = "";
  
  l_sHtml += '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>';
  
  l_sHtml +=  '<div id = "groupeditor_content" class="groupeditor_content">'+
    '<div id = "thankyou">'+
             '<div class = "thankyou_generic"><img class="finishtext" src="'+l_sImageUrl+'" ></div>'+
  '</div>'+
  '</div>';

  $('#truebox').html(l_sHtml);
  
},
   
   displayGroupBlog: function(l_sType){
     if(_xUser.getCookie("")){
  
$('#truebox').addClass('truebox_community');
 
  if(l_sType == 'post'){
 var l_sBlogKey  =  $('#plck-group-blog-key-set').html();
  }
  
  var l_sHtml = "";
  
 l_sHtml +=  '<div class="png txt txt_postblog">Post to Blog</div>'+
  '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
   '<div id = "groupeditor">'+
 '<div id = "groupeditor_content" class="groupeditor_content">';
  
  l_sHtml +=    '<form id="uploadassetform" name = "create_blog_form" method="post" action="" enctype="multipart/form-data">';
  
  l_sHtml +=   '<label for="title" class="first_label">Title*:<span id="invalid_title" class="invalid"></span></label>'+
   '<input class = "text" type="text" id="title" name="title" />';

  l_sHtml +=   '<label for="desc">Body*:<span id="invalid_desc" class="invalid"></span></label>'+
   '<textarea class="tinymce_textarea" id="desc"></textarea>';

  l_sHtml +=   '<label for="tags">Tags:</label>'+
   '<input class="text" type="text" id="tags" name="tags" />';
   
   l_sHtml +=   '<label for="create_blog_list">Published: </label>';
   l_sHtml +=   '<div class="group_secondarytext" id="form">';
   l_sHtml +=   '<select id="create_blog_list" name="create_blog_list">';
   l_sHtml +=  '<option value="True">Yes'+
 '<option value="False">No';
   l_sHtml +=   '</select>'; 
   l_sHtml += '</div>'+
  '<div class="gap20"></div>'+
  '<div id="error" class="plk_always_hide">false</div>';

 l_sHtml +='<div class="postbtn sprite"><a onclick="_xCore.updateCommunityBlog(\'' + l_sBlogKey + '\')" ><span>Post</span></a></div>'+
'<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>';

l_sHtml += "</form>";

l_sHtml +=  "</div></div>";

l_sHtml += '<div id = "thankyou" class = "plk_always_hide">'+
'<div class = "thankyou_generic"></div>'+
         '<div id = "takemetocontent"></div>'+
'</div>';
   
   

 $('#truebox').html(l_sHtml);
// _xFormUtils.initTinyMCE();
// _xFormUtils.loadTinyMCE();

}else{
  _xTruebox.makeSignupRegister();
    }

   }, 
   
   
   displayGroupEvent: function(l_sType){
    if(_xUser.getCookie("")){
     
   $('#truebox').addClass('truebox_community');
   
   if(l_sType == 'post'){
     var l_sEventKey  =  $('#plck-group-event-set-key-set').html();
}
   
   var l_sHtml = "";
  
   l_sHtml += '<div class="png txt txt_createevent">Create Event</div>'+
     '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
    '<div id = "groupeditor">'+
  '<div id = "groupeditor_content" class="groupeditor_content">';
  
   l_sHtml += '<form id="uploadassetform" name = "create_event_form" method="post" action="" enctype="multipart/form-data">';
  
   l_sHtml += '<label for="title" class="first_label">Title*:<span id="invalid_title" class="invalid"></span></label>'+
     '<input class = "text" type="text" id="title" name="title" />';

   l_sHtml += '<label for="desc">Description*:<span id="invalid_desc" class="invalid"></span></label>'+
     '<textarea class="ce_textarea" id="desc"></textarea>';

   l_sHtml += '<label for="loc">Location*:<span id="invalid_loc" class="invalid"></span></label><input class="text" id="loc" />';

   l_sHtml += '<label for="start_time_picker">'+
'Start Date/Time:'+
      '<span id="invalid_setdate" class="invalid"></span>'+
      '<span id="invalid_sdate" class="invalid"></span>'+
      '<span id="invalid_stime" class="invalid"></span>'+
  '</label>'+
     '<input type="text" id="start_time_picker" class="half_input" />'+
  '<input type="text" id="start_time_entry" class="half_input" />'+
  '<div class="clear"></div>';
   
   l_sHtml += '<label for="end_time_picker">'+
   'End Date/Time:'+
       '<span id="invalid_edate" class="invalid"></span>'+
       '<span id="invalid_etime" class="invalid"></span>'+
  '</label>'+
     '<input type="text" id="end_time_picker" class="half_input" />'+
  '<input type="text" id="end_time_entry" class="half_input" />'+
  '<div class="clear"></div>';
   
   l_sHtml += '<label for="url">'+
      'Enter Url/Name:'+
      '<span id="invalid_url" class="invalid"></span>'+
      '<span id="invalid_urlname" class="invalid"></span>'+
     '</label>'+
  '<input type="text" id="url" class="half_input" />'+
  '<input type="text" id="name" class="half_input right_input" />';

   l_sHtml += '<div class="gap20"></div>'+
  '<div id="error" class="plk_always_hide">false</div>';

   l_sHtml += '<div class="createbtn sprite"><a onclick="_xCore.updateGroupEvent(\'' + l_sEventKey + '\')" ><span>Create</span></a></div>'+
      '<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>';

   l_sHtml +=  "</form>";

       l_sHtml +=  "</div></div>";
   
   l_sHtml += '<div id = "thankyou" class = "plk_always_hide">'+
'<div class = "thankyou_generic"></div>'+
         '<div id = "takemetocontent"></div>'+
'</div>';
   
 $('#truebox').html(l_sHtml);
 
  _xFormUtils.outputDatePicker("start_time_picker");
  _xFormUtils.outputDatePicker("end_time_picker");
  _xFormUtils.outputTimePicker("start_time_entry");
  _xFormUtils.outputTimePicker("end_time_entry");
  
 
}else{
  _xTruebox.makeSignupRegister();
    } 
  
}, 


displayEmailForm: function(l_sType, f){
 switch(l_sType){
  case 'groupblog':
   var l_sArticleSlug = $(f).parents('.article_inner:first').find('.title').attr('href');
   var l_sArticleUrl = "http://"+g_xVersusBaseDomain+l_sArticleSlug;
   var l_sArticleTitle = $(f).parents('.article_inner:first').find('.title').html();
   var l_sContentType = "blog";
  break;
  case 'grouppicture':
var l_sArticleTitle = $(f).parents('.detail_meta:first').find('#photo-detail-meta-template-final').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
var l_sContentType = "picture";
  break;
  case 'groupvideo':
   var l_sArticleTitle = $(f).parents('.detail_meta:first').find('#video-detail-meta-template-final').find('.customimg').attr('alt');
   var l_sArticleUrl = window.location.href;
   var l_sContentType = "video";
  break;
  case 'picture':
    var l_sArticleTitle = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
var l_sContentType = "picture";
  break;
  case 'video':
    var l_sArticleTitle = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
var l_sContentType = "video";
  break;
  case 'gear':
    var l_sArticleTitle = $(f).parents('.detail_meta:first').find('.customimg').attr('alt');
var l_sArticleUrl = window.location.href;
var l_sContentType = "gear guide";
  break;
  
 }
  

 
 if(_xUser.getCookie("")){
 l_sUserName = _xUser.getPluckUserInfoFromCookie("", "name");
  
$('#truebox').addClass('truebox_community');
 
 var l_sHtml = "";
  
 l_sHtml +=  '<div class="png txt txt_sendemail">Send Email</div>'+
  '<div class="closebtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>X</span></a></div>'+
   '<div id="groupeditor">'+
 '<div id="groupeditor_content" class="groupeditor_content">';
  
  l_sHtml +=    '<form id="uploadassetform" name="send_email_form" method="post" action="" enctype="multipart/form-data">';
  
  l_sHtml +=   '<label for="to">To*:<span id="invalid_title" class="invalid"></span></label>'+
   '<input class="text" type="text" id="to" name="to" />'+
   '<div class="gap20 input_comment">Enter Comma Separated</div>';

  l_sHtml +=   '<label for="user_body">Body:<span id="invalid_desc" class="invalid"></span></label>'+
   '<textarea class="tinymce_textarea" id="user_body"></textarea>'+
     '<div class="gap20"></div>';
  
  l_sHtml +=   '<div class="sendbtn sprite"><a onclick="_xCore.sendEmailViaPluck()"><span>Send</span></a></div>'+
   '<div class="cancelbtn sprite"><a href="javascript:void" onclick="_xTruebox.closePopup();"><span>Cancel</span></a></div>';  
   
  l_sHtml +=   '<input class = "plk_always_hide" type="text" id="subject" name="subject" value="'+l_sUserName+' wants you to checkout Versus.com!" />'+   
   '<input class = "plk_always_hide" type="text" id="versus_body" name="versus_body" value="'+l_sUserName+' just sent you a '+l_sContentType+':'+l_sArticleTitle+'.'+ 
   ' Check it out on Versus.com: '+l_sArticleUrl+' ! This is what '+l_sUserName+' has to say about it...."  />'+
   '<div class="gap20"></div>'+
   '<div id = "error" class = "plk_always_hide">false</div>';

 

l_sHtml += "</form>";

l_sHtml +=  "</div></div>";

l_sHtml += '<div id = "thankyou" class = "plk_always_hide">'+
'<div class = "thankyou_generic"></div>'+
         '<div id = "takemetocontent"></div>'+
'</div>';
   
$('#truebox').html(l_sHtml);


}else{
  _xTruebox.makeSignupRegister();
    }

   } 


};

_xFormUtils = {

outputDatePicker :function(l_sInputId){

$('#'+l_sInputId).datepicker({dateFormat: 'D, d M yy'});
},

outputTimePicker :function(l_sInputId){
$(function () {
$('#'+l_sInputId).timeEntry({show24Hours: true, showSeconds: true});
});
},

initTinyMCE : function(){
  tinyMCE.init({ mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "bold,italic,underline,|,cut,copy,paste,pasteword,|,code,|,spellchecker",
theme_advanced_buttons2 : "justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,image",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom"

});
},

loadTinyMCE :function(){
$('.tinymce_textarea').each( function(){

var l_sId = $(this).attr('id');
var l_sName = "#" + l_sId + " .mceEditorContainer";
var l_sData = "#" + l_sId + " .mceContentBody";

tinyMCE.execCommand('mceAddControl', false, l_sId);


if( $(this).attr('rel') == 'tinymce_row_1'){
$('#'+l_sId+'_toolbar2').hide();
$('#'+l_sId+'_toolbar3').hide();
$('#'+l_sId+'_toolbar4').hide();
$('#'+l_sId+'_toolbar5').hide();
}

if( $(this).attr('config-reset-body')){
var l_xObj = _xUtils.getTinyMCEObject(l_sId).body;
l_xObj.style.color = '#000';
l_xObj.style.width = 'auto';
l_xObj.style.padding = '0px';
l_xObj.style.margin = '0px';
l_xObj.style.backgroundColor = '#fff';
}

if( $(this).attr('config-background-color')){
var l_xObj = _xUtils.getTinyMCEObject(l_sId).body;
l_xObj.style.backgroundColor = $(this).attr('config-background-color');
}

});
},

fixDialogBox:function(l_sBoxClass){
setTimeout(function(){
var l_xElement = $('.'+l_sBoxClass);
$(l_xElement).css('left','0px').css('z-index',10000)
},100);
}

  
};

//
//function displayBlogForm(p_sBlogKey, p_sType){
//    
//var html = "";
//
//html += "<h3>Create/ Update Blog!</h3>"; 
//html +=  "Enter Title: <input type='text' id='postblog_title' name='postblog_title' /><br/><br/>"; 
//    html +=  "Enter Description: <input type='text' id='postblog_description' name='postblog_description' /><br/><br/>"; 
//    html +=  "Enter Tags: <input type='text' id='postblog_tags' name='postblog_tags' /><br/><br/>"; 
//    html +=  "Published(True, False): <input type='text' id='postblog_published' name='postblog_published' /><br/><br/>"; 
//html +=   "<p><button id='btnUpload' type='button' onclick='updateGroupBlog(\"" + p_sBlogKey + "\", \"" + p_sType + "\")'>Go</button></p> ";
//
//return html;
//}
//
//
//function displayVideoForm(){
//   var html = "";
//
//html += "<div id='submitVideo'>";
//html +="<div id = 'submitVideoStep1'>";
//    html +=                            "<h3>Step 1: Upload Video</h3>";
//    html +=                            "<p>Click <strong>Browse...</strong> to find and select a video on your computer</p>";
//    html +=                                "<form id='uploadVideoForm' method='post' action='' enctype='multipart/form-data'>";
//    html +=                                    "<input id='galleryKey' type='hidden' name='galleryKey' value='' />";
//    html +=                                    "<p><input type='file' id='videoUpload' name='Filedata' /></p>";
//    html +=                                "</form>";  
//    html +=                                 "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitVideoStep1\");showObject(\"submitVideoStep2\")'>Next</button></p>"; 
//    html +=                        "</div>";
//    html +=                        "<div id='submitVideoStep2' style='display:none'>";
//    html +=                         "<h3>Step 2: Enter Video Details</h3>";   
//    html +=                            "Enter Title:<input type='text' id='video_title' name='video_title' /><br/>";
//    html +=                        "Enter Desc:<input type='text' id='video_desc' name='video_desc' /><br/>";
//    html +=                         "Enter Tags:<input type='text' id='video_tags' name='video_tags' /><br/>";
//    html +="<p><button id='btnUpload' type='button' onclick='hideObject(\"submitVideoStep2\");showObject(\"processingMessage\");uploadVideo()'>Start Upload</button></p>";
//html +=    "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitVideoStep2\");showObject(\"submitVideoStep1\")'>Previous</button></p>";
//    html +=                        "</div>";
//    html +=                        "<div id='processingMessage' style='display: none'>";
//html +="<h3>Uploading Video</h3>";
//html +="<h4>Thank You</h4>";
//html +="<p>This video will be available in the <span id='galleryTitle'></span> gallery after it has finished processing.</p>";
//html +=     "<p><button id='btnUpload' type='button' onclick='hideObject(\"processingMessage\");showObject(\"submitVideoStep1\")'>Upload More Videos</button></p>";
//    html +=                    "</div>";
//    html +=                    "</div>"
//
//return html;
//}
//
//
//
//function displayPhotoForm(){
//   var html = "";
//
//html += "<div id='submitPhoto'>";
//html +="<div id = 'submitPhotoStep1'>";
//    html +=                            "<h3>Step 1: Upload Photo</h3>";
//    html +=                            "<p>Click <strong>Browse...</strong> to find and select a Photo on your computer</p>";
//    html +=                                "<form id='uploadPhotoForm' method='post' action='' enctype='multipart/form-data'>";
//    html +=                                    "<input id='galleryKey' type='hidden' name='galleryKey' value='' />";
//    html +=                                    "<p><input type='file' id='photoUpload' name='Filedata' /></p>";
//    html +=                                "</form>";  
//    html +=                                 "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep1\");showObject(\"submitPhotoStep2\")'>Next</button></p>"; 
//    html +=                        "</div>";
//    html +=                        "<div id='submitPhotoStep2' style='display:none'>";
//    html +=                         "<h3>Step 2: Enter Photo Details</h3>";   
//    html +=                            "Enter Title:<input type='text' id='photo_title' name='photo_title' /><br/>";
//    html +=                        "Enter Desc:<input type='text' id='photo_desc' name='photo_desc' /><br/>";
//    html +=                         "Enter Tags:<input type='text' id='photo_tags' name='photo_tags' /><br/>";
//    html +="<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep2\");showObject(\"processingMessage\");uploadPhoto()'>Start Upload</button></p>";
//html +=    "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep2\");showObject(\"submitPhotoStep1\")'>Previous</button></p>";
//    html +=                        "</div>";
//    html +=                        "<div id='processingMessage' style='display: none'>";
//html +="<h3>Uploading Photo</h3>";
//html +="<h4>Thank You</h4>";
//html +="<p>This photo will be available in the <span id='galleryTitle'></span> gallery after it has finished processing.</p>";
//html +=     "<p><button id='btnUpload' type='button' onclick='hideObject(\"processingMessage\");showObject(\"submitPhotoStep1\")'>Upload More Photos</button></p>";
//    html +=                    "</div>";
//    html +=                    "</div>"
//
//return html;
//}
//
//function displayAvatarPhotoForm(){
//   var html = "";
//
//html += "<div id='submitPhoto'>";
//html +="<div id = 'submitPhotoStep1'>";
//    html +=                            "<h3>Step 1: Upload Photo</h3>";
//    html +=                            "<p>Click <strong>Browse...</strong> to find and select a Photo on your computer</p>";
//    html +=                                "<form id='uploadPhotoForm' method='post' action='' enctype='multipart/form-data'>";
//    html +=                                    "<p><input type='file' id='photoUpload' name='Filedata' /></p>";
//    html +=                                "</form>";  
//    html +=                                 "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep1\");showObject(\"submitPhotoStep2\")'>Next</button></p>"; 
//    html +=                        "</div>";
//    html +=                        "<div id='submitPhotoStep2' style='display:none'>";
//    html +=                         "<h3>Step 2: Enter Photo Details</h3>";   
//    html +=                            "Enter Title:<input type='text' id='photo_title' name='photo_title' /><br/>";
//    html +=                        "Enter Desc:<input type='text' id='photo_desc' name='photo_desc' /><br/>";
//    html +=                         "Enter Tags:<input type='text' id='photo_tags' name='photo_tags' /><br/>";
//    html +="<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep2\");showObject(\"processingMessage\");uploadPhoto()'>Start Upload</button></p>";
//html +=    "<p><button id='btnUpload' type='button' onclick='hideObject(\"submitPhotoStep2\");showObject(\"submitPhotoStep1\")'>Previous</button></p>";
//    html +=                        "</div>";
//    html +=                        "<div id='processingMessage' style='display: none'>";
//html +="<h3>Uploading Photo</h3>";
//html +="<h4>Thank You</h4>";
//html +="<p>This photo will be available in the <span id='galleryTitle'></span> gallery after it has finished processing.</p>";
//html +=     "<p><button id='btnUpload' type='button' onclick='hideObject(\"processingMessage\");showObject(\"submitPhotoStep1\")'>Upload More Photos</button></p>";
//    html +=                    "</div>";
//    html +=                    "</div>"
//
//return html;
//}
//
//function  requestCommunityGroupMembershipForm(p_sKey){
//  alert(p_sKey);
//  var html = "";
//  html +=  "<h3>Add User to Group</h3>";
//  html +=  "Enter User Key: <input type='text' id='userkey_adduser' name='userkey_adduser' /><br/>";
//  html +=  "Enter Group Key:<input type='text' id='"+ p_sKey +"' name='"+ p_sKey +"' /><br/>"; 
//  html +=  '<p><button id="btnUpload" type="button" onclick="requestCommunityGroupMembership(\'' + p_sKey + '\')">Go</button></p>';  
//
//  return html;
//}
//
//function reportAbuseForm(p_sKey, p_sType){
//var html = "";
//html += "<strong>Report Abuse Form</strong><br/>";
//html +=  "Enter Reason: <input type='text' id='reason' name='reason' /><br/>";
//    html +=  "Enter Description:<input type='text' id='description' name='description' /><br/>"; 
//    html +=  '<p><button id="btnUpload" type="button" onclick="reportGroupAbuse(\'' + p_sKey + '\', \'' + p_sType + '\')">Go</button></p>';  
//return html;   
//}
//
//function requestGroupDeleteForm(p_sCommunityKey){
//   var html = "";
//   html += "<strong>Request Group Delete Form</strong><br/>";
//   html +=  "Enter Reason: <input type='text' id='reason' name='reason' /><br/>";
//   html +=  '<p><button id="btnUpload" type="button" onclick="requestGroupDelete(\'' + p_sCommunityKey + '\')">Go</button></p>';  
//   return html;
//}
//
//
//


/* SiteCatalyst code version: H.20.3.
Copyright 1996-2009 Adobe, Inc. All Rights Reserved
More info available at http://www.omniture.com */
/************************ ADDITIONAL FEATURES ************************
     Plugins
*/

var s_account="versuscomdev"
var s=s_gi(s_account)
/************************** CONFIG SECTION **************************/
/* You may add or alter any code config here. */
/* Conversion Config */
s.currencyCode="USD"
/* Link Tracking Config */
s.trackDownloadLinks=true
s.trackExternalLinks=true
s.trackInlineStats=false
s.linkDownloadFileTypes="exe,zip,wav,mp3,mov,mpg,avi,wmv,pdf,doc,docx,xls,xlsx,ppt,pptx"
s.linkInternalFilters="javascript:,."
s.linkLeaveQueryString=false
s.linkTrackVars="None"
s.linkTrackEvents="None"
/* Plugin Config */
s.usePlugins=true
function s_doPlugins(s) {
/************** doPlugins Script **************/
/* External Campaign Tracking */
if(!s.campaign)
s.campaign=s.getQueryParam('cmpid')
s.campaign=s.getValOnce(s.campaign,'s_campaign',0)

/* Site Search */
if(s.prop7){
        s.prop7=s.prop7.toLowerCase();
        s.eVar7=s.prop7;
        var t_search=s.getValOnce(s.eVar7,'ev7',0);
        if(t_search){
               s.events=s.apl(s.events,"event1",",",2);
        }
}

/* Set Page View Event */
s.events=s.apl(s.events,'event2',',',2)

/* Set Time Parting Variables - SAMPLE EST */
if(!s.prop8&&!s.eVar8) s.prop8=s.eVar8=s.getTimeParting('h','-5'); // Set hour 
if(!s.prop9&&!s.eVar9) s.prop9=s.eVar9=s.getTimeParting('d','-5'); // Set day 
if(!s.prop10&&!s.eVar10) s.prop10=s.eVar10=s.getTimeParting('w','-5'); // Set weekday 

/* Copy props to eVars */
if(s.pageName&&!s.eVar11) s.eVar11=s.pageName;
if(s.channel&&!s.eVar12) s.eVar12=s.channel;
if(s.prop1&&!s.eVar1) s.eVar1=s.prop1;
if(s.prop2&&!s.eVar2) s.eVar2=s.prop2;
if(s.prop3&&!s.eVar3) s.eVar3=s.prop3;
if(s.prop4&&!s.eVar4) s.eVar4=s.prop4;
if(s.prop5&&!s.eVar5) s.eVar5=s.prop5;
if(s.prop6&&!s.eVar6) s.eVar6=s.prop6;
if(s.prop7&&!s.eVar7) s.eVar7=s.prop7;
if(s.prop8&&!s.eVar8) s.eVar8=s.prop8;
if(s.prop9&&!s.eVar9) s.eVar9=s.prop9;
if(s.prop10&&!s.eVar10) s.eVar10=s.prop10;
if(s.prop15&&!s.eVar15) s.eVar15=s.prop15;
if(s.prop16&&!s.eVar16) s.eVar16=s.prop16;
if(s.prop17&&!s.eVar17) s.eVar17=s.prop17;
if(s.prop18&&!s.eVar18) s.eVar18=s.prop18;
if(s.prop19&&!s.eVar19) s.eVar19=s.prop19;
/**********************************************/

}
s.doPlugins=s_doPlugins
/************************** PLUGINS SECTION *************************/
/********************************************************************/
/*
 * Function - read combined cookies v 0.3
 */
if(!s.__ccucr){s.c_rr=s.c_r;s.__ccucr = true;
s.c_r=new Function("k",""
+"var s=this,d=new Date,v=s.c_rr(k),c=s.c_rr('s_pers'),i,m,e;if(v)ret"
+"urn v;k=s.ape(k);i=c.indexOf(' '+k+'=');c=i<0?s.c_rr('s_sess'):c;i="
+"c.indexOf(' '+k+'=');m=i<0?i:c.indexOf('|',i);e=i<0?i:c.indexOf(';'"
+",i);m=m>0?m:e;v=i<0?'':s.epa(c.substring(i+2+k.length,m<0?c.length:"
+"m));if(m>0&&m!=e)if(parseInt(c.substring(m+1,e<0?c.length:e))<d.get"
+"Time()){d.setTime(d.getTime()-60000);s.c_w(s.epa(k),'',d);v='';}ret"
+"urn v;");}
/*
 * Function - write combined cookies v 0.3
 */
if(!s.__ccucw){s.c_wr=s.c_w;s.__ccucw = true;
s.c_w=new Function("k","v","e",""
+"this.new2 = true;"
+"var s=this,d=new Date,ht=0,pn='s_pers',sn='s_sess',pc=0,sc=0,pv,sv,"
+"c,i,t;d.setTime(d.getTime()-60000);if(s.c_rr(k)) s.c_wr(k,'',d);k=s"
+".ape(k);pv=s.c_rr(pn);i=pv.indexOf(' '+k+'=');if(i>-1){pv=pv.substr"
+"ing(0,i)+pv.substring(pv.indexOf(';',i)+1);pc=1;}sv=s.c_rr(sn);i=sv"
+".indexOf(' '+k+'=');if(i>-1){sv=sv.substring(0,i)+sv.substring(sv.i"
+"ndexOf(';',i)+1);sc=1;}d=new Date;if(e){if(e.getTime()>d.getTime())"
+"{pv+=' '+k+'='+s.ape(v)+'|'+e.getTime()+';';pc=1;}}else{sv+=' '+k+'"
+"='+s.ape(v)+';';sc=1;}if(sc) s.c_wr(sn,sv,0);if(pc){t=pv;while(t&&t"
+".indexOf(';')!=-1){var t1=parseInt(t.substring(t.indexOf('|')+1,t.i"
+"ndexOf(';')));t=t.substring(t.indexOf(';')+1);ht=ht<t1?t1:ht;}d.set"
+"Time(ht);s.c_wr(pn,pv,d);}return v==s.c_r(s.epa(k));");}
/*
 * Plugin: getTimeParting 2.0 - Set timeparting values based on time zone
 */
s.getTimeParting=new Function("t","z",""
+"var s=this,cy;dc=new Date('1/1/2000');"
+"if(dc.getDay()!=6||dc.getMonth()!=0){return'Data Not Available'}"
+"else{;z=parseFloat(z);var dsts=new Date(s.dstStart);"
+"var dste=new Date(s.dstEnd);fl=dste;cd=new Date();if(cd>dsts&&cd<fl)"
+"{z=z+1}else{z=z};utc=cd.getTime()+(cd.getTimezoneOffset()*60000);"
+"tz=new Date(utc + (3600000*z));thisy=tz.getFullYear();"
+"var days=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday',"
+"'Saturday'];if(thisy!=s.currentYear){return'Data Not Available'}else{;"
+"thish=tz.getHours();thismin=tz.getMinutes();thisd=tz.getDay();"
+"var dow=days[thisd];var ap='AM';var dt='Weekday';var mint='00';"
+"if(thismin>30){mint='30'}if(thish>=12){ap='PM';thish=thish-12};"
+"if (thish==0){thish=12};if(thisd==6||thisd==0){dt='Weekend'};"
+"var timestring=thish+':'+mint+ap;if(t=='h'){return timestring}"
+"if(t=='d'){return dow};if(t=='w'){return dt}}};"
);
/*
 * Plugin: getQueryParam 2.1 - return query string parameter(s)
 */
s.getQueryParam=new Function("p","d","u",""
+"var s=this,v='',i,t;d=d?d:'';u=u?u:(s.pageURL?s.pageURL:s.wd.locati"
+"on);if(u=='f')u=s.gtfs().location;while(p){i=p.indexOf(',');i=i<0?p"
+".length:i;t=s.p_gpv(p.substring(0,i),u+'');if(t)v+=v?d+t:t;p=p.subs"
+"tring(i==p.length?i:i+1)}return v");
s.p_gpv=new Function("k","u",""
+"var s=this,v='',i=u.indexOf('?'),q;if(k&&i>-1){q=u.substring(i+1);v"
+"=s.pt(q,'&','p_gvf',k)}return v");
s.p_gvf=new Function("t","k",""
+"if(t){var s=this,i=t.indexOf('='),p=i<0?t:t.substring(0,i),v=i<0?'T"
+"rue':t.substring(i+1);if(p.toLowerCase()==k.toLowerCase())return s."
+"epa(v)}return ''");
/*
 * Plugin: getValOnce 0.2 - get a value once per session or number of days
 */
s.getValOnce=new Function("v","c","e",""
+"var s=this,k=s.c_r(c),a=new Date;e=e?e:0;if(v){a.setTime(a.getTime("
+")+e*86400000);s.c_w(c,v,e?a:0);}return v==k?'':v");
/*
 * Utility Function: split v1.5 - split a string (JS 1.0 compatible)
 */
s.split=new Function("l","d",""
+"var i,x=0,a=new Array;while(l){i=l.indexOf(d);i=i>-1?i:l.length;a[x"
+"++]=l.substring(0,i);l=l.substring(i+d.length);}return a");
/*
 * Plugin Utility: apl v1.1
 */
s.apl=new Function("L","v","d","u",""
+"var s=this,m=0;if(!L)L='';if(u){var i,n,a=s.split(L,d);for(i=0;i<a."
+"length;i++){n=a[i];m=m||(u==1?(n==v):(n.toLowerCase()==v.toLowerCas"
+"e()));}}if(!m)L=L?L+d+v:v;return L");



/* Configure Modules and Plugins */

s.loadModule("Media")
s.Media.autoTrack=false
s.Media.trackWhilePlaying=true
s.Media.trackVars="None"
s.Media.trackEvents="None"

/* WARNING: Changing any of the below variables will cause drastic
changes to how your visitor data is collected.  Changes should only be
made when instructed to do so by your account manager.*/
s.visitorNamespace="versus"
s.trackingServer="serviceo.comcast.net"
s.trackingServerSecure="serviceos.comcast.net"

/****************************** MODULES *****************************/
/* Module: Media */
s.m_Media_c="var m=s.m_i('Media');m.cn=function(n){var m=this;return m.s.rep(m.s.rep(m.s.rep(n,\"\\n\",''),\"\\r\",''),'--**--','')};m.open=function(n,l,p,b){var m=this,i=new Object,tm=new Date,a='',"
+"x;n=m.cn(n);l=parseInt(l);if(!l)l=1;if(n&&p){if(!m.l)m.l=new Object;if(m.l[n])m.close(n);if(b&&b.id)a=b.id;for (x in m.l)if(m.l[x]&&m.l[x].a==a)m.close(m.l[x].n);i.n=n;i.l=l;i.p=m.cn(p);i.a=a;i.t=0"
+";i.ts=0;i.s=Math.floor(tm.getTime()/1000);i.lx=0;i.lt=i.s;i.lo=0;i.e='';i.to=-1;m.l[n]=i}};m.close=function(n){this.e(n,0,-1)};m.play=function(n,o){var m=this,i;i=m.e(n,1,o);i.m=new Function('var m"
+"=s_c_il['+m._in+'],i;if(m.l){i=m.l[\"'+m.s.rep(i.n,'\"','\\\\\"')+'\"];if(i){if(i.lx==1)m.e(i.n,3,-1);i.mt=setTimeout(i.m,5000)}}');i.m()};m.stop=function(n,o){this.e(n,2,o)};m.track=function(n){va"
+"r m=this;if (m.trackWhilePlaying) {m.e(n,4,-1)}};m.e=function(n,x,o){var m=this,i,tm=new Date,ts=Math.floor(tm.getTime()/1000),ti=m.trackSeconds,tp=m.trackMilestones,z=new Array,j,d='--**--',t=1,b,"
+"v=m.trackVars,e=m.trackEvents,pe='media',pev3,w=new Object,vo=new Object;n=m.cn(n);i=n&&m.l&&m.l[n]?m.l[n]:0;if(i){w.name=n;w.length=i.l;w.playerName=i.p;if(i.to<0)w.event=\"OPEN\";else w.event=(x="
+"=1?\"PLAY\":(x==2?\"STOP\":(x==3?\"MONITOR\":\"CLOSE\")));w.openTime=new Date();w.openTime.setTime(i.s*1000);if(x>2||(x!=i.lx&&(x!=2||i.lx==1))) {b=\"Media.\"+name;pev3 = m.s.ape(i.n)+d+i.l+d+m.s.a"
+"pe(i.p)+d;if(x){if(o<0&&i.lt>0){o=(ts-i.lt)+i.lo;o=o<i.l?o:i.l-1}o=Math.floor(o);if(x>=2&&i.lo<o){i.t+=o-i.lo;i.ts+=o-i.lo;}if(x<=2){i.e+=(x==1?'S':'E')+o;i.lx=x;}else if(i.lx!=1)m.e(n,1,o);i.lt=ts"
+";i.lo=o;pev3+=i.t+d+i.s+d+(m.trackWhilePlaying&&i.to>=0?'L'+i.to:'')+i.e+(x!=2?(m.trackWhilePlaying?'L':'E')+o:'');if(m.trackWhilePlaying){b=0;pe='m_o';if(x!=4){w.offset=o;w.percent=((w.offset+1)/w"
+".length)*100;w.percent=w.percent>100?100:Math.floor(w.percent);w.timePlayed=i.t;if(m.monitor)m.monitor(m.s,w)}if(i.to<0)pe='m_s';else if(x==4)pe='m_i';else{t=0;v=e='None';ti=ti?parseInt(ti):0;z=tp?"
+"m.s.sp(tp,','):0;if(ti&&i.ts>=ti)t=1;else if(z){if(o<i.to)i.to=o;else{for(j=0;j<z.length;j++){ti=z[j]?parseInt(z[j]):0;if(ti&&((i.to+1)/i.l<ti/100)&&((o+1)/i.l>=ti/100)){t=1;j=z.length}}}}}}}else{m"
+".e(n,2,-1);if(m.trackWhilePlaying){w.offset=i.lo;w.percent=((w.offset+1)/w.length)*100;w.percent=w.percent>100?100:Math.floor(w.percent);w.timePlayed=i.t;if(m.monitor)m.monitor(m.s,w)}m.l[n]=0;if(i"
+".e){pev3+=i.t+d+i.s+d+(m.trackWhilePlaying&&i.to>=0?'L'+i.to:'')+i.e;if(m.trackWhilePlaying){v=e='None';pe='m_o'}else{t=0;m.s.fbr(b)}}else t=0;b=0}if(t){vo.linkTrackVars=v;vo.linkTrackEvents=e;vo.p"
+"e=pe;vo.pev3=pev3;m.s.t(vo,b);if(m.trackWhilePlaying){i.ts=0;i.to=o;i.e=''}}}}return i};m.ae=function(n,l,p,x,o,b){if(n&&p){var m=this;if(!m.l||!m.l[n])m.open(n,l,p,b);m.e(n,x,o)}};m.a=function(o,t"
+"){var m=this,i=o.id?o.id:o.name,n=o.name,p=0,v,c,c1,c2,xc=m.s.h,x,e,f1,f2='s_media_'+m._in+'_oc',f3='s_media_'+m._in+'_t',f4='s_media_'+m._in+'_s',f5='s_media_'+m._in+'_l',f6='s_media_'+m._in+'_m',"
+"f7='s_media_'+m._in+'_c',tcf,w;if(!i){if(!m.c)m.c=0;i='s_media_'+m._in+'_'+m.c;m.c++}if(!o.id)o.id=i;if(!o.name)o.name=n=i;if(!m.ol)m.ol=new Object;if(m.ol[i])return;m.ol[i]=o;if(!xc)xc=m.s.b;tcf=n"
+"ew Function('o','var e,p=0;try{if(o.versionInfo&&o.currentMedia&&o.controls)p=1}catch(e){p=0}return p');p=tcf(o);if(!p){tcf=new Function('o','var e,p=0,t;try{t=o.GetQuickTimeVersion();if(t)p=2}catc"
+"h(e){p=0}return p');p=tcf(o);if(!p){tcf=new Function('o','var e,p=0,t;try{t=o.GetVersionInfo();if(t)p=3}catch(e){p=0}return p');p=tcf(o)}}v=\"var m=s_c_il[\"+m._in+\"],o=m.ol['\"+i+\"']\";if(p==1){"
+"p='Windows Media Player '+o.versionInfo;c1=v+',n,p,l,x=-1,cm,c,mn;if(o){cm=o.currentMedia;c=o.controls;if(cm&&c){mn=cm.name?cm.name:c.URL;l=cm.duration;p=c.currentPosition;n=o.playState;if(n){if(n="
+"=8)x=0;if(n==3)x=1;if(n==1||n==2||n==4||n==5||n==6)x=2;}';c2='if(x>=0)m.ae(mn,l,\"'+p+'\",x,x!=2?p:-1,o)}}';c=c1+c2;if(m.s.isie&&xc){x=m.s.d.createElement('script');x.language='jscript';x.type='tex"
+"t/javascript';x.htmlFor=i;x.event='PlayStateChange(NewState)';x.defer=true;x.text=c;xc.appendChild(x);o[f6]=new Function(c1+'if(n==3){x=3;'+c2+'}setTimeout(o.'+f6+',5000)');o[f6]()}}if(p==2){p='Qui"
+"ckTime Player '+(o.GetIsQuickTimeRegistered()?'Pro ':'')+o.GetQuickTimeVersion();f1=f2;c=v+',n,x,t,l,p,p2,mn;if(o){mn=o.GetMovieName()?o.GetMovieName():o.GetURL();n=o.GetRate();t=o.GetTimeScale();l"
+"=o.GetDuration()/t;p=o.GetTime()/t;p2=o.'+f5+';if(n!=o.'+f4+'||p<p2||p-p2>5){x=2;if(n!=0)x=1;else if(p>=l)x=0;if(p<p2||p-p2>5)m.ae(mn,l,\"'+p+'\",2,p2,o);m.ae(mn,l,\"'+p+'\",x,x!=2?p:-1,o)}if(n>0&&"
+"o.'+f7+'>=10){m.ae(mn,l,\"'+p+'\",3,p,o);o.'+f7+'=0}o.'+f7+'++;o.'+f4+'=n;o.'+f5+'=p;setTimeout(\"'+v+';o.'+f2+'(0,0)\",500)}';o[f1]=new Function('a','b',c);o[f4]=-1;o[f7]=0;o[f1](0,0)}if(p==3){p='"
+"RealPlayer '+o.GetVersionInfo();f1=n+'_OnPlayStateChange';c1=v+',n,x=-1,l,p,mn;if(o){mn=o.GetTitle()?o.GetTitle():o.GetSource();n=o.GetPlayState();l=o.GetLength()/1000;p=o.GetPosition()/1000;if(n!="
+"o.'+f4+'){if(n==3)x=1;if(n==0||n==2||n==4||n==5)x=2;if(n==0&&(p>=l||p==0))x=0;if(x>=0)m.ae(mn,l,\"'+p+'\",x,x!=2?p:-1,o)}if(n==3&&(o.'+f7+'>=10||!o.'+f3+')){m.ae(mn,l,\"'+p+'\",3,p,o);o.'+f7+'=0}o."
+"'+f7+'++;o.'+f4+'=n;';c2='if(o.'+f2+')o.'+f2+'(o,n)}';if(m.s.wd[f1])o[f2]=m.s.wd[f1];m.s.wd[f1]=new Function('a','b',c1+c2);o[f1]=new Function('a','b',c1+'setTimeout(\"'+v+';o.'+f1+'(0,0)\",o.'+f3+"
+"'?500:5000);'+c2);o[f4]=-1;if(m.s.isie)o[f3]=1;o[f7]=0;o[f1](0,0)}};m.as=new Function('e','var m=s_c_il['+m._in+'],l,n;if(m.autoTrack&&m.s.d.getElementsByTagName){l=m.s.d.getElementsByTagName(m.s.i"
+"sie?\"OBJECT\":\"EMBED\");if(l)for(n=0;n<l.length;n++)m.a(l[n]);}');if(s.wd.attachEvent)s.wd.attachEvent('onload',m.as);else if(s.wd.addEventListener)s.wd.addEventListener('load',m.as,false)";
s.m_i("Media");

/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code='',s_objectID;function s_gi(un,pg,ss){var c="s._c='s_c';s.wd=window;if(!s.wd.s_c_in){s.wd.s_c_il=new Array;s.wd.s_c_in=0;}s._il=s.wd.s_c_il;s._in=s.wd.s_c_in;s._il[s._in]=s;s.wd.s_c_in++;s"
+".an=s_an;s.cls=function(x,c){var i,y='';if(!c)c=this.an;for(i=0;i<x.length;i++){n=x.substring(i,i+1);if(c.indexOf(n)>=0)y+=n}return y};s.fl=function(x,l){return x?(''+x).substring(0,l):x};s.co=func"
+"tion(o){if(!o)return o;var n=new Object,x;for(x in o)if(x.indexOf('select')<0&&x.indexOf('filter')<0)n[x]=o[x];return n};s.num=function(x){x=''+x;for(var p=0;p<x.length;p++)if(('0123456789').indexO"
+"f(x.substring(p,p+1))<0)return 0;return 1};s.rep=s_rep;s.sp=s_sp;s.jn=s_jn;s.ape=function(x){var s=this,h='0123456789ABCDEF',i,c=s.charSet,n,l,e,y='';c=c?c.toUpperCase():'';if(x){x=''+x;if(c=='AUTO"
+"'&&('').charCodeAt){for(i=0;i<x.length;i++){c=x.substring(i,i+1);n=x.charCodeAt(i);if(n>127){l=0;e='';while(n||l<4){e=h.substring(n%16,n%16+1)+e;n=(n-n%16)/16;l++}y+='%u'+e}else if(c=='+')y+='%2B';"
+"else y+=escape(c)}x=y}else{x=x?s.rep(escape(''+x),'+','%2B'):x;if(x&&c&&s.em==1&&x.indexOf('%u')<0&&x.indexOf('%U')<0){i=x.indexOf('%');while(i>=0){i++;if(h.substring(8).indexOf(x.substring(i,i+1)."
+"toUpperCase())>=0)return x.substring(0,i)+'u00'+x.substring(i);i=x.indexOf('%',i)}}}}return x};s.epa=function(x){var s=this;return x?unescape(s.rep(''+x,'+',' ')):x};s.pt=function(x,d,f,a){var s=th"
+"is,t=x,z=0,y,r;while(t){y=t.indexOf(d);y=y<0?t.length:y;t=t.substring(0,y);r=s[f](t,a);if(r)return r;z+=y+d.length;t=x.substring(z,x.length);t=z<x.length?t:''}return ''};s.isf=function(t,a){var c=a"
+".indexOf(':');if(c>=0)a=a.substring(0,c);if(t.substring(0,2)=='s_')t=t.substring(2);return (t!=''&&t==a)};s.fsf=function(t,a){var s=this;if(s.pt(a,',','isf',t))s.fsg+=(s.fsg!=''?',':'')+t;return 0}"
+";s.fs=function(x,f){var s=this;s.fsg='';s.pt(x,',','fsf',f);return s.fsg};s.si=function(wd){var s=this,c=''+s_gi,a=c.indexOf(\"{\"),b=c.lastIndexOf(\"}\"),m;c=s_fe(a>0&&b>0?c.substring(a+1,b):0);if"
+"(wd&&wd.document&&c){wd.setTimeout('function s_sv(o,n,k){var v=o[k],i;if(v){if(typeof(v)==\"string\"||typeof(v)==\"number\")n[k]=v;else if (typeof(v)==\"array\"){n[k]=new Array;for(i=0;i<v.length;i"
+"++)s_sv(v,n[k],i)}else if (typeof(v)==\"object\"){n[k]=new Object;for(i in v)s_sv(v,n[k],i)}}}function s_si(t){var wd=window,s,i,j,c,a,b;wd.s_gi=new Function(\"un\",\"pg\",\"ss\",\"'+c+'\");wd.s=s_"
+"gi(\"'+s.oun+'\");s=wd.s;s.sa(\"'+s.un+'\");s.tfs=wd;s.pt(s.vl_g,\",\",\"vo1\",t);s.lnk=s.eo=s.linkName=s.linkType=s.wd.s_objectID=s.ppu=s.pe=s.pev1=s.pev2=s.pev3=\\'\\';if(t.m_l&&t.m_nl)for(i=0;i<"
+"t.m_nl.length;i++){n=t.m_nl[i];if(n){m=t[n];c=t[\"m_\"+n];if(m&&c){c=\"\"+c;if(c.indexOf(\"function\")>=0){a=c.indexOf(\"{\");b=c.lastIndexOf(\"}\");c=a>0&&b>0?c.substring(a+1,b):0;s[\"m_\"+n+\"_c"
+"\"]=c;if(m._e)s.loadModule(n);if(s[n])for(j=0;j<m._l.length;j++)s_sv(m,s[n],m._l[j])}}}}}var e,o,t;try{o=window.opener;if(o&&o.s_gi){t=o.s_gi(\"'+s.un+'\");if(t)s_si(t)}}catch(e){}',1)}};s.c_d='';s"
+".c_gdf=function(t,a){var s=this;if(!s.num(t))return 1;return 0};s.c_gd=function(){var s=this,d=s.wd.location.hostname,n=s.fpCookieDomainPeriods,p;if(!n)n=s.cookieDomainPeriods;if(d&&!s.c_d){n=n?par"
+"seInt(n):2;n=n>2?n:2;p=d.lastIndexOf('.');if(p>=0){while(p>=0&&n>1){p=d.lastIndexOf('.',p-1);n--}s.c_d=p>0&&s.pt(d,'.','c_gdf',0)?d.substring(p):d}}return s.c_d};s.c_r=function(k){var s=this;k=s.ap"
+"e(k);var c=' '+s.d.cookie,i=c.indexOf(' '+k+'='),e=i<0?i:c.indexOf(';',i),v=i<0?'':s.epa(c.substring(i+2+k.length,e<0?c.length:e));return v!='[[B]]'?v:''};s.c_w=function(k,v,e){var s=this,d=s.c_gd("
+"),l=s.cookieLifetime,t;v=''+v;l=l?(''+l).toUpperCase():'';if(e&&l!='SESSION'&&l!='NONE'){t=(v!=''?parseInt(l?l:0):-60);if(t){e=new Date;e.setTime(e.getTime()+(t*1000))}}if(k&&l!='NONE'){s.d.cookie="
+"k+'='+s.ape(v!=''?v:'[[B]]')+'; path=/;'+(e&&l!='SESSION'?' expires='+e.toGMTString()+';':'')+(d?' domain='+d+';':'');return s.c_r(k)==v}return 0};s.eh=function(o,e,r,f){var s=this,b='s_'+e+'_'+s._"
+"in,n=-1,l,i,x;if(!s.ehl)s.ehl=new Array;l=s.ehl;for(i=0;i<l.length&&n<0;i++){if(l[i].o==o&&l[i].e==e)n=i}if(n<0){n=i;l[n]=new Object}x=l[n];x.o=o;x.e=e;f=r?x.b:f;if(r||f){x.b=r?0:o[e];x.o[e]=f}if(x"
+".b){x.o[b]=x.b;return b}return 0};s.cet=function(f,a,t,o,b){var s=this,r,tcf;if(s.apv>=5&&(!s.isopera||s.apv>=7)){tcf=new Function('s','f','a','t','var e,r;try{r=s[f](a)}catch(e){r=s[t](e)}return r"
+"');r=tcf(s,f,a,t)}else{if(s.ismac&&s.u.indexOf('MSIE 4')>=0)r=s[b](a);else{s.eh(s.wd,'onerror',0,o);r=s[f](a);s.eh(s.wd,'onerror',1)}}return r};s.gtfset=function(e){var s=this;return s.tfs};s.gtfso"
+"e=new Function('e','var s=s_c_il['+s._in+'],c;s.eh(window,\"onerror\",1);s.etfs=1;c=s.t();if(c)s.d.write(c);s.etfs=0;return true');s.gtfsfb=function(a){return window};s.gtfsf=function(w){var s=this"
+",p=w.parent,l=w.location;s.tfs=w;if(p&&p.location!=l&&p.location.host==l.host){s.tfs=p;return s.gtfsf(s.tfs)}return s.tfs};s.gtfs=function(){var s=this;if(!s.tfs){s.tfs=s.wd;if(!s.etfs)s.tfs=s.cet("
+"'gtfsf',s.tfs,'gtfset',s.gtfsoe,'gtfsfb')}return s.tfs};s.mrq=function(u){var s=this,l=s.rl[u],n,r;s.rl[u]=0;if(l)for(n=0;n<l.length;n++){r=l[n];s.mr(0,0,r.r,0,r.t,r.u)}};s.br=function(id,rs){var s"
+"=this;if(s.disableBufferedRequests||!s.c_w('s_br',rs))s.brl=rs};s.flushBufferedRequests=function(){this.fbr(0)};s.fbr=function(id){var s=this,br=s.c_r('s_br');if(!br)br=s.brl;if(br){if(!s.disableBu"
+"fferedRequests)s.c_w('s_br','');s.mr(0,0,br)}s.brl=0};s.mr=function(sess,q,rs,id,ta,u){var s=this,dc=s.dc,t1=s.trackingServer,t2=s.trackingServerSecure,tb=s.trackingServerBase,p='.sc',ns=s.visitorN"
+"amespace,un=s.cls(u?u:(ns?ns:s.fun)),r=new Object,l,imn='s_i_'+(un),im,b,e;if(!rs){if(t1){if(t2&&s.ssl)t1=t2}else{if(!tb)tb='2o7.net';if(dc)dc=(''+dc).toLowerCase();else dc='d1';if(tb=='2o7.net'){i"
+"f(dc=='d1')dc='112';else if(dc=='d2')dc='122';p=''}t1=un+'.'+dc+'.'+p+tb}rs='http'+(s.ssl?'s':'')+'://'+t1+'/b/ss/'+s.un+'/'+(s.mobile?'5.1':'1')+'/H.20.3/'+sess+'?AQB=1&ndh=1'+(q?q:'')+'&AQE=1';if"
+"(s.isie&&!s.ismac){if(s.apv>5.5)rs=s.fl(rs,4095);else rs=s.fl(rs,2047)}if(id){s.br(id,rs);return}}if(s.d.images&&s.apv>=3&&(!s.isopera||s.apv>=7)&&(s.ns6<0||s.apv>=6.1)){if(!s.rc)s.rc=new Object;if"
+"(!s.rc[un]){s.rc[un]=1;if(!s.rl)s.rl=new Object;s.rl[un]=new Array;setTimeout('if(window.s_c_il)window.s_c_il['+s._in+'].mrq(\"'+un+'\")',750)}else{l=s.rl[un];if(l){r.t=ta;r.u=un;r.r=rs;l[l.length]"
+"=r;return ''}imn+='_'+s.rc[un];s.rc[un]++}im=s.wd[imn];if(!im)im=s.wd[imn]=new Image;im.s_l=0;im.onload=new Function('e','this.s_l=1;var wd=window,s;if(wd.s_c_il){s=wd.s_c_il['+s._in+'];s.mrq(\"'+u"
+"n+'\");s.nrs--;if(!s.nrs)s.m_m(\"rr\")}');if(!s.nrs){s.nrs=1;s.m_m('rs')}else s.nrs++;im.src=rs;if(rs.indexOf('&pe=')>=0&&(!ta||ta=='_self'||ta=='_top'||(s.wd.name&&ta==s.wd.name))){b=e=new Date;wh"
+"ile(!im.s_l&&e.getTime()-b.getTime()<500)e=new Date}return ''}return '<im'+'g sr'+'c=\"'+rs+'\" width=1 height=1 border=0 alt=\"\">'};s.gg=function(v){var s=this;if(!s.wd['s_'+v])s.wd['s_'+v]='';re"
+"turn s.wd['s_'+v]};s.glf=function(t,a){if(t.substring(0,2)=='s_')t=t.substring(2);var s=this,v=s.gg(t);if(v)s[t]=v};s.gl=function(v){var s=this;if(s.pg)s.pt(v,',','glf',0)};s.rf=function(x){var s=t"
+"his,y,i,j,h,l,a,b='',c='',t;if(x){y=''+x;i=y.indexOf('?');if(i>0){a=y.substring(i+1);y=y.substring(0,i);h=y.toLowerCase();i=0;if(h.substring(0,7)=='http://')i+=7;else if(h.substring(0,8)=='https://"
+"')i+=8;h=h.substring(i);i=h.indexOf(\"/\");if(i>0){h=h.substring(0,i);if(h.indexOf('google')>=0){a=s.sp(a,'&');if(a.length>1){l=',q,ie,start,search_key,word,kw,cd,';for(j=0;j<a.length;j++){t=a[j];i"
+"=t.indexOf('=');if(i>0&&l.indexOf(','+t.substring(0,i)+',')>=0)b+=(b?'&':'')+t;else c+=(c?'&':'')+t}if(b&&c){y+='?'+b+'&'+c;if(''+x!=y)x=y}}}}}}return x};s.hav=function(){var s=this,qs='',fv=s.link"
+"TrackVars,fe=s.linkTrackEvents,mn,i;if(s.pe){mn=s.pe.substring(0,1).toUpperCase()+s.pe.substring(1);if(s[mn]){fv=s[mn].trackVars;fe=s[mn].trackEvents}}fv=fv?fv+','+s.vl_l+','+s.vl_l2:'';for(i=0;i<s"
+".va_t.length;i++){var k=s.va_t[i],v=s[k],b=k.substring(0,4),x=k.substring(4),n=parseInt(x),q=k;if(v&&k!='linkName'&&k!='linkType'){if(s.pe||s.lnk||s.eo){if(fv&&(','+fv+',').indexOf(','+k+',')<0)v='"
+"';if(k=='events'&&fe)v=s.fs(v,fe)}if(v){if(k=='dynamicVariablePrefix')q='D';else if(k=='visitorID')q='vid';else if(k=='pageURL'){q='g';v=s.fl(v,255)}else if(k=='referrer'){q='r';v=s.fl(s.rf(v),255)"
+"}else if(k=='vmk'||k=='visitorMigrationKey')q='vmt';else if(k=='visitorMigrationServer'){q='vmf';if(s.ssl&&s.visitorMigrationServerSecure)v=''}else if(k=='visitorMigrationServerSecure'){q='vmf';if("
+"!s.ssl&&s.visitorMigrationServer)v=''}else if(k=='charSet'){q='ce';if(v.toUpperCase()=='AUTO')v='ISO8859-1';else if(s.em==2)v='UTF-8'}else if(k=='visitorNamespace')q='ns';else if(k=='cookieDomainPe"
+"riods')q='cdp';else if(k=='cookieLifetime')q='cl';else if(k=='variableProvider')q='vvp';else if(k=='currencyCode')q='cc';else if(k=='channel')q='ch';else if(k=='transactionID')q='xact';else if(k=='"
+"campaign')q='v0';else if(k=='resolution')q='s';else if(k=='colorDepth')q='c';else if(k=='javascriptVersion')q='j';else if(k=='javaEnabled')q='v';else if(k=='cookiesEnabled')q='k';else if(k=='browse"
+"rWidth')q='bw';else if(k=='browserHeight')q='bh';else if(k=='connectionType')q='ct';else if(k=='homepage')q='hp';else if(k=='plugins')q='p';else if(s.num(x)){if(b=='prop')q='c'+n;else if(b=='eVar')"
+"q='v'+n;else if(b=='list')q='l'+n;else if(b=='hier'){q='h'+n;v=s.fl(v,255)}}if(v)qs+='&'+q+'='+(k.substring(0,3)!='pev'?s.ape(v):v)}}}return qs};s.ltdf=function(t,h){t=t?t.toLowerCase():'';h=h?h.to"
+"LowerCase():'';var qi=h.indexOf('?');h=qi>=0?h.substring(0,qi):h;if(t&&h.substring(h.length-(t.length+1))=='.'+t)return 1;return 0};s.ltef=function(t,h){t=t?t.toLowerCase():'';h=h?h.toLowerCase():'"
+"';if(t&&h.indexOf(t)>=0)return 1;return 0};s.lt=function(h){var s=this,lft=s.linkDownloadFileTypes,lef=s.linkExternalFilters,lif=s.linkInternalFilters;lif=lif?lif:s.wd.location.hostname;h=h.toLower"
+"Case();if(s.trackDownloadLinks&&lft&&s.pt(lft,',','ltdf',h))return 'd';if(s.trackExternalLinks&&h.substring(0,1)!='#'&&(lef||lif)&&(!lef||s.pt(lef,',','ltef',h))&&(!lif||!s.pt(lif,',','ltef',h)))re"
+"turn 'e';return ''};s.lc=new Function('e','var s=s_c_il['+s._in+'],b=s.eh(this,\"onclick\");s.lnk=s.co(this);s.t();s.lnk=0;if(b)return this[b](e);return true');s.bc=new Function('e','var s=s_c_il['"
+"+s._in+'],f,tcf;if(s.d&&s.d.all&&s.d.all.cppXYctnr)return;s.eo=e.srcElement?e.srcElement:e.target;tcf=new Function(\"s\",\"var e;try{if(s.eo&&(s.eo.tagName||s.eo.parentElement||s.eo.parentNode))s.t"
+"()}catch(e){}\");tcf(s);s.eo=0');s.oh=function(o){var s=this,l=s.wd.location,h=o.href?o.href:'',i,j,k,p;i=h.indexOf(':');j=h.indexOf('?');k=h.indexOf('/');if(h&&(i<0||(j>=0&&i>j)||(k>=0&&i>k))){p=o"
+".protocol&&o.protocol.length>1?o.protocol:(l.protocol?l.protocol:'');i=l.pathname.lastIndexOf('/');h=(p?p+'//':'')+(o.host?o.host:(l.host?l.host:''))+(h.substring(0,1)!='/'?l.pathname.substring(0,i"
+"<0?0:i)+'/':'')+h}return h};s.ot=function(o){var t=o.tagName;t=t&&t.toUpperCase?t.toUpperCase():'';if(t=='SHAPE')t='';if(t){if(t=='INPUT'&&o.type&&o.type.toUpperCase)t=o.type.toUpperCase();else if("
+"!t&&o.href)t='A';}return t};s.oid=function(o){var s=this,t=s.ot(o),p,c,n='',x=0;if(t&&!o.s_oid){p=o.protocol;c=o.onclick;if(o.href&&(t=='A'||t=='AREA')&&(!c||!p||p.toLowerCase().indexOf('javascript"
+"')<0))n=s.oh(o);else if(c){n=s.rep(s.rep(s.rep(s.rep(''+c,\"\\r\",''),\"\\n\",''),\"\\t\",''),' ','');x=2}else if(o.value&&(t=='INPUT'||t=='SUBMIT')){n=o.value;x=3}else if(o.src&&t=='IMAGE')n=o.src"
+";if(n){o.s_oid=s.fl(n,100);o.s_oidt=x}}return o.s_oid};s.rqf=function(t,un){var s=this,e=t.indexOf('='),u=e>=0?','+t.substring(0,e)+',':'';return u&&u.indexOf(','+un+',')>=0?s.epa(t.substring(e+1))"
+":''};s.rq=function(un){var s=this,c=un.indexOf(','),v=s.c_r('s_sq'),q='';if(c<0)return s.pt(v,'&','rqf',un);return s.pt(un,',','rq',0)};s.sqp=function(t,a){var s=this,e=t.indexOf('='),q=e<0?'':s.ep"
+"a(t.substring(e+1));s.sqq[q]='';if(e>=0)s.pt(t.substring(0,e),',','sqs',q);return 0};s.sqs=function(un,q){var s=this;s.squ[un]=q;return 0};s.sq=function(q){var s=this,k='s_sq',v=s.c_r(k),x,c=0;s.sq"
+"q=new Object;s.squ=new Object;s.sqq[q]='';s.pt(v,'&','sqp',0);s.pt(s.un,',','sqs',q);v='';for(x in s.squ)if(x&&(!Object||!Object.prototype||!Object.prototype[x]))s.sqq[s.squ[x]]+=(s.sqq[s.squ[x]]?'"
+",':'')+x;for(x in s.sqq)if(x&&(!Object||!Object.prototype||!Object.prototype[x])&&s.sqq[x]&&(x==q||c<2)){v+=(v?'&':'')+s.sqq[x]+'='+s.ape(x);c++}return s.c_w(k,v,0)};s.wdl=new Function('e','var s=s"
+"_c_il['+s._in+'],r=true,b=s.eh(s.wd,\"onload\"),i,o,oc;if(b)r=this[b](e);for(i=0;i<s.d.links.length;i++){o=s.d.links[i];oc=o.onclick?\"\"+o.onclick:\"\";if((oc.indexOf(\"s_gs(\")<0||oc.indexOf(\".s"
+"_oc(\")>=0)&&oc.indexOf(\".tl(\")<0)s.eh(o,\"onclick\",0,s.lc);}return r');s.wds=function(){var s=this;if(s.apv>3&&(!s.isie||!s.ismac||s.apv>=5)){if(s.b&&s.b.attachEvent)s.b.attachEvent('onclick',s"
+".bc);else if(s.b&&s.b.addEventListener)s.b.addEventListener('click',s.bc,false);else s.eh(s.wd,'onload',0,s.wdl)}};s.vs=function(x){var s=this,v=s.visitorSampling,g=s.visitorSamplingGroup,k='s_vsn_"
+"'+s.un+(g?'_'+g:''),n=s.c_r(k),e=new Date,y=e.getYear();e.setYear(y+10+(y<1900?1900:0));if(v){v*=100;if(!n){if(!s.c_w(k,x,e))return 0;n=x}if(n%10000>v)return 0}return 1};s.dyasmf=function(t,m){if(t"
+"&&m&&m.indexOf(t)>=0)return 1;return 0};s.dyasf=function(t,m){var s=this,i=t?t.indexOf('='):-1,n,x;if(i>=0&&m){var n=t.substring(0,i),x=t.substring(i+1);if(s.pt(x,',','dyasmf',m))return n}return 0}"
+";s.uns=function(){var s=this,x=s.dynamicAccountSelection,l=s.dynamicAccountList,m=s.dynamicAccountMatch,n,i;s.un=s.un.toLowerCase();if(x&&l){if(!m)m=s.wd.location.host;if(!m.toLowerCase)m=''+m;l=l."
+"toLowerCase();m=m.toLowerCase();n=s.pt(l,';','dyasf',m);if(n)s.un=n}i=s.un.indexOf(',');s.fun=i<0?s.un:s.un.substring(0,i)};s.sa=function(un){var s=this;s.un=un;if(!s.oun)s.oun=un;else if((','+s.ou"
+"n+',').indexOf(','+un+',')<0)s.oun+=','+un;s.uns()};s.m_i=function(n,a){var s=this,m,f=n.substring(0,1),r,l,i;if(!s.m_l)s.m_l=new Object;if(!s.m_nl)s.m_nl=new Array;m=s.m_l[n];if(!a&&m&&m._e&&!m._i"
+")s.m_a(n);if(!m){m=new Object,m._c='s_m';m._in=s.wd.s_c_in;m._il=s._il;m._il[m._in]=m;s.wd.s_c_in++;m.s=s;m._n=n;m._l=new Array('_c','_in','_il','_i','_e','_d','_dl','s','n','_r','_g','_g1','_t','_"
+"t1','_x','_x1','_rs','_rr','_l');s.m_l[n]=m;s.m_nl[s.m_nl.length]=n}else if(m._r&&!m._m){r=m._r;r._m=m;l=m._l;for(i=0;i<l.length;i++)if(m[l[i]])r[l[i]]=m[l[i]];r._il[r._in]=r;m=s.m_l[n]=r}if(f==f.t"
+"oUpperCase())s[n]=m;return m};s.m_a=new Function('n','g','e','if(!g)g=\"m_\"+n;var s=s_c_il['+s._in+'],c=s[g+\"_c\"],m,x,f=0;if(!c)c=s.wd[\"s_\"+g+\"_c\"];if(c&&s_d)s[g]=new Function(\"s\",s_ft(s_d"
+"(c)));x=s[g];if(!x)x=s.wd[\\'s_\\'+g];if(!x)x=s.wd[g];m=s.m_i(n,1);if(x&&(!m._i||g!=\"m_\"+n)){m._i=f=1;if((\"\"+x).indexOf(\"function\")>=0)x(s);else s.m_m(\"x\",n,x,e)}m=s.m_i(n,1);if(m._dl)m._dl"
+"=m._d=0;s.dlt();return f');s.m_m=function(t,n,d,e){t='_'+t;var s=this,i,x,m,f='_'+t,r=0,u;if(s.m_l&&s.m_nl)for(i=0;i<s.m_nl.length;i++){x=s.m_nl[i];if(!n||x==n){m=s.m_i(x);u=m[t];if(u){if((''+u).in"
+"dexOf('function')>=0){if(d&&e)u=m[t](d,e);else if(d)u=m[t](d);else u=m[t]()}}if(u)r=1;u=m[t+1];if(u&&!m[f]){if((''+u).indexOf('function')>=0){if(d&&e)u=m[t+1](d,e);else if(d)u=m[t+1](d);else u=m[t+"
+"1]()}}m[f]=1;if(u)r=1}}return r};s.m_ll=function(){var s=this,g=s.m_dl,i,o;if(g)for(i=0;i<g.length;i++){o=g[i];if(o)s.loadModule(o.n,o.u,o.d,o.l,o.e,1);g[i]=0}};s.loadModule=function(n,u,d,l,e,ln){"
+"var s=this,m=0,i,g,o=0,f1,f2,c=s.h?s.h:s.b,b,tcf;if(n){i=n.indexOf(':');if(i>=0){g=n.substring(i+1);n=n.substring(0,i)}else g=\"m_\"+n;m=s.m_i(n)}if((l||(n&&!s.m_a(n,g)))&&u&&s.d&&c&&s.d.createElem"
+"ent){if(d){m._d=1;m._dl=1}if(ln){if(s.ssl)u=s.rep(u,'http:','https:');i='s_s:'+s._in+':'+n+':'+g;b='var s=s_c_il['+s._in+'],o=s.d.getElementById(\"'+i+'\");if(s&&o){if(!o.l&&s.wd.'+g+'){o.l=1;if(o."
+"i)clearTimeout(o.i);o.i=0;s.m_a(\"'+n+'\",\"'+g+'\"'+(e?',\"'+e+'\"':'')+')}';f2=b+'o.c++;if(!s.maxDelay)s.maxDelay=250;if(!o.l&&o.c<(s.maxDelay*2)/100)o.i=setTimeout(o.f2,100)}';f1=new Function('e"
+"',b+'}');tcf=new Function('s','c','i','u','f1','f2','var e,o=0;try{o=s.d.createElement(\"script\");if(o){o.type=\"text/javascript\";'+(n?'o.id=i;o.defer=true;o.onload=o.onreadystatechange=f1;o.f2=f"
+"2;o.l=0;':'')+'o.src=u;c.appendChild(o);'+(n?'o.c=0;o.i=setTimeout(f2,100)':'')+'}}catch(e){o=0}return o');o=tcf(s,c,i,u,f1,f2)}else{o=new Object;o.n=n+':'+g;o.u=u;o.d=d;o.l=l;o.e=e;g=s.m_dl;if(!g)"
+"g=s.m_dl=new Array;i=0;while(i<g.length&&g[i])i++;g[i]=o}}else if(n){m=s.m_i(n);m._e=1}return m};s.vo1=function(t,a){if(a[t]||a['!'+t])this[t]=a[t]};s.vo2=function(t,a){if(!a[t]){a[t]=this[t];if(!a"
+"[t])a['!'+t]=1}};s.dlt=new Function('var s=s_c_il['+s._in+'],d=new Date,i,vo,f=0;if(s.dll)for(i=0;i<s.dll.length;i++){vo=s.dll[i];if(vo){if(!s.m_m(\"d\")||d.getTime()-vo._t>=s.maxDelay){s.dll[i]=0;"
+"s.t(vo)}else f=1}}if(s.dli)clearTimeout(s.dli);s.dli=0;if(f){if(!s.dli)s.dli=setTimeout(s.dlt,s.maxDelay)}else s.dll=0');s.dl=function(vo){var s=this,d=new Date;if(!vo)vo=new Object;s.pt(s.vl_g,','"
+",'vo2',vo);vo._t=d.getTime();if(!s.dll)s.dll=new Array;s.dll[s.dll.length]=vo;if(!s.maxDelay)s.maxDelay=250;s.dlt()};s.t=function(vo,id){var s=this,trk=1,tm=new Date,sed=Math&&Math.random?Math.floo"
+"r(Math.random()*10000000000000):tm.getTime(),sess='s'+Math.floor(tm.getTime()/10800000)%10+sed,y=tm.getYear(),vt=tm.getDate()+'/'+tm.getMonth()+'/'+(y<1900?y+1900:y)+' '+tm.getHours()+':'+tm.getMin"
+"utes()+':'+tm.getSeconds()+' '+tm.getDay()+' '+tm.getTimezoneOffset(),tcf,tfs=s.gtfs(),ta='',q='',qs='',code='',vb=new Object;s.gl(s.vl_g);s.uns();s.m_ll();if(!s.td){var tl=tfs.location,a,o,i,x='',"
+"c='',v='',p='',bw='',bh='',j='1.0',k=s.c_w('s_cc','true',0)?'Y':'N',hp='',ct='',pn=0,ps;if(String&&String.prototype){j='1.1';if(j.match){j='1.2';if(tm.setUTCDate){j='1.3';if(s.isie&&s.ismac&&s.apv>"
+"=5)j='1.4';if(pn.toPrecision){j='1.5';a=new Array;if(a.forEach){j='1.6';i=0;o=new Object;tcf=new Function('o','var e,i=0;try{i=new Iterator(o)}catch(e){}return i');i=tcf(o);if(i&&i.next)j='1.7'}}}}"
+"}if(s.apv>=4)x=screen.width+'x'+screen.height;if(s.isns||s.isopera){if(s.apv>=3){v=s.n.javaEnabled()?'Y':'N';if(s.apv>=4){c=screen.pixelDepth;bw=s.wd.innerWidth;bh=s.wd.innerHeight}}s.pl=s.n.plugin"
+"s}else if(s.isie){if(s.apv>=4){v=s.n.javaEnabled()?'Y':'N';c=screen.colorDepth;if(s.apv>=5){bw=s.d.documentElement.offsetWidth;bh=s.d.documentElement.offsetHeight;if(!s.ismac&&s.b){tcf=new Function"
+"('s','tl','var e,hp=0;try{s.b.addBehavior(\"#default#homePage\");hp=s.b.isHomePage(tl)?\"Y\":\"N\"}catch(e){}return hp');hp=tcf(s,tl);tcf=new Function('s','var e,ct=0;try{s.b.addBehavior(\"#default"
+"#clientCaps\");ct=s.b.connectionType}catch(e){}return ct');ct=tcf(s)}}}else r=''}if(s.pl)while(pn<s.pl.length&&pn<30){ps=s.fl(s.pl[pn].name,100)+';';if(p.indexOf(ps)<0)p+=ps;pn++}s.resolution=x;s.c"
+"olorDepth=c;s.javascriptVersion=j;s.javaEnabled=v;s.cookiesEnabled=k;s.browserWidth=bw;s.browserHeight=bh;s.connectionType=ct;s.homepage=hp;s.plugins=p;s.td=1}if(vo){s.pt(s.vl_g,',','vo2',vb);s.pt("
+"s.vl_g,',','vo1',vo)}if(s.usePlugins)s.doPlugins(s);var l=s.wd.location,r=tfs.document.referrer;if(!s.pageURL)s.pageURL=l.href?l.href:l;if(!s.referrer&&!s._1_referrer){s.referrer=r;s._1_referrer=1}"
+"if((vo&&vo._t)||!s.m_m('d')){s.m_m('g');if(s.lnk||s.eo){var o=s.eo?s.eo:s.lnk;if(!o)return '';var p=s.pageName,w=1,t=s.ot(o),n=s.oid(o),x=o.s_oidt,h,l,i,oc;if(s.eo&&o==s.eo){while(o&&!n&&t!='BODY')"
+"{o=o.parentElement?o.parentElement:o.parentNode;if(!o)return '';t=s.ot(o);n=s.oid(o);x=o.s_oidt}oc=o.onclick?''+o.onclick:'';if((oc.indexOf(\"s_gs(\")>=0&&oc.indexOf(\".s_oc(\")<0)||oc.indexOf(\".t"
+"l(\")>=0)return ''}ta=n?o.target:1;h=s.oh(o);i=h.indexOf('?');h=s.linkLeaveQueryString||i<0?h:h.substring(0,i);l=s.linkName;t=s.linkType?s.linkType.toLowerCase():s.lt(h);if(t&&(h||l))q+='&pe=lnk_'+"
+"(t=='d'||t=='e'?s.ape(t):'o')+(h?'&pev1='+s.ape(h):'')+(l?'&pev2='+s.ape(l):'');else trk=0;if(s.trackInlineStats){if(!p){p=s.pageURL;w=0}t=s.ot(o);i=o.sourceIndex;if(s.gg('objectID')){n=s.gg('objec"
+"tID');x=1;i=1}if(p&&n&&t)qs='&pid='+s.ape(s.fl(p,255))+(w?'&pidt='+w:'')+'&oid='+s.ape(s.fl(n,100))+(x?'&oidt='+x:'')+'&ot='+s.ape(t)+(i?'&oi='+i:'')}}if(!trk&&!qs)return '';s.sampled=s.vs(sed);if("
+"trk){if(s.sampled)code=s.mr(sess,(vt?'&t='+s.ape(vt):'')+s.hav()+q+(qs?qs:s.rq(s.un)),0,id,ta);qs='';s.m_m('t');if(s.p_r)s.p_r();s.referrer=''}s.sq(qs);}else{s.dl(vo);}if(vo)s.pt(s.vl_g,',','vo1',v"
+"b);s.lnk=s.eo=s.linkName=s.linkType=s.wd.s_objectID=s.ppu=s.pe=s.pev1=s.pev2=s.pev3='';if(s.pg)s.wd.s_lnk=s.wd.s_eo=s.wd.s_linkName=s.wd.s_linkType='';if(!id&&!s.tc){s.tc=1;s.flushBufferedRequests("
+")}return code};s.tl=function(o,t,n,vo){var s=this;s.lnk=s.co(o);s.linkType=t;s.linkName=n;s.t(vo)};if(pg){s.wd.s_co=function(o){var s=s_gi(\"_\",1,1);return s.co(o)};s.wd.s_gs=function(un){var s=s_"
+"gi(un,1,1);return s.t()};s.wd.s_dc=function(un){var s=s_gi(un,1);return s.t()}}s.ssl=(s.wd.location.protocol.toLowerCase().indexOf('https')>=0);s.d=document;s.b=s.d.body;if(s.d.getElementsByTagName"
+"){s.h=s.d.getElementsByTagName('HEAD');if(s.h)s.h=s.h[0]}s.n=navigator;s.u=s.n.userAgent;s.ns6=s.u.indexOf('Netscape6/');var apn=s.n.appName,v=s.n.appVersion,ie=v.indexOf('MSIE '),o=s.u.indexOf('Op"
+"era '),i;if(v.indexOf('Opera')>=0||o>0)apn='Opera';s.isie=(apn=='Microsoft Internet Explorer');s.isns=(apn=='Netscape');s.isopera=(apn=='Opera');s.ismac=(s.u.indexOf('Mac')>=0);if(o>0)s.apv=parseFl"
+"oat(s.u.substring(o+6));else if(ie>0){s.apv=parseInt(i=v.substring(ie+5));if(s.apv>3)s.apv=parseFloat(i)}else if(s.ns6>0)s.apv=parseFloat(s.u.substring(s.ns6+10));else s.apv=parseFloat(v);s.em=0;if"
+"(String.fromCharCode){i=escape(String.fromCharCode(256)).toUpperCase();s.em=(i=='%C4%80'?2:(i=='%U0100'?1:0))}s.sa(un);s.vl_l='dynamicVariablePrefix,visitorID,vmk,visitorMigrationKey,visitorMigrati"
+"onServer,visitorMigrationServerSecure,ppu,charSet,visitorNamespace,cookieDomainPeriods,cookieLifetime,pageName,pageURL,referrer,currencyCode';s.va_l=s.sp(s.vl_l,',');s.vl_t=s.vl_l+',variableProvide"
+"r,channel,server,pageType,transactionID,purchaseID,campaign,state,zip,events,products,linkName,linkType';for(var n=1;n<51;n++)s.vl_t+=',prop'+n+',eVar'+n+',hier'+n+',list'+n;s.vl_l2=',tnt,pe,pev1,p"
+"ev2,pev3,resolution,colorDepth,javascriptVersion,javaEnabled,cookiesEnabled,browserWidth,browserHeight,connectionType,homepage,plugins';s.vl_t+=s.vl_l2;s.va_t=s.sp(s.vl_t,',');s.vl_g=s.vl_t+',track"
+"ingServer,trackingServerSecure,trackingServerBase,fpCookieDomainPeriods,disableBufferedRequests,mobile,visitorSampling,visitorSamplingGroup,dynamicAccountSelection,dynamicAccountList,dynamicAccount"
+"Match,trackDownloadLinks,trackExternalLinks,trackInlineStats,linkLeaveQueryString,linkDownloadFileTypes,linkExternalFilters,linkInternalFilters,linkTrackVars,linkTrackEvents,linkNames,lnk,eo,_1_ref"
+"errer';s.va_g=s.sp(s.vl_g,',');s.pg=pg;s.gl(s.vl_g);if(!ss)s.wds()",
w=window,l=w.s_c_il,n=navigator,u=n.userAgent,v=n.appVersion,e=v.indexOf('MSIE '),m=u.indexOf('Netscape6/'),a,i,s;if(un){un=un.toLowerCase();if(l)for(i=0;i<l.length;i++){s=l[i];if(!s._c||s._c=='s_c'){if(s.oun==un)return s;else if(s.fs&&s.sa&&s.fs(s.oun,un)){s.sa(un);return s}}}}w.s_an='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
w.s_sp=new Function("x","d","var a=new Array,i=0,j;if(x){if(x.split)a=x.split(d);else if(!d)for(i=0;i<x.length;i++)a[a.length]=x.substring(i,i+1);else while(i>=0){j=x.indexOf(d,i);a[a.length]=x.subst"
+"ring(i,j<0?x.length:j);i=j;if(i>=0)i+=d.length}}return a");
w.s_jn=new Function("a","d","var x='',i,j=a.length;if(a&&j>0){x=a[0];if(j>1){if(a.join)x=a.join(d);else for(i=1;i<j;i++)x+=d+a[i]}}return x");
w.s_rep=new Function("x","o","n","return s_jn(s_sp(x,o),n)");
w.s_d=new Function("x","var t='`^@$#',l=s_an,l2=new Object,x2,d,b=0,k,i=x.lastIndexOf('~~'),j,v,w;if(i>0){d=x.substring(0,i);x=x.substring(i+2);l=s_sp(l,'');for(i=0;i<62;i++)l2[l[i]]=i;t=s_sp(t,'');d"
+"=s_sp(d,'~');i=0;while(i<5){v=0;if(x.indexOf(t[i])>=0) {x2=s_sp(x,t[i]);for(j=1;j<x2.length;j++){k=x2[j].substring(0,1);w=t[i]+k;if(k!=' '){v=1;w=d[b+l2[k]]}x2[j]=w+x2[j].substring(1)}}if(v)x=s_jn("
+"x2,'');else{w=t[i]+' ';if(x.indexOf(w)>=0)x=s_rep(x,w,t[i]);i++;b+=62}}}return x");
w.s_fe=new Function("c","return s_rep(s_rep(s_rep(c,'\\\\','\\\\\\\\'),'\"','\\\\\"'),\"\\n\",\"\\\\n\")");
w.s_fa=new Function("f","var s=f.indexOf('(')+1,e=f.indexOf(')'),a='',c;while(s>=0&&s<e){c=f.substring(s,s+1);if(c==',')a+='\",\"';else if((\"\\n\\r\\t \").indexOf(c)<0)a+=c;s++}return a?'\"'+a+'\"':"
+"a");
w.s_ft=new Function("c","c+='';var s,e,o,a,d,q,f,h,x;s=c.indexOf('=function(');while(s>=0){s++;d=1;q='';x=0;f=c.substring(s);a=s_fa(f);e=o=c.indexOf('{',s);e++;while(d>0){h=c.substring(e,e+1);if(q){i"
+"f(h==q&&!x)q='';if(h=='\\\\')x=x?0:1;else x=0}else{if(h=='\"'||h==\"'\")q=h;if(h=='{')d++;if(h=='}')d--}if(d>0)e++}c=c.substring(0,s)+'new Function('+(a?a+',':'')+'\"'+s_fe(c.substring(o+1,e))+'\")"
+"'+c.substring(e+1);s=c.indexOf('=function(')}return c;");
c=s_d(c);if(e>0){a=parseInt(i=v.substring(e+5));if(a>3)a=parseFloat(i)}else if(m>0)a=parseFloat(u.substring(m+10));else a=parseFloat(v);if(a>=5&&v.indexOf('Opera')<0&&u.indexOf('Opera')<0){w.s_c=new Function("un","pg","ss","var s=this;"+c);return new s_c(un,pg,ss)}else s=new Function("un","pg","ss","var s=new Object;"+s_ft(c)+";return s");return s(un,pg,ss)}



var g_sEnvironmentCurrent = 'live';
        var g_sEnvironmentLive    = 'live';
        var g_sResourceUrl = 'http://www.vsimgcdn.com/';
    
        var g_xServerUrl = 'http://sitelife.versus.com/ver1.0/Direct/Process';
  var g_xPhotoUploadUrl = 'http://sitelife.versus.com/ver1.0/Photo/Upload';
        var g_xVideoUploadUrl = 'http://sitelife.versus.com/ver1.0/video/Upload';
        
        var g_xVersusBaseDomain= 'www.versus.com';
        var g_sDelimiter = '_';
        var g_sYesKey = '1';
var g_sNoKey = '0';
        var g_sDataSourceCMS = 'cms';
        var g_sDataSourcePluck = 'pluck';
        var uploadFormCounter = 10000;
        
        g_aOfficialGroupsArray = new Array();
        g_aOfficialGroupsArray["nhl"] = "c272c3d3-4c26-4ded-b3e0-e75d364ecdff";g_aOfficialGroupsArray["cycling"] = "785236ff-2689-4288-b33d-6d23e5d120d6";g_aOfficialGroupsArray["hunting"] = "37ce019d-9952-47b5-bb90-c91f600376c7";g_aOfficialGroupsArray["fishing"] = "c54a9a80-e1a0-4e7a-94f5-1e9be493bbe2";g_aOfficialGroupsArray["mma"] = "a52c812b-196e-475d-a8c6-be655f75bb4e";g_aOfficialGroupsArray["college-football"] = "fb279397-abe4-4c58-88db-c40323a138d0";g_aOfficialGroupsArray["indycar"] = "57a1efe5-ee10-469c-abcb-567f14f86476";g_aOfficialGroupsArray["bull-riding"] = "9756871c-a011-46ef-a09d-49a719b2fa2e";g_aOfficialGroupsArray["default"] = "7a718045-1a87-4e7b-bed6-777f8287b558";        
        g_aPluckArticleItemTypes = new Array();
        g_aPluckArticleItemTypes['207'] = "video";
        g_aPluckArticleItemTypes['206'] = "photo";
        g_aPluckArticleItemTypes['108'] = "blog";
         
        document.domain = "versus.com";
                
        RELEASE_VERSION = 213;
        
           
 