/*! jQuery v1.11.2 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.2",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=hb(),z=hb(),A=hb(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},eb=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fb){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function gb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+rb(o[l]);w=ab.test(a)&&pb(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function hb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ib(a){return a[u]=!0,a}function jb(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function kb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function lb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function nb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function ob(a){return ib(function(b){return b=+b,ib(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pb(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=gb.support={},f=gb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=gb.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",eb,!1):e.attachEvent&&e.attachEvent("onunload",eb)),p=!f(g),c.attributes=jb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=jb(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=jb(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(jb(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),jb(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&jb(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return lb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?lb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},gb.matches=function(a,b){return gb(a,null,null,b)},gb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return gb(b,n,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},gb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=gb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=gb.selectors={cacheLength:50,createPseudo:ib,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&gb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=gb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||gb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ib(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ib(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ib(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ib(function(a){return function(b){return gb(a,b).length>0}}),contains:ib(function(a){return a=a.replace(cb,db),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ib(function(a){return W.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:ob(function(){return[0]}),last:ob(function(a,b){return[b-1]}),eq:ob(function(a,b,c){return[0>c?c+b:c]}),even:ob(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:ob(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:ob(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:ob(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=mb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=nb(b);function qb(){}qb.prototype=d.filters=d.pseudos,d.setFilters=new qb,g=gb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?gb.error(a):z(a,i).slice(0)};function rb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function tb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ub(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function vb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wb(a,b,c,d,e,f){return d&&!d[u]&&(d=wb(d)),e&&!e[u]&&(e=wb(e,f)),ib(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ub(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:vb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=vb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=vb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sb(function(a){return a===b},h,!0),l=sb(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sb(tb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wb(i>1&&tb(m),i>1&&rb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xb(a.slice(i,e)),f>e&&xb(a=a.slice(e)),f>e&&rb(a))}m.push(c)}return tb(m)}function yb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=vb(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&gb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ib(f):f}return h=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,yb(e,d)),f.selector=a}return f},i=gb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&pb(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&rb(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&pb(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=jb(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),jb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||kb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&jb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||kb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),jb(function(a){return null==a.getAttribute("disabled")})||kb(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),gb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)
} m.Tween = Zb, Zb.prototype = { constructor: Zb, init: function (a, b, c, d, e, f) { this.elem = a, this.prop = c, this.easing = e || "swing", this.options = b, this.start = this.now = this.cur(), this.end = d, this.unit = f || (m.cssNumber[c] ? "" : "px") }, cur: function () { var a = Zb.propHooks[this.prop]; return a && a.get ? a.get(this) : Zb.propHooks._default.get(this) }, run: function (a) { var b, c = Zb.propHooks[this.prop]; return this.pos = b = this.options.duration ? m.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration) : a, this.now = (this.end - this.start) * b + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), c && c.set ? c.set(this) : Zb.propHooks._default.set(this), this } }, Zb.prototype.init.prototype = Zb.prototype, Zb.propHooks = { _default: { get: function (a) { var b; return null == a.elem[a.prop] || a.elem.style && null != a.elem.style[a.prop] ? (b = m.css(a.elem, a.prop, ""), b && "auto" !== b ? b : 0) : a.elem[a.prop] }, set: function (a) { m.fx.step[a.prop] ? m.fx.step[a.prop](a) : a.elem.style && (null != a.elem.style[m.cssProps[a.prop]] || m.cssHooks[a.prop]) ? m.style(a.elem, a.prop, a.now + a.unit) : a.elem[a.prop] = a.now } } }, Zb.propHooks.scrollTop = Zb.propHooks.scrollLeft = { set: function (a) { a.elem.nodeType && a.elem.parentNode && (a.elem[a.prop] = a.now) } }, m.easing = { linear: function (a) { return a }, swing: function (a) { return .5 - Math.cos(a * Math.PI) / 2 } }, m.fx = Zb.prototype.init, m.fx.step = {}; var $b, _b, ac = /^(?:toggle|show|hide)$/, bc = new RegExp("^(?:([+-])=|)(" + S + ")([a-z%]*)$", "i"), cc = /queueHooks$/, dc = [ic], ec = { "*": [function (a, b) { var c = this.createTween(a, b), d = c.cur(), e = bc.exec(b), f = e && e[3] || (m.cssNumber[a] ? "" : "px"), g = (m.cssNumber[a] || "px" !== f && +d) && bc.exec(m.css(c.elem, a)), h = 1, i = 20; if (g && g[3] !== f) { f = f || g[3], e = e || [], g = +d || 1; do h = h || ".5", g /= h, m.style(c.elem, a, g + f); while (h !== (h = c.cur() / d) && 1 !== h && --i) } return e && (g = c.start = +g || +d || 0, c.unit = f, c.end = e[1] ? g + (e[1] + 1) * e[2] : +e[2]), c }] }; function fc() { return setTimeout(function () { $b = void 0 }), $b = m.now() } function gc(a, b) { var c, d = { height: a }, e = 0; for (b = b ? 1 : 0; 4 > e; e += 2 - b) c = T[e], d["margin" + c] = d["padding" + c] = a; return b && (d.opacity = d.width = a), d } function hc(a, b, c) { for (var d, e = (ec[b] || []).concat(ec["*"]), f = 0, g = e.length; g > f; f++) if (d = e[f].call(c, b, a)) return d } function ic(a, b, c) { var d, e, f, g, h, i, j, l, n = this, o = {}, p = a.style, q = a.nodeType && U(a), r = m._data(a, "fxshow"); c.queue || (h = m._queueHooks(a, "fx"), null == h.unqueued && (h.unqueued = 0, i = h.empty.fire, h.empty.fire = function () { h.unqueued || i() }), h.unqueued++, n.always(function () { n.always(function () { h.unqueued--, m.queue(a, "fx").length || h.empty.fire() }) })), 1 === a.nodeType && ("height" in b || "width" in b) && (c.overflow = [p.overflow, p.overflowX, p.overflowY], j = m.css(a, "display"), l = "none" === j ? m._data(a, "olddisplay") || Fb(a.nodeName) : j, "inline" === l && "none" === m.css(a, "float") && (k.inlineBlockNeedsLayout && "inline" !== Fb(a.nodeName) ? p.zoom = 1 : p.display = "inline-block")), c.overflow && (p.overflow = "hidden", k.shrinkWrapBlocks() || n.always(function () { p.overflow = c.overflow[0], p.overflowX = c.overflow[1], p.overflowY = c.overflow[2] })); for (d in b) if (e = b[d], ac.exec(e)) { if (delete b[d], f = f || "toggle" === e, e === (q ? "hide" : "show")) { if ("show" !== e || !r || void 0 === r[d]) continue; q = !0 } o[d] = r && r[d] || m.style(a, d) } else j = void 0; if (m.isEmptyObject(o)) "inline" === ("none" === j ? Fb(a.nodeName) : j) && (p.display = j); else { r ? "hidden" in r && (q = r.hidden) : r = m._data(a, "fxshow", {}), f && (r.hidden = !q), q ? m(a).show() : n.done(function () { m(a).hide() }), n.done(function () { var b; m._removeData(a, "fxshow"); for (b in o) m.style(a, b, o[b]) }); for (d in o) g = hc(q ? r[d] : 0, d, n), d in r || (r[d] = g.start, q && (g.end = g.start, g.start = "width" === d || "height" === d ? 1 : 0)) } } function jc(a, b) { var c, d, e, f, g; for (c in a) if (d = m.camelCase(c), e = b[d], f = a[c], m.isArray(f) && (e = f[1], f = a[c] = f[0]), c !== d && (a[d] = f, delete a[c]), g = m.cssHooks[d], g && "expand" in g) { f = g.expand(f), delete a[d]; for (c in f) c in a || (a[c] = f[c], b[c] = e) } else b[d] = e } function kc(a, b, c) { var d, e, f = 0, g = dc.length, h = m.Deferred().always(function () { delete i.elem }), i = function () { if (e) return !1; for (var b = $b || fc(), c = Math.max(0, j.startTime + j.duration - b), d = c / j.duration || 0, f = 1 - d, g = 0, i = j.tweens.length; i > g; g++) j.tweens[g].run(f); return h.notifyWith(a, [j, f, c]), 1 > f && i ? c : (h.resolveWith(a, [j]), !1) }, j = h.promise({ elem: a, props: m.extend({}, b), opts: m.extend(!0, { specialEasing: {} }, c), originalProperties: b, originalOptions: c, startTime: $b || fc(), duration: c.duration, tweens: [], createTween: function (b, c) { var d = m.Tween(a, j.opts, b, c, j.opts.specialEasing[b] || j.opts.easing); return j.tweens.push(d), d }, stop: function (b) { var c = 0, d = b ? j.tweens.length : 0; if (e) return this; for (e = !0; d > c; c++) j.tweens[c].run(1); return b ? h.resolveWith(a, [j, b]) : h.rejectWith(a, [j, b]), this } }), k = j.props; for (jc(k, j.opts.specialEasing) ; g > f; f++) if (d = dc[f].call(j, a, k, j.opts)) return d; return m.map(k, hc, j), m.isFunction(j.opts.start) && j.opts.start.call(a, j), m.fx.timer(m.extend(i, { elem: a, anim: j, queue: j.opts.queue })), j.progress(j.opts.progress).done(j.opts.done, j.opts.complete).fail(j.opts.fail).always(j.opts.always) } m.Animation = m.extend(kc, { tweener: function (a, b) { m.isFunction(a) ? (b = a, a = ["*"]) : a = a.split(" "); for (var c, d = 0, e = a.length; e > d; d++) c = a[d], ec[c] = ec[c] || [], ec[c].unshift(b) }, prefilter: function (a, b) { b ? dc.unshift(a) : dc.push(a) } }), m.speed = function (a, b, c) { var d = a && "object" == typeof a ? m.extend({}, a) : { complete: c || !c && b || m.isFunction(a) && a, duration: a, easing: c && b || b && !m.isFunction(b) && b }; return d.duration = m.fx.off ? 0 : "number" == typeof d.duration ? d.duration : d.duration in m.fx.speeds ? m.fx.speeds[d.duration] : m.fx.speeds._default, (null == d.queue || d.queue === !0) && (d.queue = "fx"), d.old = d.complete, d.complete = function () { m.isFunction(d.old) && d.old.call(this), d.queue && m.dequeue(this, d.queue) }, d }, m.fn.extend({ fadeTo: function (a, b, c, d) { return this.filter(U).css("opacity", 0).show().end().animate({ opacity: b }, a, c, d) }, animate: function (a, b, c, d) { var e = m.isEmptyObject(a), f = m.speed(b, c, d), g = function () { var b = kc(this, m.extend({}, a), f); (e || m._data(this, "finish")) && b.stop(!0) }; return g.finish = g, e || f.queue === !1 ? this.each(g) : this.queue(f.queue, g) }, stop: function (a, b, c) { var d = function (a) { var b = a.stop; delete a.stop, b(c) }; return "string" != typeof a && (c = b, b = a, a = void 0), b && a !== !1 && this.queue(a || "fx", []), this.each(function () { var b = !0, e = null != a && a + "queueHooks", f = m.timers, g = m._data(this); if (e) g[e] && g[e].stop && d(g[e]); else for (e in g) g[e] && g[e].stop && cc.test(e) && d(g[e]); for (e = f.length; e--;) f[e].elem !== this || null != a && f[e].queue !== a || (f[e].anim.stop(c), b = !1, f.splice(e, 1)); (b || !c) && m.dequeue(this, a) }) }, finish: function (a) { return a !== !1 && (a = a || "fx"), this.each(function () { var b, c = m._data(this), d = c[a + "queue"], e = c[a + "queueHooks"], f = m.timers, g = d ? d.length : 0; for (c.finish = !0, m.queue(this, a, []), e && e.stop && e.stop.call(this, !0), b = f.length; b--;) f[b].elem === this && f[b].queue === a && (f[b].anim.stop(!0), f.splice(b, 1)); for (b = 0; g > b; b++) d[b] && d[b].finish && d[b].finish.call(this); delete c.finish }) } }), m.each(["toggle", "show", "hide"], function (a, b) { var c = m.fn[b]; m.fn[b] = function (a, d, e) { return null == a || "boolean" == typeof a ? c.apply(this, arguments) : this.animate(gc(b, !0), a, d, e) } }), m.each({ slideDown: gc("show"), slideUp: gc("hide"), slideToggle: gc("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function (a, b) { m.fn[a] = function (a, c, d) { return this.animate(b, a, c, d) } }), m.timers = [], m.fx.tick = function () { var a, b = m.timers, c = 0; for ($b = m.now() ; c < b.length; c++) a = b[c], a() || b[c] !== a || b.splice(c--, 1); b.length || m.fx.stop(), $b = void 0 }, m.fx.timer = function (a) { m.timers.push(a), a() ? m.fx.start() : m.timers.pop() }, m.fx.interval = 13, m.fx.start = function () { _b || (_b = setInterval(m.fx.tick, m.fx.interval)) }, m.fx.stop = function () { clearInterval(_b), _b = null }, m.fx.speeds = { slow: 600, fast: 200, _default: 400 }, m.fn.delay = function (a, b) { return a = m.fx ? m.fx.speeds[a] || a : a, b = b || "fx", this.queue(b, function (b, c) { var d = setTimeout(b, a); c.stop = function () { clearTimeout(d) } }) }, function () { var a, b, c, d, e; b = y.createElement("div"), b.setAttribute("className", "t"), b.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", d = b.getElementsByTagName("a")[0], c = y.createElement("select"), e = c.appendChild(y.createElement("option")), a = b.getElementsByTagName("input")[0], d.style.cssText = "top:1px", k.getSetAttribute = "t" !== b.className, k.style = /top/.test(d.getAttribute("style")), k.hrefNormalized = "/a" === d.getAttribute("href"), k.checkOn = !!a.value, k.optSelected = e.selected, k.enctype = !!y.createElement("form").enctype, c.disabled = !0, k.optDisabled = !e.disabled, a = y.createElement("input"), a.setAttribute("value", ""), k.input = "" === a.getAttribute("value"), a.value = "t", a.setAttribute("type", "radio"), k.radioValue = "t" === a.value }(); var lc = /\r/g; m.fn.extend({ val: function (a) { var b, c, d, e = this[0]; { if (arguments.length) return d = m.isFunction(a), this.each(function (c) { var e; 1 === this.nodeType && (e = d ? a.call(this, c, m(this).val()) : a, null == e ? e = "" : "number" == typeof e ? e += "" : m.isArray(e) && (e = m.map(e, function (a) { return null == a ? "" : a + "" })), b = m.valHooks[this.type] || m.valHooks[this.nodeName.toLowerCase()], b && "set" in b && void 0 !== b.set(this, e, "value") || (this.value = e)) }); if (e) return b = m.valHooks[e.type] || m.valHooks[e.nodeName.toLowerCase()], b && "get" in b && void 0 !== (c = b.get(e, "value")) ? c : (c = e.value, "string" == typeof c ? c.replace(lc, "") : null == c ? "" : c) } } }), m.extend({ valHooks: { option: { get: function (a) { var b = m.find.attr(a, "value"); return null != b ? b : m.trim(m.text(a)) } }, select: { get: function (a) { for (var b, c, d = a.options, e = a.selectedIndex, f = "select-one" === a.type || 0 > e, g = f ? null : [], h = f ? e + 1 : d.length, i = 0 > e ? h : f ? e : 0; h > i; i++) if (c = d[i], !(!c.selected && i !== e || (k.optDisabled ? c.disabled : null !== c.getAttribute("disabled")) || c.parentNode.disabled && m.nodeName(c.parentNode, "optgroup"))) { if (b = m(c).val(), f) return b; g.push(b) } return g }, set: function (a, b) { var c, d, e = a.options, f = m.makeArray(b), g = e.length; while (g--) if (d = e[g], m.inArray(m.valHooks.option.get(d), f) >= 0) try { d.selected = c = !0 } catch (h) { d.scrollHeight } else d.selected = !1; return c || (a.selectedIndex = -1), e } } } }), m.each(["radio", "checkbox"], function () { m.valHooks[this] = { set: function (a, b) { return m.isArray(b) ? a.checked = m.inArray(m(a).val(), b) >= 0 : void 0 } }, k.checkOn || (m.valHooks[this].get = function (a) { return null === a.getAttribute("value") ? "on" : a.value }) }); var mc, nc, oc = m.expr.attrHandle, pc = /^(?:checked|selected)$/i, qc = k.getSetAttribute, rc = k.input; m.fn.extend({ attr: function (a, b) { return V(this, m.attr, a, b, arguments.length > 1) }, removeAttr: function (a) { return this.each(function () { m.removeAttr(this, a) }) } }), m.extend({ attr: function (a, b, c) { var d, e, f = a.nodeType; if (a && 3 !== f && 8 !== f && 2 !== f) return typeof a.getAttribute === K ? m.prop(a, b, c) : (1 === f && m.isXMLDoc(a) || (b = b.toLowerCase(), d = m.attrHooks[b] || (m.expr.match.bool.test(b) ? nc : mc)), void 0 === c ? d && "get" in d && null !== (e = d.get(a, b)) ? e : (e = m.find.attr(a, b), null == e ? void 0 : e) : null !== c ? d && "set" in d && void 0 !== (e = d.set(a, c, b)) ? e : (a.setAttribute(b, c + ""), c) : void m.removeAttr(a, b)) }, removeAttr: function (a, b) { var c, d, e = 0, f = b && b.match(E); if (f && 1 === a.nodeType) while (c = f[e++]) d = m.propFix[c] || c, m.expr.match.bool.test(c) ? rc && qc || !pc.test(c) ? a[d] = !1 : a[m.camelCase("default-" + c)] = a[d] = !1 : m.attr(a, c, ""), a.removeAttribute(qc ? c : d) }, attrHooks: { type: { set: function (a, b) { if (!k.radioValue && "radio" === b && m.nodeName(a, "input")) { var c = a.value; return a.setAttribute("type", b), c && (a.value = c), b } } } } }), nc = { set: function (a, b, c) { return b === !1 ? m.removeAttr(a, c) : rc && qc || !pc.test(c) ? a.setAttribute(!qc && m.propFix[c] || c, c) : a[m.camelCase("default-" + c)] = a[c] = !0, c } }, m.each(m.expr.match.bool.source.match(/\w+/g), function (a, b) { var c = oc[b] || m.find.attr; oc[b] = rc && qc || !pc.test(b) ? function (a, b, d) { var e, f; return d || (f = oc[b], oc[b] = e, e = null != c(a, b, d) ? b.toLowerCase() : null, oc[b] = f), e } : function (a, b, c) { return c ? void 0 : a[m.camelCase("default-" + b)] ? b.toLowerCase() : null } }), rc && qc || (m.attrHooks.value = { set: function (a, b, c) { return m.nodeName(a, "input") ? void (a.defaultValue = b) : mc && mc.set(a, b, c) } }), qc || (mc = { set: function (a, b, c) { var d = a.getAttributeNode(c); return d || a.setAttributeNode(d = a.ownerDocument.createAttribute(c)), d.value = b += "", "value" === c || b === a.getAttribute(c) ? b : void 0 } }, oc.id = oc.name = oc.coords = function (a, b, c) { var d; return c ? void 0 : (d = a.getAttributeNode(b)) && "" !== d.value ? d.value : null }, m.valHooks.button = { get: function (a, b) { var c = a.getAttributeNode(b); return c && c.specified ? c.value : void 0 }, set: mc.set }, m.attrHooks.contenteditable = { set: function (a, b, c) { mc.set(a, "" === b ? !1 : b, c) } }, m.each(["width", "height"], function (a, b) { m.attrHooks[b] = { set: function (a, c) { return "" === c ? (a.setAttribute(b, "auto"), c) : void 0 } } })), k.style || (m.attrHooks.style = { get: function (a) { return a.style.cssText || void 0 }, set: function (a, b) { return a.style.cssText = b + "" } }); var sc = /^(?:input|select|textarea|button|object)$/i, tc = /^(?:a|area)$/i; m.fn.extend({ prop: function (a, b) { return V(this, m.prop, a, b, arguments.length > 1) }, removeProp: function (a) { return a = m.propFix[a] || a, this.each(function () { try { this[a] = void 0, delete this[a] } catch (b) { } }) } }), m.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function (a, b, c) { var d, e, f, g = a.nodeType; if (a && 3 !== g && 8 !== g && 2 !== g) return f = 1 !== g || !m.isXMLDoc(a), f && (b = m.propFix[b] || b, e = m.propHooks[b]), void 0 !== c ? e && "set" in e && void 0 !== (d = e.set(a, c, b)) ? d : a[b] = c : e && "get" in e && null !== (d = e.get(a, b)) ? d : a[b] }, propHooks: { tabIndex: { get: function (a) { var b = m.find.attr(a, "tabindex"); return b ? parseInt(b, 10) : sc.test(a.nodeName) || tc.test(a.nodeName) && a.href ? 0 : -1 } } } }), k.hrefNormalized || m.each(["href", "src"], function (a, b) { m.propHooks[b] = { get: function (a) { return a.getAttribute(b, 4) } } }), k.optSelected || (m.propHooks.selected = { get: function (a) { var b = a.parentNode; return b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex), null } }), m.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () { m.propFix[this.toLowerCase()] = this }), k.enctype || (m.propFix.enctype = "encoding"); var uc = /[\t\r\n\f]/g; m.fn.extend({ addClass: function (a) { var b, c, d, e, f, g, h = 0, i = this.length, j = "string" == typeof a && a; if (m.isFunction(a)) return this.each(function (b) { m(this).addClass(a.call(this, b, this.className)) }); if (j) for (b = (a || "").match(E) || []; i > h; h++) if (c = this[h], d = 1 === c.nodeType && (c.className ? (" " + c.className + " ").replace(uc, " ") : " ")) { f = 0; while (e = b[f++]) d.indexOf(" " + e + " ") < 0 && (d += e + " "); g = m.trim(d), c.className !== g && (c.className = g) } return this }, removeClass: function (a) { var b, c, d, e, f, g, h = 0, i = this.length, j = 0 === arguments.length || "string" == typeof a && a; if (m.isFunction(a)) return this.each(function (b) { m(this).removeClass(a.call(this, b, this.className)) }); if (j) for (b = (a || "").match(E) || []; i > h; h++) if (c = this[h], d = 1 === c.nodeType && (c.className ? (" " + c.className + " ").replace(uc, " ") : "")) { f = 0; while (e = b[f++]) while (d.indexOf(" " + e + " ") >= 0) d = d.replace(" " + e + " ", " "); g = a ? m.trim(d) : "", c.className !== g && (c.className = g) } return this }, toggleClass: function (a, b) { var c = typeof a; return "boolean" == typeof b && "string" === c ? b ? this.addClass(a) : this.removeClass(a) : this.each(m.isFunction(a) ? function (c) { m(this).toggleClass(a.call(this, c, this.className, b), b) } : function () { if ("string" === c) { var b, d = 0, e = m(this), f = a.match(E) || []; while (b = f[d++]) e.hasClass(b) ? e.removeClass(b) : e.addClass(b) } else (c === K || "boolean" === c) && (this.className && m._data(this, "__className__", this.className), this.className = this.className || a === !1 ? "" : m._data(this, "__className__") || "") }) }, hasClass: function (a) { for (var b = " " + a + " ", c = 0, d = this.length; d > c; c++) if (1 === this[c].nodeType && (" " + this[c].className + " ").replace(uc, " ").indexOf(b) >= 0) return !0; return !1 } }), m.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 contextmenu".split(" "), function (a, b) { m.fn[b] = function (a, c) { return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b) } }), m.fn.extend({ hover: function (a, b) { return this.mouseenter(a).mouseleave(b || a) }, bind: function (a, b, c) { return this.on(a, null, b, c) }, unbind: function (a, b) { return this.off(a, null, b) }, delegate: function (a, b, c, d) { return this.on(b, a, c, d) }, undelegate: function (a, b, c) { return 1 === arguments.length ? this.off(a, "**") : this.off(b, a || "**", c) } }); var vc = m.now(), wc = /\?/, xc = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; m.parseJSON = function (b) { if (a.JSON && a.JSON.parse) return a.JSON.parse(b + ""); var c, d = null, e = m.trim(b + ""); return e && !m.trim(e.replace(xc, function (a, b, e, f) { return c && b && (d = 0), 0 === d ? a : (c = e || b, d += !f - !e, "") })) ? Function("return " + e)() : m.error("Invalid JSON: " + b) }, m.parseXML = function (b) { var c, d; if (!b || "string" != typeof b) return null; try { a.DOMParser ? (d = new DOMParser, c = d.parseFromString(b, "text/xml")) : (c = new ActiveXObject("Microsoft.XMLDOM"), c.async = "false", c.loadXML(b)) } catch (e) { c = void 0 } return c && c.documentElement && !c.getElementsByTagName("parsererror").length || m.error("Invalid XML: " + b), c }; var yc, zc, Ac = /#.*$/, Bc = /([?&])_=[^&]*/, Cc = /^(.*?):[ \t]*([^\r\n]*)\r?$/gm, Dc = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, Ec = /^(?:GET|HEAD)$/, Fc = /^\/\//, Gc = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, Hc = {}, Ic = {}, Jc = "*/".concat("*"); try { zc = location.href } catch (Kc) { zc = y.createElement("a"), zc.href = "", zc = zc.href } yc = Gc.exec(zc.toLowerCase()) || []; function Lc(a) { return function (b, c) { "string" != typeof b && (c = b, b = "*"); var d, e = 0, f = b.toLowerCase().match(E) || []; if (m.isFunction(c)) while (d = f[e++]) "+" === d.charAt(0) ? (d = d.slice(1) || "*", (a[d] = a[d] || []).unshift(c)) : (a[d] = a[d] || []).push(c) } } function Mc(a, b, c, d) { var e = {}, f = a === Ic; function g(h) { var i; return e[h] = !0, m.each(a[h] || [], function (a, h) { var j = h(b, c, d); return "string" != typeof j || f || e[j] ? f ? !(i = j) : void 0 : (b.dataTypes.unshift(j), g(j), !1) }), i } return g(b.dataTypes[0]) || !e["*"] && g("*") } function Nc(a, b) { var c, d, e = m.ajaxSettings.flatOptions || {}; for (d in b) void 0 !== b[d] && ((e[d] ? a : c || (c = {}))[d] = b[d]); return c && m.extend(!0, a, c), a } function Oc(a, b, c) { var d, e, f, g, h = a.contents, i = a.dataTypes; while ("*" === i[0]) i.shift(), void 0 === e && (e = a.mimeType || b.getResponseHeader("Content-Type")); if (e) for (g in h) if (h[g] && h[g].test(e)) { i.unshift(g); break } if (i[0] in c) f = i[0]; else { for (g in c) { if (!i[0] || a.converters[g + " " + i[0]]) { f = g; break } d || (d = g) } f = f || d } return f ? (f !== i[0] && i.unshift(f), c[f]) : void 0 } function Pc(a, b, c, d) { var e, f, g, h, i, j = {}, k = a.dataTypes.slice(); if (k[1]) for (g in a.converters) j[g.toLowerCase()] = a.converters[g]; f = k.shift(); while (f) if (a.responseFields[f] && (c[a.responseFields[f]] = b), !i && d && a.dataFilter && (b = a.dataFilter(b, a.dataType)), i = f, f = k.shift()) if ("*" === f) f = i; else if ("*" !== i && i !== f) { if (g = j[i + " " + f] || j["* " + f], !g) for (e in j) if (h = e.split(" "), h[1] === f && (g = j[i + " " + h[0]] || j["* " + h[0]])) { g === !0 ? g = j[e] : j[e] !== !0 && (f = h[0], k.unshift(h[1])); break } if (g !== !0) if (g && a["throws"]) b = g(b); else try { b = g(b) } catch (l) { return { state: "parsererror", error: g ? l : "No conversion from " + i + " to " + f } } } return { state: "success", data: b } } m.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: zc, type: "GET", isLocal: Dc.test(yc[1]), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": Jc, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, converters: { "* text": String, "text html": !0, "text json": m.parseJSON, "text xml": m.parseXML }, flatOptions: { url: !0, context: !0 } }, ajaxSetup: function (a, b) { return b ? Nc(Nc(a, m.ajaxSettings), b) : Nc(m.ajaxSettings, a) }, ajaxPrefilter: Lc(Hc), ajaxTransport: Lc(Ic), ajax: function (a, b) { "object" == typeof a && (b = a, a = void 0), b = b || {}; var c, d, e, f, g, h, i, j, k = m.ajaxSetup({}, b), l = k.context || k, n = k.context && (l.nodeType || l.jquery) ? m(l) : m.event, o = m.Deferred(), p = m.Callbacks("once memory"), q = k.statusCode || {}, r = {}, s = {}, t = 0, u = "canceled", v = { readyState: 0, getResponseHeader: function (a) { var b; if (2 === t) { if (!j) { j = {}; while (b = Cc.exec(f)) j[b[1].toLowerCase()] = b[2] } b = j[a.toLowerCase()] } return null == b ? null : b }, getAllResponseHeaders: function () { return 2 === t ? f : null }, setRequestHeader: function (a, b) { var c = a.toLowerCase(); return t || (a = s[c] = s[c] || a, r[a] = b), this }, overrideMimeType: function (a) { return t || (k.mimeType = a), this }, statusCode: function (a) { var b; if (a) if (2 > t) for (b in a) q[b] = [q[b], a[b]]; else v.always(a[v.status]); return this }, abort: function (a) { var b = a || u; return i && i.abort(b), x(0, b), this } }; if (o.promise(v).complete = p.add, v.success = v.done, v.error = v.fail, k.url = ((a || k.url || zc) + "").replace(Ac, "").replace(Fc, yc[1] + "//"), k.type = b.method || b.type || k.method || k.type, k.dataTypes = m.trim(k.dataType || "*").toLowerCase().match(E) || [""], null == k.crossDomain && (c = Gc.exec(k.url.toLowerCase()), k.crossDomain = !(!c || c[1] === yc[1] && c[2] === yc[2] && (c[3] || ("http:" === c[1] ? "80" : "443")) === (yc[3] || ("http:" === yc[1] ? "80" : "443")))), k.data && k.processData && "string" != typeof k.data && (k.data = m.param(k.data, k.traditional)), Mc(Hc, k, b, v), 2 === t) return v; h = m.event && k.global, h && 0 === m.active++ && m.event.trigger("ajaxStart"), k.type = k.type.toUpperCase(), k.hasContent = !Ec.test(k.type), e = k.url, k.hasContent || (k.data && (e = k.url += (wc.test(e) ? "&" : "?") + k.data, delete k.data), k.cache === !1 && (k.url = Bc.test(e) ? e.replace(Bc, "$1_=" + vc++) : e + (wc.test(e) ? "&" : "?") + "_=" + vc++)), k.ifModified && (m.lastModified[e] && v.setRequestHeader("If-Modified-Since", m.lastModified[e]), m.etag[e] && v.setRequestHeader("If-None-Match", m.etag[e])), (k.data && k.hasContent && k.contentType !== !1 || b.contentType) && v.setRequestHeader("Content-Type", k.contentType), v.setRequestHeader("Accept", k.dataTypes[0] && k.accepts[k.dataTypes[0]] ? k.accepts[k.dataTypes[0]] + ("*" !== k.dataTypes[0] ? ", " + Jc + "; q=0.01" : "") : k.accepts["*"]); for (d in k.headers) v.setRequestHeader(d, k.headers[d]); if (k.beforeSend && (k.beforeSend.call(l, v, k) === !1 || 2 === t)) return v.abort(); u = "abort"; for (d in { success: 1, error: 1, complete: 1 }) v[d](k[d]); if (i = Mc(Ic, k, b, v)) { v.readyState = 1, h && n.trigger("ajaxSend", [v, k]), k.async && k.timeout > 0 && (g = setTimeout(function () { v.abort("timeout") }, k.timeout)); try { t = 1, i.send(r, x) } catch (w) { if (!(2 > t)) throw w; x(-1, w) } } else x(-1, "No Transport"); function x(a, b, c, d) { var j, r, s, u, w, x = b; 2 !== t && (t = 2, g && clearTimeout(g), i = void 0, f = d || "", v.readyState = a > 0 ? 4 : 0, j = a >= 200 && 300 > a || 304 === a, c && (u = Oc(k, v, c)), u = Pc(k, u, v, j), j ? (k.ifModified && (w = v.getResponseHeader("Last-Modified"), w && (m.lastModified[e] = w), w = v.getResponseHeader("etag"), w && (m.etag[e] = w)), 204 === a || "HEAD" === k.type ? x = "nocontent" : 304 === a ? x = "notmodified" : (x = u.state, r = u.data, s = u.error, j = !s)) : (s = x, (a || !x) && (x = "error", 0 > a && (a = 0))), v.status = a, v.statusText = (b || x) + "", j ? o.resolveWith(l, [r, x, v]) : o.rejectWith(l, [v, x, s]), v.statusCode(q), q = void 0, h && n.trigger(j ? "ajaxSuccess" : "ajaxError", [v, k, j ? r : s]), p.fireWith(l, [v, x]), h && (n.trigger("ajaxComplete", [v, k]), --m.active || m.event.trigger("ajaxStop"))) } return v }, getJSON: function (a, b, c) { return m.get(a, b, c, "json") }, getScript: function (a, b) { return m.get(a, void 0, b, "script") } }), m.each(["get", "post"], function (a, b) { m[b] = function (a, c, d, e) { return m.isFunction(c) && (e = e || d, d = c, c = void 0), m.ajax({ url: a, type: b, dataType: e, data: c, success: d }) } }), m._evalUrl = function (a) { return m.ajax({ url: a, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0 }) }, m.fn.extend({ wrapAll: function (a) { if (m.isFunction(a)) return this.each(function (b) { m(this).wrapAll(a.call(this, b)) }); if (this[0]) { var b = m(a, this[0].ownerDocument).eq(0).clone(!0); this[0].parentNode && b.insertBefore(this[0]), b.map(function () { var a = this; while (a.firstChild && 1 === a.firstChild.nodeType) a = a.firstChild; return a }).append(this) } return this }, wrapInner: function (a) { return this.each(m.isFunction(a) ? function (b) { m(this).wrapInner(a.call(this, b)) } : function () { var b = m(this), c = b.contents(); c.length ? c.wrapAll(a) : b.append(a) }) }, wrap: function (a) { var b = m.isFunction(a); return this.each(function (c) { m(this).wrapAll(b ? a.call(this, c) : a) }) }, unwrap: function () { return this.parent().each(function () { m.nodeName(this, "body") || m(this).replaceWith(this.childNodes) }).end() } }), m.expr.filters.hidden = function (a) { return a.offsetWidth <= 0 && a.offsetHeight <= 0 || !k.reliableHiddenOffsets() && "none" === (a.style && a.style.display || m.css(a, "display")) }, m.expr.filters.visible = function (a) { return !m.expr.filters.hidden(a) }; var Qc = /%20/g, Rc = /\[\]$/, Sc = /\r?\n/g, Tc = /^(?:submit|button|image|reset|file)$/i, Uc = /^(?:input|select|textarea|keygen)/i; function Vc(a, b, c, d) { var e; if (m.isArray(b)) m.each(b, function (b, e) { c || Rc.test(a) ? d(a, e) : Vc(a + "[" + ("object" == typeof e ? b : "") + "]", e, c, d) }); else if (c || "object" !== m.type(b)) d(a, b); else for (e in b) Vc(a + "[" + e + "]", b[e], c, d) } m.param = function (a, b) { var c, d = [], e = function (a, b) { b = m.isFunction(b) ? b() : null == b ? "" : b, d[d.length] = encodeURIComponent(a) + "=" + encodeURIComponent(b) }; if (void 0 === b && (b = m.ajaxSettings && m.ajaxSettings.traditional), m.isArray(a) || a.jquery && !m.isPlainObject(a)) m.each(a, function () { e(this.name, this.value) }); else for (c in a) Vc(c, a[c], b, e); return d.join("&").replace(Qc, "+") }, m.fn.extend({ serialize: function () { return m.param(this.serializeArray()) }, serializeArray: function () { return this.map(function () { var a = m.prop(this, "elements"); return a ? m.makeArray(a) : this }).filter(function () { var a = this.type; return this.name && !m(this).is(":disabled") && Uc.test(this.nodeName) && !Tc.test(a) && (this.checked || !W.test(a)) }).map(function (a, b) { var c = m(this).val(); return null == c ? null : m.isArray(c) ? m.map(c, function (a) { return { name: b.name, value: a.replace(Sc, "\r\n") } }) : { name: b.name, value: c.replace(Sc, "\r\n") } }).get() } }), m.ajaxSettings.xhr = void 0 !== a.ActiveXObject ? function () { return !this.isLocal && /^(get|post|head|put|delete|options)$/i.test(this.type) && Zc() || $c() } : Zc; var Wc = 0, Xc = {}, Yc = m.ajaxSettings.xhr(); a.attachEvent && a.attachEvent("onunload", function () { for (var a in Xc) Xc[a](void 0, !0) }), k.cors = !!Yc && "withCredentials" in Yc, Yc = k.ajax = !!Yc, Yc && m.ajaxTransport(function (a) { if (!a.crossDomain || k.cors) { var b; return { send: function (c, d) { var e, f = a.xhr(), g = ++Wc; if (f.open(a.type, a.url, a.async, a.username, a.password), a.xhrFields) for (e in a.xhrFields) f[e] = a.xhrFields[e]; a.mimeType && f.overrideMimeType && f.overrideMimeType(a.mimeType), a.crossDomain || c["X-Requested-With"] || (c["X-Requested-With"] = "XMLHttpRequest"); for (e in c) void 0 !== c[e] && f.setRequestHeader(e, c[e] + ""); f.send(a.hasContent && a.data || null), b = function (c, e) { var h, i, j; if (b && (e || 4 === f.readyState)) if (delete Xc[g], b = void 0, f.onreadystatechange = m.noop, e) 4 !== f.readyState && f.abort(); else { j = {}, h = f.status, "string" == typeof f.responseText && (j.text = f.responseText); try { i = f.statusText } catch (k) { i = "" } h || !a.isLocal || a.crossDomain ? 1223 === h && (h = 204) : h = j.text ? 200 : 404 } j && d(h, i, j, f.getAllResponseHeaders()) }, a.async ? 4 === f.readyState ? setTimeout(b) : f.onreadystatechange = Xc[g] = b : b() }, abort: function () { b && b(void 0, !0) } } } }); function Zc() { try { return new a.XMLHttpRequest } catch (b) { } } function $c() { try { return new a.ActiveXObject("Microsoft.XMLHTTP") } catch (b) { } } m.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function (a) { return m.globalEval(a), a } } }), m.ajaxPrefilter("script", function (a) { void 0 === a.cache && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1) }), m.ajaxTransport("script", function (a) { if (a.crossDomain) { var b, c = y.head || m("head")[0] || y.documentElement; return { send: function (d, e) { b = y.createElement("script"), b.async = !0, a.scriptCharset && (b.charset = a.scriptCharset), b.src = a.url, b.onload = b.onreadystatechange = function (a, c) { (c || !b.readyState || /loaded|complete/.test(b.readyState)) && (b.onload = b.onreadystatechange = null, b.parentNode && b.parentNode.removeChild(b), b = null, c || e(200, "success")) }, c.insertBefore(b, c.firstChild) }, abort: function () { b && b.onload(void 0, !0) } } } }); var _c = [], ad = /(=)\?(?=&|$)|\?\?/; m.ajaxSetup({ jsonp: "callback", jsonpCallback: function () { var a = _c.pop() || m.expando + "_" + vc++; return this[a] = !0, a } }), m.ajaxPrefilter("json jsonp", function (b, c, d) { var e, f, g, h = b.jsonp !== !1 && (ad.test(b.url) ? "url" : "string" == typeof b.data && !(b.contentType || "").indexOf("application/x-www-form-urlencoded") && ad.test(b.data) && "data"); return h || "jsonp" === b.dataTypes[0] ? (e = b.jsonpCallback = m.isFunction(b.jsonpCallback) ? b.jsonpCallback() : b.jsonpCallback, h ? b[h] = b[h].replace(ad, "$1" + e) : b.jsonp !== !1 && (b.url += (wc.test(b.url) ? "&" : "?") + b.jsonp + "=" + e), b.converters["script json"] = function () { return g || m.error(e + " was not called"), g[0] }, b.dataTypes[0] = "json", f = a[e], a[e] = function () { g = arguments }, d.always(function () { a[e] = f, b[e] && (b.jsonpCallback = c.jsonpCallback, _c.push(e)), g && m.isFunction(f) && f(g[0]), g = f = void 0 }), "script") : void 0 }), m.parseHTML = function (a, b, c) { if (!a || "string" != typeof a) return null; "boolean" == typeof b && (c = b, b = !1), b = b || y; var d = u.exec(a), e = !c && []; return d ? [b.createElement(d[1])] : (d = m.buildFragment([a], b, e), e && e.length && m(e).remove(), m.merge([], d.childNodes)) }; var bd = m.fn.load; m.fn.load = function (a, b, c) { if ("string" != typeof a && bd) return bd.apply(this, arguments); var d, e, f, g = this, h = a.indexOf(" "); return h >= 0 && (d = m.trim(a.slice(h, a.length)), a = a.slice(0, h)), m.isFunction(b) ? (c = b, b = void 0) : b && "object" == typeof b && (f = "POST"), g.length > 0 && m.ajax({ url: a, type: f, dataType: "html", data: b }).done(function (a) { e = arguments, g.html(d ? m("<div>").append(m.parseHTML(a)).find(d) : a) }).complete(c && function (a, b) { g.each(c, e || [a.responseText, b, a]) }), this }, m.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (a, b) { m.fn[b] = function (a) { return this.on(b, a) } }), m.expr.filters.animated = function (a) { return m.grep(m.timers, function (b) { return a === b.elem }).length }; var cd = a.document.documentElement; function dd(a) { return m.isWindow(a) ? a : 9 === a.nodeType ? a.defaultView || a.parentWindow : !1 } m.offset = { setOffset: function (a, b, c) { var d, e, f, g, h, i, j, k = m.css(a, "position"), l = m(a), n = {}; "static" === k && (a.style.position = "relative"), h = l.offset(), f = m.css(a, "top"), i = m.css(a, "left"), j = ("absolute" === k || "fixed" === k) && m.inArray("auto", [f, i]) > -1, j ? (d = l.position(), g = d.top, e = d.left) : (g = parseFloat(f) || 0, e = parseFloat(i) || 0), m.isFunction(b) && (b = b.call(a, c, h)), null != b.top && (n.top = b.top - h.top + g), null != b.left && (n.left = b.left - h.left + e), "using" in b ? b.using.call(a, n) : l.css(n) } }, m.fn.extend({ offset: function (a) { if (arguments.length) return void 0 === a ? this : this.each(function (b) { m.offset.setOffset(this, a, b) }); var b, c, d = { top: 0, left: 0 }, e = this[0], f = e && e.ownerDocument; if (f) return b = f.documentElement, m.contains(b, e) ? (typeof e.getBoundingClientRect !== K && (d = e.getBoundingClientRect()), c = dd(f), { top: d.top + (c.pageYOffset || b.scrollTop) - (b.clientTop || 0), left: d.left + (c.pageXOffset || b.scrollLeft) - (b.clientLeft || 0) }) : d }, position: function () { if (this[0]) { var a, b, c = { top: 0, left: 0 }, d = this[0]; return "fixed" === m.css(d, "position") ? b = d.getBoundingClientRect() : (a = this.offsetParent(), b = this.offset(), m.nodeName(a[0], "html") || (c = a.offset()), c.top += m.css(a[0], "borderTopWidth", !0), c.left += m.css(a[0], "borderLeftWidth", !0)), { top: b.top - c.top - m.css(d, "marginTop", !0), left: b.left - c.left - m.css(d, "marginLeft", !0) } } }, offsetParent: function () { return this.map(function () { var a = this.offsetParent || cd; while (a && !m.nodeName(a, "html") && "static" === m.css(a, "position")) a = a.offsetParent; return a || cd }) } }), m.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (a, b) { var c = /Y/.test(b); m.fn[a] = function (d) { return V(this, function (a, d, e) { var f = dd(a); return void 0 === e ? f ? b in f ? f[b] : f.document.documentElement[d] : a[d] : void (f ? f.scrollTo(c ? m(f).scrollLeft() : e, c ? e : m(f).scrollTop()) : a[d] = e) }, a, d, arguments.length, null) } }), m.each(["top", "left"], function (a, b) { m.cssHooks[b] = Lb(k.pixelPosition, function (a, c) { return c ? (c = Jb(a, b), Hb.test(c) ? m(a).position()[b] + "px" : c) : void 0 }) }), m.each({ Height: "height", Width: "width" }, function (a, b) { m.each({ padding: "inner" + a, content: b, "": "outer" + a }, function (c, d) { m.fn[d] = function (d, e) { var f = arguments.length && (c || "boolean" != typeof d), g = c || (d === !0 || e === !0 ? "margin" : "border"); return V(this, function (b, c, d) { var e; return m.isWindow(b) ? b.document.documentElement["client" + a] : 9 === b.nodeType ? (e = b.documentElement, Math.max(b.body["scroll" + a], e["scroll" + a], b.body["offset" + a], e["offset" + a], e["client" + a])) : void 0 === d ? m.css(b, c, g) : m.style(b, c, d, g) }, b, f ? d : void 0, f, null) } }) }), m.fn.size = function () { return this.length }, m.fn.andSelf = m.fn.addBack, "function" == typeof define && define.amd && define("jquery", [], function () { return m }); var ed = a.jQuery, fd = a.$; return m.noConflict = function (b) { return a.$ === m && (a.$ = fd), b && a.jQuery === m && (a.jQuery = ed), m }, typeof b === K && (a.jQuery = a.$ = m), m
});

/*! jQuery Migrate v1.2.1 | (c) 2005, 2013 jQuery Foundation, Inc. and other contributors | jquery.org/license */
jQuery.migrateMute === void 0 && (jQuery.migrateMute = !0), function (e, t, n) { function r(n) { var r = t.console; i[n] || (i[n] = !0, e.migrateWarnings.push(n), r && r.warn && !e.migrateMute && (r.warn("JQMIGRATE: " + n), e.migrateTrace && r.trace && r.trace())) } function a(t, a, i, o) { if (Object.defineProperty) try { return Object.defineProperty(t, a, { configurable: !0, enumerable: !0, get: function () { return r(o), i }, set: function (e) { r(o), i = e } }), n } catch (s) { } e._definePropertyBroken = !0, t[a] = i } var i = {}; e.migrateWarnings = [], !e.migrateMute && t.console && t.console.log && t.console.log("JQMIGRATE: Logging is active"), e.migrateTrace === n && (e.migrateTrace = !0), e.migrateReset = function () { i = {}, e.migrateWarnings.length = 0 }, "BackCompat" === document.compatMode && r("jQuery is not compatible with Quirks Mode"); var o = e("<input/>", { size: 1 }).attr("size") && e.attrFn, s = e.attr, u = e.attrHooks.value && e.attrHooks.value.get || function () { return null }, c = e.attrHooks.value && e.attrHooks.value.set || function () { return n }, l = /^(?:input|button)$/i, d = /^[238]$/, p = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, f = /^(?:checked|selected)$/i; a(e, "attrFn", o || {}, "jQuery.attrFn is deprecated"), e.attr = function (t, a, i, u) { var c = a.toLowerCase(), g = t && t.nodeType; return u && (4 > s.length && r("jQuery.fn.attr( props, pass ) is deprecated"), t && !d.test(g) && (o ? a in o : e.isFunction(e.fn[a]))) ? e(t)[a](i) : ("type" === a && i !== n && l.test(t.nodeName) && t.parentNode && r("Can't change the 'type' of an input or button in IE 6/7/8"), !e.attrHooks[c] && p.test(c) && (e.attrHooks[c] = { get: function (t, r) { var a, i = e.prop(t, r); return i === !0 || "boolean" != typeof i && (a = t.getAttributeNode(r)) && a.nodeValue !== !1 ? r.toLowerCase() : n }, set: function (t, n, r) { var a; return n === !1 ? e.removeAttr(t, r) : (a = e.propFix[r] || r, a in t && (t[a] = !0), t.setAttribute(r, r.toLowerCase())), r } }, f.test(c) && r("jQuery.fn.attr('" + c + "') may use property instead of attribute")), s.call(e, t, a, i)) }, e.attrHooks.value = { get: function (e, t) { var n = (e.nodeName || "").toLowerCase(); return "button" === n ? u.apply(this, arguments) : ("input" !== n && "option" !== n && r("jQuery.fn.attr('value') no longer gets properties"), t in e ? e.value : null) }, set: function (e, t) { var a = (e.nodeName || "").toLowerCase(); return "button" === a ? c.apply(this, arguments) : ("input" !== a && "option" !== a && r("jQuery.fn.attr('value', val) no longer sets properties"), e.value = t, n) } }; var g, h, v = e.fn.init, m = e.parseJSON, y = /^([^<]*)(<[\w\W]+>)([^>]*)$/; e.fn.init = function (t, n, a) { var i; return t && "string" == typeof t && !e.isPlainObject(n) && (i = y.exec(e.trim(t))) && i[0] && ("<" !== t.charAt(0) && r("$(html) HTML strings must start with '<' character"), i[3] && r("$(html) HTML text after last tag is ignored"), "#" === i[0].charAt(0) && (r("HTML string cannot start with a '#' character"), e.error("JQMIGRATE: Invalid selector string (XSS)")), n && n.context && (n = n.context), e.parseHTML) ? v.call(this, e.parseHTML(i[2], n, !0), n, a) : v.apply(this, arguments) }, e.fn.init.prototype = e.fn, e.parseJSON = function (e) { return e || null === e ? m.apply(this, arguments) : (r("jQuery.parseJSON requires a valid JSON string"), null) }, e.uaMatch = function (e) { e = e.toLowerCase(); var t = /(chrome)[ \/]([\w.]+)/.exec(e) || /(webkit)[ \/]([\w.]+)/.exec(e) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e) || /(msie) ([\w.]+)/.exec(e) || 0 > e.indexOf("compatible") && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e) || []; return { browser: t[1] || "", version: t[2] || "0" } }, e.browser || (g = e.uaMatch(navigator.userAgent), h = {}, g.browser && (h[g.browser] = !0, h.version = g.version), h.chrome ? h.webkit = !0 : h.webkit && (h.safari = !0), e.browser = h), a(e, "browser", e.browser, "jQuery.browser is deprecated"), e.sub = function () { function t(e, n) { return new t.fn.init(e, n) } e.extend(!0, t, this), t.superclass = this, t.fn = t.prototype = this(), t.fn.constructor = t, t.sub = this.sub, t.fn.init = function (r, a) { return a && a instanceof e && !(a instanceof t) && (a = t(a)), e.fn.init.call(this, r, a, n) }, t.fn.init.prototype = t.fn; var n = t(document); return r("jQuery.sub() is deprecated"), t }, e.ajaxSetup({ converters: { "text json": e.parseJSON } }); var b = e.fn.data; e.fn.data = function (t) { var a, i, o = this[0]; return !o || "events" !== t || 1 !== arguments.length || (a = e.data(o, t), i = e._data(o, t), a !== n && a !== i || i === n) ? b.apply(this, arguments) : (r("Use of jQuery.fn.data('events') is deprecated"), i) }; var j = /\/(java|ecma)script/i, w = e.fn.andSelf || e.fn.addBack; e.fn.andSelf = function () { return r("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"), w.apply(this, arguments) }, e.clean || (e.clean = function (t, a, i, o) { a = a || document, a = !a.nodeType && a[0] || a, a = a.ownerDocument || a, r("jQuery.clean() is deprecated"); var s, u, c, l, d = []; if (e.merge(d, e.buildFragment(t, a).childNodes), i) for (c = function (e) { return !e.type || j.test(e.type) ? o ? o.push(e.parentNode ? e.parentNode.removeChild(e) : e) : i.appendChild(e) : n }, s = 0; null != (u = d[s]) ; s++) e.nodeName(u, "script") && c(u) || (i.appendChild(u), u.getElementsByTagName !== n && (l = e.grep(e.merge([], u.getElementsByTagName("script")), c), d.splice.apply(d, [s + 1, 0].concat(l)), s += l.length)); return d }); var Q = e.event.add, x = e.event.remove, k = e.event.trigger, N = e.fn.toggle, T = e.fn.live, M = e.fn.die, S = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess", C = RegExp("\\b(?:" + S + ")\\b"), H = /(?:^|\s)hover(\.\S+|)\b/, A = function (t) { return "string" != typeof t || e.event.special.hover ? t : (H.test(t) && r("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"), t && t.replace(H, "mouseenter$1 mouseleave$1")) }; e.event.props && "attrChange" !== e.event.props[0] && e.event.props.unshift("attrChange", "attrName", "relatedNode", "srcElement"), e.event.dispatch && a(e.event, "handle", e.event.dispatch, "jQuery.event.handle is undocumented and deprecated"), e.event.add = function (e, t, n, a, i) { e !== document && C.test(t) && r("AJAX events should be attached to document: " + t), Q.call(this, e, A(t || ""), n, a, i) }, e.event.remove = function (e, t, n, r, a) { x.call(this, e, A(t) || "", n, r, a) }, e.fn.error = function () { var e = Array.prototype.slice.call(arguments, 0); return r("jQuery.fn.error() is deprecated"), e.splice(0, 0, "error"), arguments.length ? this.bind.apply(this, e) : (this.triggerHandler.apply(this, e), this) }, e.fn.toggle = function (t, n) { if (!e.isFunction(t) || !e.isFunction(n)) return N.apply(this, arguments); r("jQuery.fn.toggle(handler, handler...) is deprecated"); var a = arguments, i = t.guid || e.guid++, o = 0, s = function (n) { var r = (e._data(this, "lastToggle" + t.guid) || 0) % o; return e._data(this, "lastToggle" + t.guid, r + 1), n.preventDefault(), a[r].apply(this, arguments) || !1 }; for (s.guid = i; a.length > o;) a[o++].guid = i; return this.click(s) }, e.fn.live = function (t, n, a) { return r("jQuery.fn.live() is deprecated"), T ? T.apply(this, arguments) : (e(this.context).on(t, this.selector, n, a), this) }, e.fn.die = function (t, n) { return r("jQuery.fn.die() is deprecated"), M ? M.apply(this, arguments) : (e(this.context).off(t, this.selector || "**", n), this) }, e.event.trigger = function (e, t, n, a) { return n || C.test(e) || r("Global events are undocumented and deprecated"), k.call(this, e, t, n || document, a) }, e.each(S.split("|"), function (t, n) { e.event.special[n] = { setup: function () { var t = this; return t !== document && (e.event.add(document, n + "." + e.guid, function () { e.event.trigger(n, null, t, !0) }), e._data(this, n, e.guid++)), !1 }, teardown: function () { return this !== document && e.event.remove(document, n + "." + e._data(this, n)), !1 } } }) }(jQuery, window);
;

var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e) { cX = e.pageX; cY = e.pageY; }
function UpdateCursorPositionDocAll(e) { cX = event.clientX; cY = event.clientY; }
if (document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
    if (self.pageYOffset) {
        rX = self.pageXOffset;
        rY = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        rX = document.documentElement.scrollLeft;
        rY = document.documentElement.scrollTop;
    }
    else if (document.body) {
        rX = document.body.scrollLeft;
        rY = document.body.scrollTop;
    }
    if (document.all) {
        cX += rX;
        cY += rY;
    }
    d.style.left = (cX + 10) + "px";
    d.style.top = (cY + 10) + "px";
}
function HideContent(d) {
    if (d.length < 1) { return; }
    document.getElementById(d).style.display = "none";
}
function ShowContent(d, img, txt) {
    if (d.length < 1) { return; }

    var content = "";
    if (img) content += '<div class="thumb_img"><img src="' + img + '"></div>';
    if (txt) content += '<div class="thumb_txt">' + txt + '</div>';
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
    dd.innerHTML = content;
}

function ShowDisclaimer(displayElement) {
    if (typeof (document.getElementById(displayElement)) != "undefined") {
        document.getElementById(displayElement).style.display = "block";
    }
    else {
        return;
    }
}

function HideContent(displayElement) {
    if (typeof (document.getElementById(displayElement)) != "undefined") {
        document.getElementById(displayElement).style.display = "none";
    }
    else {
        return;
    }
}

function ReverseContentDisplay(d) {
    if (d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") { dd.style.display = "block"; }
    else { dd.style.display = "none"; }
}

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}

function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all)
        x = d.all[n];

    for (i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];

    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2) ; i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}


function MM_nbGroup(event, grpName) { //v3.0
    var i, img, nbArr, args = MM_nbGroup.arguments;
    if (event == "init" && args.length > 2) {
        if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
            img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
            if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
            nbArr[nbArr.length] = img;
            for (i = 4; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
                if (!img.MM_up) img.MM_up = img.src;
                img.src = img.MM_dn = args[i + 1];
                nbArr[nbArr.length] = img;
            }
        }
    } else if (event == "over") {
        document.MM_nbOver = nbArr = new Array();
        for (i = 1; i < args.length - 1; i += 3) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = (img.MM_dn && args[i + 2]) ? args[i + 2] : args[i + 1];
            nbArr[nbArr.length] = img;
        }
        //document.layers["layerCorpPopup"].zIndex = 0;
    } else if (event == "out") {
        for (i = 0; i < document.MM_nbOver.length; i++) {
            img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up;
        }
    } else if (event == "down") {
        if ((nbArr = document[grpName]) != null)
            for (i = 0; i < nbArr.length; i++) { img = nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
        document[grpName] = nbArr = new Array();
        for (i = 2; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = img.MM_dn = args[i + 1];
            nbArr[nbArr.length] = img;
        }
    }
}

function ClearAllOptions() {
    clearCookie();
    ClearValue();

    for (i = 0; i < document.forms[0].length; i++) {
        doc = document.forms[0].elements[i];
        switch (doc.type) {
            case "text":
                doc.value = "";
                break;
            case "checkbox":
                doc.checked = false;
                break;
            case "radio":
                doc.checked = false;
                break;
            case "select-one":
                doc.selectedIndex = 0;
                break;
            case "select-multiple":
                doc.selectedIndex = 0;
                break;
            default:
                break;
        }
    }
}

function BootstrapShowModalNotification(modalId, autoclose, timeoutSeconds) {

    $('#' + modalId).modal('show');

    if (autoclose && timeoutSeconds > 0) {
        setTimeout(function () { $('#' + modalId).modal('hide') }, timeoutSeconds * 1000);
    }

    return;
}


function ShowDialogModal(page, title, attributes) {
    //window.alert(navigator.userAgent);
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        //window.alert("MSIE");
        attributes = attributes.replace(/,/g, ';');
        attributes = attributes.replace(/=/g, ':');
        attributes = attributes.replace(/width/, 'dialogWidth');
        attributes = attributes.replace(/height/, 'dialogHeight');
        attributes = attributes.replace(/top/, 'dialogTop');
        attributes = attributes.replace(/left/, 'dialogLeft');
        attributes = attributes.replace(/scrollbars/, 'scroll');
        return window.showModalDialog(page, title, attributes);
    }
    else {
        //window.alert("Other");
        if (attributes != "") attributes = attributes + ",";
        return window.open(page, title, attributes + 'dependent=YES,dialog=YES,modal=YES'); //.opener.MyArgs;
    }
}

function Start(page) {
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        //window.alert("MSIE");
        return window.showModalDialog(page, "CurrencyConverter", "height=400,width=390,resizable=yes,scrollbars=yes");
    }
    else {
        //window.alert("Other");
        if (attributes != "") attributes = attributes + ",";
        return window.open(page, "CurrencyConverter", 'height=400,width=390,resizable=yes,scrollbars=yes,dependent=YES,dialog=YES,modal=YES').opener.MyArgs;
    }
}

function CurrencyWindow(page) {
    ShowDialogModal(page, "CurrencyConverter", "height=585px,width=425px,resizable=yes,scrollbars=yes");
}

function SendToAFriendWindow(page) {
    this.open(page, "sendtoafriend", 'width=390,height=610,top=' + ((screen.height / 2) - 210) + ',left=' + ((screen.width / 2) - 230) + ',scrollbars=auto,menubar=no,resizable=no');
}

function VirtualTourWindow(page) {
    InsertGoogleTagManagerEvent('Virtual Tour', 'Click', 'Listing List VirtualTour');
    OpenWin = this.open(page, "VirtualTour", "height=525,width=800,resizable=yes,scrollbars=yes");
}

function MultiMediaWindow(page) {
    //OpenWin = this.open(page, "Multimedia", 'height=800,width=965,top=100,left=200 resizable=yes,scrollbars=yes, location=no,status=no');
    var w = 1024, h = 768;
    if (document.all || document.layers) {
        w = screen.availWidth;
        h = screen.availHeight;
    }

    var popW = 990, popH = 930;

    var leftPos = (w - popW) / 2, topPos = (h - popH) / 2;
    OpenWin = this.open(page, "Multimedia", 'height=' + popH + ',width=' + popW + ',top=' + topPos + ',left=' + leftPos + ' resizable=yes,scrollbars=yes, location=no,status=no');
}

function GoogleMapWindow(page) {
    this.open(page, "findWithGoogleMap", 'width=620,height=535,top=' + ((screen.height / 2) - 210) + ',left=' + ((screen.width / 2) - 230) + ',scrollbars=no,resizable=no,titlebar=no,location=no,status=no');
}

//browser resize
function maxtable() {
    //alert("resizing window");

    var isNS = (document.layers) ? true : false;

    bodyW = (isNS) ? window.innerWidth : document.body.offsetWidth;

    if (bodyW < 1000)
    { MainTable.width = "100%" }
    else
    { MainTable.width = 1000 }
}

function hideshow(whichdiv) {
    //
    // hide them all 

    // hide divFindOffices
    document.getElementById('divFindOffices').style.display = "none";
    document.getElementById('divFindOffices').style.visibility = "hidden";
    // hide divFindProp
    document.getElementById('divFindProp').style.display = "none";
    document.getElementById('divFindProp').style.visibility = "hidden";
    // hide divFindAgents
    //	document.getElementById('divFindAgents').style.display = "none";
    //	document.getElementById('divFindAgents').style.visibility = "hidden";

    // now show selected tab

    document.getElementById(whichdiv).style.display = "block";
    document.getElementById(whichdiv).style.visibility = "visible";
    //
}

function hideshowEurope(whichdiv) {
    //
    // hide them all 

    // hide divFindOffices
    //	document.getElementById('divSellProperty').style.display = "none";
    //	document.getElementById('divSellProperty').style.visibility = "hidden";
    // hide divFindProp
    document.getElementById('divFindProp').style.display = "none";
    document.getElementById('divFindProp').style.visibility = "hidden";
    // hide divFindAgents
    document.getElementById('divFindAgents').style.display = "none";
    document.getElementById('divFindAgents').style.visibility = "hidden";

    // now show selected tab

    document.getElementById(whichdiv).style.display = "block";
    document.getElementById(whichdiv).style.visibility = "visible";
    //
}

function visibilityToggle(id) {
    var objectClicked = null;
    if (!/string/i.test(typeof (id))) {
        objectClicked = id[0]; //THIS IS HERE FOR LATER USE:
        //FIX THE DISTANCE BETWEEN THE ITEM CLICKED AND THE POPUP LIST DISPLAY
        id = id[1];
    }
    var el = document.getElementById(id);
    var elStyle = el.style;

    if (id == "countrypopup" || id == "countrypopup_Global") {
        var el2 = document.getElementById('myState');
    } else if (id == "currencypopup" || id == "currencypopup_global") {
        var el2 = document.getElementById('myStateCurrency');
    }

    //
    if (elStyle.display == "none") {
        elStyle.visibility = 'visible';
        elStyle.display = "block";
        if (document.URL.toLowerCase().indexOf('publiclistinglist.aspx') > -1) {
            var objectClickedOffset = $(objectClicked).parent().offset();
            if (objectClickedOffset) {
                $(el).offset({ left: objectClickedOffset.left, top: objectClickedOffset.top });
            }
        }
        if (id == "currencypopup_global") {
            document.getElementById("currencypopup_global").style.zIndex = 9999;
        }
        if (id == "countrypopup" || id == "currencypopup" || id == "currencypopup_global" || id == "countrypopup_Global") {
            el2.value = 1;
        }
    } else if (elStyle.display == "block") {
        elStyle.visibility = 'hidden';
        elStyle.display = "none";
        if (id == "countrypopup" || id == "currencypopup" || id == "currencypopup_global" || id == "countrypopup_Global") {
            el2.value = 0;
        }
    }
}

function ClosePopUp(id) {
    var objectClicked = null;
    if (!/string/i.test(typeof (id))) {
        objectClicked = id[0]; //THIS IS HERE FOR LATER USE:
        //FIX THE DISTANCE BETWEEN THE ITEM CLICKED AND THE POPUP LIST DISPLAY
        id = id[1];
    }
    var el = document.getElementById(id).style;
    el.visibility = 'hidden';
    el.display = "none";
    if (document.getElementById('ShowCountrypopup_Global'))
        document.getElementById('ShowCountrypopup_Global').value = 0;
}

function checkState(e) {
    //e is undefined in IE 8 only so this fix basically just allows users to use the site with IE 8. low priority fix cr94751
    if (e != undefined) {
        // hide country popup if clicked outside of it
        var countryPopup = $("#country-selector-popup");
        var countryPopupButton = $("#btnSelectCountry");
        if (!countryPopup.is(e.target) && countryPopup.has(e.target).length === 0
            && !countryPopupButton.is(e.target) && countryPopupButton.has(e.target).length === 0) {
            countryPopup.hide();
        }
    }

    var chkCss;
    for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href != null && document.styleSheets[i].href.indexOf('common_heb.css') != -1) {
            chkCss = "true";
            break;
        }
        else {
            chkCss = "false";
        }
    }
    var IE = document.all ? true : false;
    if (!IE) document.captureEvents(Event.MOUSEMOVE)

    var tempX = 0;
    var tempY = 0;
    if (IE) { // grab the x-y pos.s if browser is IE
        if (typeof (event) == "undefined" || event == null) {
            return;
        }
        tempX = event.clientX + document.body.scrollLeft;
        tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX;
        tempY = e.pageY;
    }
    if (tempX < 0) { tempX = 0; }
    if (tempY < 0) { tempY = 0; }
    var div;
    var target = (e && e.target) || (event && event.srcElement);
    if (document.getElementById('countrypopup') != null) {
        div = document.getElementById('countrypopup');
        div.style.left = tempX + 50 + "px";
        div.style.top = tempY - 200 + "px";



        var el = document.getElementById('myState').value;


        if (el == 1) {

            var obj = document.getElementById('shoCountry');
            var obj2 = document.getElementById('shoFlag');
            var obj3 = document.getElementById('shoArrow');
            if (target != obj && target.parentNode != obj2 && target.parentNode != obj3) {

                var el2 = document.getElementById('countrypopup').style;
                el2.visibility = "hidden";
                el2.display = "none";
                el = 0;
                showHideSelect('visible');
            }
        }
    }
    if (document.getElementById('countrypopup_Global') != null) {
        var obj4 = document.getElementById('ctl01_ucCountrySelector_btnSelectCountry');
        div = document.getElementById('countrypopup_Global');
        if (window.location.href.toLowerCase().match('publiclistinglist.aspx')) {
            div.style.top = 300 + "px";
        }

        var target = (e && e.target) || (event && event.srcElement);
        var el = document.getElementById('myState').value;
        if (el == 1) {
            if (document.getElementById('ShowCountrypopup_Global')) {
                if (document.getElementById('ShowCountrypopup_Global').value == 0) {

                    var el2 = document.getElementById('countrypopup_Global').style;
                    el2.visibility = "hidden";
                    el2.display = "none";
                    el = 0;
                    showHideSelect('visible');

                }
                document.getElementById('ShowCountrypopup_Global').value = 0;
            }
            else {
                var obj = document.getElementById('shoCountry');
                var obj2 = document.getElementById('shoFlag');
                var obj3 = document.getElementById('shoArrow');
                var obj5 = document.getElementById('shoGlobe');
                if (target != obj && target.parentNode != obj2 && target.parentNode != obj3 && target != obj4 && target != obj5) {

                    var el2 = document.getElementById('countrypopup_Global').style;
                    el2.visibility = "hidden";
                    el2.display = "none";
                    el = 0;
                    showHideSelect('visible');
                }
            }
        }



    }
    if (document.getElementById('myStateCurrency') != null && document.getElementById('currencypopup') != null) {
        var div = document.getElementById('currencypopup');
        div.style.left = tempX + 30 + "px";
        div.style.top = tempY - 100 + "px";

        el2 = document.getElementById('myStateCurrency').value;

        if (el2 == 1) {
            var obj = document.getElementById('shoCurrency');
            var obj2 = document.getElementById('shoCoins');
            var obj3 = document.getElementById('shoCurArrow');


            if (target.parentNode != obj && target.parentNode != obj2 && target.parentNode != obj3) {

                var el2 = document.getElementById('currencypopup').style;
                el2.visibility = "hidden";
                el2.display = "none";
                el = 0;
                showHideSelect('visible');
            }
        }
    }
    if (document.getElementById('myStateCurrency') != null && document.getElementById('currencypopup_global') != null) {
        var div = document.getElementById('currencypopup_global');
        //        div.style.left = tempX + 30 + "px";
        //        div.style.top = tempY - 100 + "px";

        el2 = document.getElementById('myStateCurrency').value;
        if (el2 == 1) {
            var obj = document.getElementById('shoCurrency');
            var obj2 = document.getElementById('shoCoins');
            var obj3 = document.getElementById('shoCurArrow');
            var obj4 = document.getElementById('divCurrencySymbol');

            if (target.parentNode != obj && target.parentNode != obj2 && target.parentNode != obj3 && target.parentNode != obj4) {
                var el2 = document.getElementById('currencypopup_global').style;
                el2.visibility = "hidden";
                el2.display = "none";
                el = 0;
                showHideSelect('visible');
            }
        }
    }
}



function showHideSelect(action) {
    // if (navigator.appName.indexOf("MSIE")) {
    for (var S = 0; S < document.forms.length; S++) {
        for (var R = 0; R < document.forms[S].length; R++) {
            if (document.forms[S].elements[R].options) {
                document.forms[S].elements[R].style.visibility = action;
                if (action == 'hidden')
                    document.forms[S].elements[R].style.display = 'none';
                else
                    document.forms[S].elements[R].style.display = 'inline';
            }
        }
    }
    // }
}

// Applies  styles to input controls based on input "type"
function appendInputTypeClasses() {
    if (!document.getElementsByTagName) {
        return;
    }
    var inputs = document.getElementsByTagName('input');
    var inputLen = inputs.length;
    for (i = 0; i < inputLen; i++) {
        if (inputs[i].getAttribute('type')) {
            inputs[i].className += ' ' + inputs[i].getAttribute('type');
        }
    }
}
// Change which searchtype radio button is selected  (property or agent/office)
function changeSearchType(searchType) {
    if (searchType == 'SearchType1') {
        el = document.getElementById('SearchType1');
        el.checked = true;
        el = document.getElementById('SearchType2');
        el.checked = false;
    }
    if (searchType == 'SearchType2') {
        el = document.getElementById('SearchType2');
        el.checked = true;
        el = document.getElementById('SearchType1');
        el.checked = false;
    }
}
function sendLostPassword() {
    //path to js file:  \\gttstweb02\webs$\testgeneric.slingshot.com\Sites\RemaxEuropeCommon\Includes
    var emailAddress = document.getElementById(emailTextBoxClientId.value).value;
    //todo:  if emailAddress is blank, do nothing, else pop up the dialog
    if ((emailAddress != null) && (emailAddress.length > 1)) {
        ShowDialogModal("/MyRemaxLostPassword.aspx?email=" + emailAddress, "Email Lost Password", "height=200px,width=350px");
    }
}

function OpenOfficeSelect(divOfficeNameID, emailID) {
    var ParmA;
    var ParmB;
    var MyArgs = new Array(ParmA, ParmB);
    var WinSettings = "center:yes;resizable:no;dialogHeight:300px"

    v_emailID = emailID;
    v_divOfficeNameID = divOfficeNameID;



    //ALTER BELOW LINE - supply correct URL for Child Form
    //var MyArgs = window.showModalDialog("http://localhost/ModalWin/ChildWebForm.aspx", MyArgs, WinSettings);
    //MyArgs = window.showModalDialog('.../PubScripts/SelectOffice.asp',MyArgs,'width=460,height=420,top='+((screen.height/2)-210)+',left='+((screen.width/2)-230) + ',scrollbars=yes,dependent=yes,menubar=no,resizable=no');
    var url = '/Common/SelectOffice.aspx?';
    url += "email=" + emailID;
    url += "&officename=" + divOfficeNameID;
    MyArgs = ShowDialogModal(url, MyArgs, 'width=460px,height=420px,top=' + ((screen.height / 2) - 210) + ',left=' + ((screen.width / 2) - 230) + ',scrollbars=yes,dependent=yes,menubar=no,resizable=no');
    if (MyArgs == null) {
        window.alert("No Office Selected");
    }
    else if (MyArgs[0] != undefined && (MyArgs[0].toString() == null || MyArgs[0].toString() == "")) {
        window.alert("This office does not have email, please select another");
    }
    else {
        if (navigator.userAgent.indexOf("MSIE") != -1) {
            document.getElementById(emailID).value = MyArgs[0].toString();
            document.getElementById(divOfficeNameID).innerHTML = MyArgs[1].toString();
        }
    }
}



var v_emailID;
var v_divOfficeNameID;

function GetFF(MyArgs) {
    document.getElementById(v_emailID).value = MyArgs[0].toString();
    document.getElementById(v_divOfficeNameID).innerHTML = MyArgs[1].toString();
}


function OpenOfficeSelectSell(divOfficeNameID, emailID, regionID) {
    var ParmA;
    var ParmB;
    var MyArgs = new Array(ParmA, ParmB);
    var WinSettings = "center:yes;resizable:no;dialogHeight:300px"
    var Url;
    Url = '/Common/SelectOfficeFrame.aspx?RegionID=' + regionID;
    //ALTER BELOW LINE - supply correct URL for Child Form
    //var MyArgs = window.showModalDialog("http://localhost/ModalWin/ChildWebForm.aspx", MyArgs, WinSettings);
    //MyArgs = window.showModalDialog('.../PubScripts/SelectOffice.asp',MyArgs,'width=460,height=420,top='+((screen.height/2)-210)+',left='+((screen.width/2)-230) + ',scrollbars=yes,dependent=yes,menubar=no,resizable=no');
    MyArgs = window.showModalDialog(Url, MyArgs, 'width=460,height=420,top=' + ((screen.height / 2) - 210) + ',left=' + ((screen.width / 2) - 230) + ',scrollbars=no,dependent=yes,menubar=no,resizable=no');
    if (MyArgs == null) {
        window.alert("No Office Selected");
    }
    else if (MyArgs[0].toString() == null || MyArgs[0].toString() == "") {
        window.alert("This office does not have email, please select another");
    }
    else {
        document.getElementById(emailID).value = MyArgs[0].toString();
        document.getElementById(divOfficeNameID).innerHTML = MyArgs[1].toString();
    }
}

function ShowHideDiv(div, show) {
    if ('True' != 'True') {
        if (show && ('False' == 'True')) {
            document.getElementById(div).style.display = "inline";
            document.getElementById(div).style.visibility = "visible";
        }
        else {
            document.getElementById(div).style.display = "none";
            document.getElementById(div).style.visibility = "hidden";
        }
    }
}

// This should be deprecated as it is less customizable and more vague.. Use OpenOfficeSelect() above
function OpenChild() {
    var ParmA;
    var ParmB;
    var MyArgs = new Array(ParmA, ParmB);
    var WinSettings = "center:yes;resizable:no;dialogHeight:300px";
    MyArgs = ShowDialogModal('/Common/SelectOffice.aspx', MyArgs, 'width=460,height=420,top=' + ((screen.height / 2) - 210) + ',left=' + ((screen.width / 2) - 230) + ',scrollbars=yes,dependent=yes,menubar=no,resizable=no');
    if (MyArgs == null) {
        window.alert("No Office Selected");
    }
    else {
        if (navigator.userAgent.indexOf("MSIE") != -1) {
            document.getElementById('HSENDTO').value = MyArgs[0].toString();
            document.getElementById('officename').innerHTML = MyArgs[1].toString();
        }
        else {
            document.getElementById('HSENDTO').value = document.getElementById('email').value;
            document.getElementById('officename').innerHTML = document.getElementById('officename').innerHTML;
        }
    }
}



function LangaugeChanged(LangVal, PreviousLangVal) {
    var origin = location.origin || location.protocol + "//" + location.hostname;
    var curURL = origin + location.pathname;
    var curHash = location.hash;
    var Params = location.search.replace(/^\?/, "");

    if (Params.length > 0)
        Params = Params.split('&');
    var KeyVal = null;
    var curQueryString = "";

    var LangKeyNotFound = true;
    var PreviousLangKeyNotFound = true;
    for (var x = 0; x < Params.length; x++) {
        var arr = [];             //new storage
        str = Params[x].split('=');     //split by =
        arr.push(str.shift());    //add the number
        arr.push(str.join('='));

        KeyVal = arr;

        if (/^lang$/i.test(KeyVal[0])) {
            KeyVal[1] = LangVal;
            LangKeyNotFound = false;
        }

        if (/^PreviousLang$/i.test(KeyVal[0])) {
            PreviousLangKeyNotFound = false;
            if (PreviousLangVal) {
                KeyVal[1] = PreviousLangVal;
            }
        }
        curQueryString += "&" + KeyVal[0] + "=" + KeyVal[1]
    }

    if (LangKeyNotFound)
        curQueryString += "&Lang=" + LangVal
    if (PreviousLangKeyNotFound && PreviousLangVal) {
        curQueryString += "&PreviousLang=" + PreviousLangVal
    }
    if (/\/$/.test(curURL)) {
        curURL += "Default.aspx?"
    }
    else if (curURL.Length - 4 == location.hostname.length) {
        curURL += "/Default.aspx?"
    }
    if (!/\?$/.test(curURL))
        curURL += '?'
    // Excluded Reg-Ex filter so current URL does not change, but just has the Language params added or updated to the end.
    location.replace(curURL + curQueryString.replace(/^\&/, "") + curHash);
}

function changeMap() {
    curURL = location.href;
    curSearch = curURL.split('SearchType=');
    curSearch = curSearch[1];
    curSearch = curSearch.split("", 1);
    curSearch = curSearch[0];
    el = document.getElementById("mapImage");
    if (curSearch == 'O') {
        el.src = '/sites/REMAXSlovakia/mapimages/bratislava.gif';
    } else {
        el.src = '/sites/REMAXSlovakia/mapimages/bratislava2.gif';
    }
}

/* Popup div for images on Favourites/Recently Viewed */
var viewport = {
    getWinWidth: function () {
        this.width = document.body.clientWidth;
    },

    getWinHeight: function () {
        this.height = document.body.clientHeight;
    },

    getScrollX: function () {
        this.scrollX = this.scrollX = document.body.scrollLeft;
    },

    getScrollY: function () {
        this.scrollY = document.body.scrollTop;
    },

    getAll: function () {
        this.getWinWidth(); this.getWinHeight();
        this.getScrollX(); this.getScrollY();
    }

}

var ImagePopup = {
    followMouse: true,
    offX: 0,
    offY: 12,
    elemID: "ImagePopupDiv",
    showDelay: 100,
    hideDelay: 200,
    ready: false,
    timer: null,
    elem: null,
    init: function () {
        if (document.createElement && document.body && typeof document.body.appendChild != "undefined") {/*
        if(!document.getElementById(this.elemID)) {
          var elem=document.createElement("DIV");
          elem.id=this.elemID;
          document.body.appendChild(elem);
        }*/
            this.ready = true;
        }
    },
    show: function (e, msg) {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = 0;
        }
        this.elem = document.getElementById(this.elemID);
        if (this.followMouse) {
            if (document.addEventListener) document.addEventListener("mousemove", this.trackMouseCallback, true);
            else if (document.attachEvent) document.attachEvent("onmousemove", this.trackMouseCallback);
        }
        this.writePopup("");
        this.writePopup(msg);
        viewport.getAll();
        //debugger;
        this.positionPopup(e);
        this.timer = setTimeout("ImagePopup.toggleVis('" + this.elemID + "', 'visible')", this.showDelay);
    },
    writePopup: function (msg) {
        if (this.elem && typeof this.elem.innerHTML != "undefined")
            this.elem.innerHTML = msg;
    },
    hide: function () {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = 0;
        }
        this.timer = setTimeout("ImagePopup.toggleVis('" + this.elemID + "', 'hidden')", this.hideDelay);
        if (this.followMouse) {
            if (document.removeEventListener) document.removeEventListener("mousemove", this.trackMouseCallback, true);
            else if (document.detachEvent) document.detachEvent("onmousemove", this.trackMouseCallback);
        }
        this.elem = null;
    },
    toggleVis: function (id, vis) {
        var el = document.getElementById(id);
        if (el)
            el.style.visibility = vis;
    },
    trackMouseCallback: function (e) {
        e = e ? e : window.event;
        e.tgt = e.srcElement ? e.srcElement : e.target;

        if (!e.preventDefault) e.preventDefault = function () { return false; }
        if (!e.stopPropagation) e.stopPropagation = function () { if (window.event) window.event.cancelBubble = true; }
        ImagePopup.positionPopup(e);
    },
    positionPopup: function (e) {
        if (this.elem && this.elem.style) {
            var x = 0;
            if (this.offX > 0) {  //LTR
                x = e.clientX;
                if (x + this.elem.offsetWidth + this.offX > viewport.width + viewport.scrollX) {
                    x -= this.elem.offsetWidth - this.offX;
                    if (x < 0) x = 0;
                } else {
                    x += this.offX;
                }
            } else {  //RTL
                x = e.clientX - this.elem.parentElement.offsetLeft - this.elem.parentElement.offsetWidth - this.elem.scrollWidth;
                if (document.body.clientWidth - e.clientX + this.elem.scrollWidth + 4 - this.offX * 2 > document.body.clientWidth) {
                    x += this.elem.scrollWidth;
                } else {
                    x += this.offX;
                }
            }

            var y = e.pageY ? e.pageY : e.clientY + viewport.scrollY;
            if (y + this.elem.offsetHeight + this.offY > viewport.height + viewport.scrollY) {
                y = y - this.elem.offsetHeight - this.offY;
                if (y < viewport.scrollY) {
                    y = viewport.height + viewport.scrollY - this.elem.offsetHeight;
                }
            } else {
                y = y + this.offY;
            }
            //debugger;
            this.elem.style.left = (x - (typeof divStayTopLeft != "undefined" ? divStayTopLeft.offsetLeft : 0) - (typeof CurFloater != 'undefined' && CurFloater ? CurFloater.offsetLeft : 0)) + "px";
            this.elem.style.top = (y - (typeof divStayTopLeft != "undefined" ? divStayTopLeft.offsetTop : 0) - (typeof CurFloater != 'undefined' && CurFloater ? CurFloater.offsetTop : 0) - (typeof this.elem.parentElement != 'undefined' ? this.elem.parentElement.offsetTop : 0)) + "px";
        }
    }
};

function showImagePopup(e, img, txt) {
    if (typeof ImagePopup == "undefined" || !ImagePopup.ready) return;

    ImagePopup.offX = /rtl/i.test(document.dir) ? -8 : 8;
    var content = "";
    if (img) content += '<div class="thumb_img"><img src="' + img + '"></div>';
    if (txt) content += '<div class="thumb_txt">' + txt + '</div>';
    ImagePopup.show(e, content)
}

function hideImagePopup() {
    if (typeof ImagePopup == "undefined" || !ImagePopup.ready) return;
    ImagePopup.hide();
}
/* END Popup div for images on Favourites/Recently Viewed */

//Function to retrieve cookie value
function getCookie(name) {
    var sPos = document.cookie.indexOf(name + "=");
    var len = sPos + name.length + 1;
    if ((!sPos) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (sPos == -1) {
        return null;
    }
    var ePos = document.cookie.indexOf(';', len);
    if (ePos == -1) ePos = document.cookie.length;
    return unescape(document.cookie.substring(len, ePos));
}

//The onclick event for scrolling or not scrolling from the checkbox
function StopStartScrolling() {
    if (document.getElementById("CanScrollRegional") != null) {
        if (document.getElementById("CanScrollRegional").checked == true) {
            document.cookie = "CanScroll=NO;";
        }
        else {
            document.cookie = "CanScroll=YES;";
        }
        JSFX_FloatTopDiv();
    }
}

function SetScrolling() {
    if (document.getElementById("CanScrollRegional") != null) {
        if (document.getElementById("CanScrollText") != null) {
            MainWebService.instance().getTranslations("GtTranslationManagerScroll", "130.DontScrollColumn", "Remax", "130", "Lang", languageCode).done(function (data) {
                document.getElementById("CanScrollText").innerHTML = data.d;
            }).fail(function (xhr) { });
            //document.getElementById("CanScrollText").innerHTML = Gryphtech.Slingshot.SlingshotAddin.AjaxMethods.GetTranslations("GtTranslationManagerScroll", "130.DontScrollColumn", "Remax", "130", "Lang", languageCode).value;
        }
        if (getCookie("CanScroll") == "NO") {
            document.getElementById("CanScrollRegional").checked = true;
        }
        else if (getCookie("CanScroll") == "YES") {
            document.getElementById("CanScrollRegional").checked = false;
        }
        else {
            document.getElementById("CanScrollRegional").checked = false;
        }
    }
}

var ftlObj = null;
/* Floating Sidebar */
function JSFX_FloatTopDiv() {
    var scrolling;

    if (getCookie("CanScroll") == "NO") {
        scrolling = false;
        if (document.getElementById("CanScrollRegional") != null) {
            document.getElementById("CanScrollRegional").checked = true;
        }
    }
    else if (getCookie("CanScroll") == "YES") {
        scrolling = true;
        if (document.getElementById("CanScrollRegional") != null) {
            document.getElementById("CanScrollRegional").checked = false;
        }
    }
    else {//When coookie "CanScroll" is null
        scrolling = true;
        if (document.getElementById("CanScrollRegional") != null) {
            document.getElementById("CanScrollRegional").checked = false;
        }
    }

    function ml(id) {
        var el = d.getElementById ? d.getElementById(id) : (d.all ? d.all[id] : d.layers[id]);
        if (d.layers) el.style = el;
        el.sP = function (x, y) {
            this.style.left = x;
            if (y > -1) {
                this.style.top = y;
            }
            else {//Sends floating div back to top
                this.style.top = 0;
            }
        };
        el.x = startX;

        if (typeof verticalpos == 'undefined') {
            el.y = 0;
        }
        else if (verticalpos == 'fromtop') {
            el.y = startY;
        }
        else {
            el.y = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
            el.y -= startY;
        }

        return el;
    }

    window.stayTopLeft = function () {
        if (typeof verticalpos == 'undefined') {
            var pY = 0;
            ftlObj.y = 0;
        }
        else if (verticalpos == 'fromtop') {
            var pY = ns ? pageYOffset : document.body.scrollTop;
            ftlObj.y += (pY + startY - ftlObj.y) / 8;
        }
        else {
            var pY = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
            ftlObj.y += (pY - startY - ftlObj.y) / 8;
        }
        if (document.body.scrollTop + (typeof CurChildFloater != 'undefined' ? CurChildFloater.scrollHeight : 0) + 5 > MainFooterDiv.offsetTop) {
            ftlObj.y = MainFooterDiv.offsetTop - (typeof CurChildFloater != 'undefined' ? CurChildFloater.scrollHeight : 0) - (typeof CurrentFloatingTop != 'undefined' ? CurrentFloatingTop : 0) - 5;
        }
        else if (document.body.scrollTop - (typeof CurrentFloatingTop != 'undefined' ? CurrentFloatingTop : 0) < 0) {
            ftlObj.y = 0
        }

        ftlObj.sP(ftlObj.x, ftlObj.y);
        setTimeout('stayTopLeft()', 10);
    }
    var startX = 0;
    var startY;
    var ns = (navigator.appName.indexOf('Netscape') != -1);
    var d = document;

    if (scrolling) {
        startY = (typeof CurrentFloatingTop != 'undefined' ? -CurrentFloatingTop : 0) + 5;
        ftlObj = ml('divStayTopLeft');
        stayTopLeft();
    }
}


/* Europe Modules */
function loadRegion(whichForm) {
    el = document.getElementById(whichForm).value;
    if (el != "Select Region")
        window.location.href = el;
}

function enableButton(whichForm, whichButton) {
    el = document.getElementById(whichButton);
    el2 = document.getElementById(whichForm).value;
    if (el2 != "Select Region") {
        el.disabled = false;
        el.className = "btnEnabled"
    } else {
        el.disabled = true;
        el.className = "btnDisabled"
    }
}

/**/

/*Portugal's Form */

function validate(frmForm) { // function not  found to be  used. 
    // Place validation code here if required.
    var requiredInfoMissing = false;
    var bgcolorRed = "#ff0000";
    var bgcolorWhite = "#ffffff";

    if (document.getElementById("Nome Completo").value == "") {
        document.getElementById("Nome Completo").style.background = bgcolorRed;
        document.getElementById("Nome Completo").focus();
        requiredInfoMissing = true;
    }
    else {
        document.getElementById("Nome Completo").style.background = bgcolorWhite;
    }

    if (document.getElementById("Telefone").value == "") {
        document.getElementById("Telefone").style.background = bgcolorRed;
        document.getElementById("Telefone").focus();
        requiredInfoMissing = true;
    }
    else {
        document.getElementById("Telefone").style.background = bgcolorWhite;
    }

    if (document.getElementById("Telemovel").value == "") {
        document.getElementById("Telemovel").style.background = bgcolorRed;
        document.getElementById("Telemovel").focus();
        requiredInfoMissing = true;
    }
    else {
        document.getElementById("Telemovel").style.background = bgcolorWhite;
    }



    if (requiredInfoMissing) {
        return false;
    }
    else {
        frmForm.submit();
        return true;
    }

}

function ValidateForm() {
    //debugger;
    var office = MM_findObj("officename");
    //could have used  jquery text(), but  not loaded  at this  time.
    if (document.all) {
        if (!office.innerText.length > 0) {
            // copy needed.
            alert('Por favor seleccione a Loja.');
            return false;
        }
    }
    else {
        if (!office.textContent.length > 0) {
            // copy needed.
            alert('Por favor seleccione a Loja.');
            return false;
        }
    }
    return true;
}


/**/

function SetQueryStringParam(qs, pname, pvalue) {
    if (qs.length > 1) this.q = qs.substring(1, qs.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (this.q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.found = false;
    for (var j = 0; j < this.keyValuePairs.length && !this.found; j++) {
        if (this.keyValuePairs[j].split("=")[0] == pname) {
            this.keyValuePairs[j] = pname + "=" + pvalue;
            this.found = true;
        }
    }
    if (!this.found) {
        this.keyValuePairs[this.keyValuePairs.length] = pname + "=" + pvalue;
    }
    this.q = "?";
    for (var k = 0; k < this.keyValuePairs.length; k++) {
        this.q += keyValuePairs[k] + "&";
    }
    this.q = this.q.substring(0, this.q.length - 1);
    return this.q;
}

function CheckValue(obj, target) {
    if (document.getElementById(target) != null) {
        return document.getElementById(target).value == obj.value;
    }
    return true;
}

function SetValue(obj, target) {
    var targetid = "";
    if (target == "ProvinceId") {
        targetid = "ddlProvince";
        $("[id$=ddlProvince]").val(obj.value);
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'Province');
        }
    }
    else if (target == "RegionRowId") {
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'Region');
        }
    }
    else if (target == "CityId") {
        targetid = "ddlCity";
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'City');
        }
    }
    else if (target == "PropertyType") {
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'PropertyType');
        }
    }
    else if (target == "TotalNumOfRooms") {
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'Rooms');
        }
    }
    else if (target == "SqMeter") {
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'MinSqM');
        }
    }
    else if (target == "MinNumOfBedrooms") {
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Search Filters', 'Bedrooms');
        }
    }

    else if (target == 'ListingsAdded') {
        $("[id$='ListingsAddedChange']").val("1");
    }
    else if ((target == 'Zip1') && ($("[id$='rzip']").length > 0)) {
        if (obj.value != '' && typeof (obj.value) != 'undefined') {
            $("[id$='rzip']").val(obj.value);
        }
    }

    if ($("[id$='" + targetid + "'] span").length > 0 && $("[id$='" + targetid + "'] :selected").length > 0) {
        $("[id$='" + targetid + "'] span")[0].innerHTML = $("[id$='" + targetid + "'] :selected")[0].text;
    }

    if (document.getElementById(target) != null) {
        var value = obj.value;
        if (typeof (value) == "undefined" || value == null || value == "" || value == "-1") {
            //exceptions
            if (target == "FloorLevel"
                || target == "Zip1"
                || target == "Zip2"
                || target == "Street"
                || target == "MLSID"
                || target == "txtFirstName"
                || target == "txtLastName"
                || target == "txtNewPassword") {
                document.getElementById(target).value = "";
            }
            else {
                SetZero(target);
            }
        }
        else {
            document.getElementById(target).value = value;
        }
    }
}

function SetZero(target) {
    var targetid = "";
    if (target == "ProvinceId") {
        targetid = "ddlProvince";
    }
    else if (target == "CityId") {
        targetid = "ddlCity";
    }
    if ($("[id$='" + targetid + "'] span").length > 0) {
        $("[id$='" + targetid + "'] span")[0].innerHTML = $("[id$='" + targetid + "'] select option[value='0']").text();
    }
    if (document.getElementById(target) != null)
        document.getElementById(target).value = '0';
}

function AjaxBind_Select_DataTable(selectObj, dataTableObj, valueFieldName, textFieldName, defaultOptionText) {
    //clear select before binding
    selectObj.options.length = 1;

    if (dataTableObj != null && dataTableObj.value != null && dataTableObj.value.Rows != null) {
        var isIE = false;
        if (navigator.appVersion.indexOf("MSIE") != -1) isIE = true;
        for (var i = 0; i < dataTableObj.value.Rows.length; ++i) {
            var row = dataTableObj.value.Rows[i];
            var oOption = new Option(row[textFieldName], row[valueFieldName]);
            if (isIE) {
                selectObj.add(oOption); // IE only
            } else {
                selectObj.add(oOption, null); // standards compliant
            }
        }
    }
    if (defaultOptionText != null && defaultOptionText != "") {
        selectObj.options[0].text = defaultOptionText;
        selectObj.options[0].value = '0';
    }
    else {
        selectObj.remove(0);
    }
}

function GetSelectedItem(ddlId) {
    var DDL = document.getElementById(ddlId);
    var val = "";
    if (DDL != null && DDL.selectedIndex != -1)
        val = DDL.options[DDL.selectedIndex].value;
    if (isNaN(val)) {
        return 0;
    }
    else {
        return val;
    }
}

function SetSelectValue(ddlId, val) {
    var selectobj = document.getElementById(ddlId);
    if (selectobj != null && val != null && val >= 0) {
        for (var i = 0; i < selectobj.length; i++)
            if (selectobj.options[i].value == val)
                selectobj.selectedIndex = i;
    }
}

var persistmenu = "yes" //"yes" or "no". Make sure each SPAN content contains an incrementing ID starting at 1 (id="sub1", id="sub2", etc)
var persisttype = "sitewide" //enter "sitewide" for menu to persist across site, "local" for this page only


function clearCookie() {
    var cookie_date = new Date();  // current date & time
    cookie_date.setTime(cookie_date.getTime() - 1);
    blockid = 1;
    var cookiename = (persisttype == "sitewide") ? "switchmenu" : window.location.pathname;
    var cookievalue = (persisttype == "sitewide") ? blockid + ";path=/" : blockid;
    //alert(cookiename);
    document.cookie = cookiename + "=" + cookievalue;
}

function checkMyForm() {
    form = document.getElementById("sellContactForm");

    if (form.txtFullName.value == "") {
        alert("Please fill in your full name");
        form.txtFullName.focus();
        return false;
    }

    if (form.txtEmailAddress.value == "") {
        alert("Please fill in your email address");
        form.txtEmailAddress.focus();
        return false;
    }

    if (form.txtPhone.value == "") {
        alert("Please fill in your phone number");
        form.txtPhone.focus();
        return false;
    }

    if (form.txtCityLong.value == "") {
        alert("Please fill in your city");
        form.txtCityLong.focus();
        return false;
    }

    if (form.txtOfficeEmail.value == "") {
        alert("Please select an office");
        return false;
    }

    if (form.selPropertyType.value == "0") {
        alert("Please select a Property Type");
        return false;
    }

    return true;

}


function CheckRequiredFields() { //function not  found to be  used. 
    var errormessage = new String();
    if (WithoutContent(document.getElementById("officename").innerHTML))
    { errormessage += "\n\nBitte wählen Sie ein Büro aus durch anklicken des Büronamens."; }
    if (errormessage.length > 2) {
        alert(errormessage);
        return false;
    }
    return true;
}


function WithoutContent(ss) {
    if (ss.length > 0) { return false; }
    return true;
}

function clearDefault(el) {
    if (el.defaultValue == el.value) el.value = "";
}
function restoreDefault(el) {
    if (el.value == "") {
        el.value = el.defaultValue;
    }
}

function ShowHideFeatures(obj) { //function not used 
    if (obj != null) {
        if (obj.value == 2) //Residential
        {
            if (document.getElementById("divPropertyType") != null) {
                document.getElementById("divPropertyType").style.display = "inline";
            }
            if (document.getElementById("divCommPropertyType") != null) {
                document.getElementById("divCommPropertyType").style.display = "none";
            }
        }
        if (obj.value == 1) //Commercial
        {
            if (document.getElementById("divPropertyType") != null) {
                document.getElementById("divPropertyType").style.display = "none";
            }
            if (document.getElementById("divCommPropertyType") != null) {
                document.getElementById("divCommPropertyType").style.display = "inline";
            }
        }
    }
}

function ClearValue() {
    if (document.forms[0]) {
        document.forms[0].reset;
    }
}

function SetStatusValue(obj, target) {
    if (obj.checked) {
        document.getElementById(target).value = obj.value;
    }
    else {
        document.getElementById(target).value = "";
    }
}

var minPrice = "";
function SetMinPrice(MinPriceVal) {
    minPrice = MinPriceVal;
}

function SetMinMaxPriceRange(obj, divPriceClientId, divRentalPriceClientId, ddlMinPriceClientId, ddlMaxPriceClientId, ddlRentalMinPriceClientId, ddlRentalMaxPriceClientId) {
    var ddlMinPrice = document.getElementById(ddlMinPriceClientId);
    var ddlMaxPrice = document.getElementById(ddlMaxPriceClientId);
    var ddlRentalMinPrice = document.getElementById(ddlRentalMinPriceClientId);
    var ddlRentalMaxPrice = document.getElementById(ddlRentalMaxPriceClientId);
    var MinPrice = document.getElementById("MinPrice");
    var MaxPrice = document.getElementById("MaxPrice");
    var RentalMinPrice = document.getElementById("RentalMinPrice");
    var RentalMaxPrice = document.getElementById("RentalMaxPrice");

    if (obj.value == '260' || obj.value == '262' || obj.value == 'For Rent/Lease' || obj.value == 'Holiday/Short Term Rental') {
        if (document.getElementById(divPriceClientId) != null) {
            document.getElementById(divPriceClientId).style.visibility = "hidden";
            document.getElementById(divPriceClientId).style.display = "none";
        }
        if (document.getElementById(divRentalPriceClientId) != null) {
            document.getElementById(divRentalPriceClientId).style.visibility = "visible";
            document.getElementById(divRentalPriceClientId).style.display = "";
        }
        if (ddlMinPrice != null) {
            MinPrice.value = "";
            ddlMinPrice.selectedIndex = 0;
        }
        if (ddlMaxPrice != null) {
            MaxPrice.value = "";
            ddlMaxPrice.selectedIndex = 0;
        }
    }
    else {
        if (document.getElementById(divPriceClientId) != null) {
            document.getElementById(divPriceClientId).style.visibility = "visible";
            document.getElementById(divPriceClientId).style.display = "";
        }
        if (document.getElementById(divRentalPriceClientId) != null) {
            document.getElementById(divRentalPriceClientId).style.visibility = "hidden";
            document.getElementById(divRentalPriceClientId).style.display = "none";
        }
        if (ddlRentalMinPrice != null) {
            ddlRentalMinPrice.selectedIndex = 0;
            RentalMinPrice.value = "";
        }
        if (ddlRentalMaxPrice != null) {
            ddlRentalMaxPrice.selectedIndex = 0;
            RentalMaxPrice.value = "";
        }

        MinPrice.value = minPrice;

        for (i = 0; i < ddlMinPrice.length; i++) {
            if (ddlMinPrice.options[i].value == minPrice) {
                ddlMinPrice.selectedIndex = i;
            }
        }

        SetValue(ddlMinPrice, 'MinPrice');
    }
}

function ToggleFavourite(obj, Remove) {
    if (window.addToFavsJSON && (obj == addToFavsJSON.listingKey)) {
        var $addToFavsDiv = $('#gallery-icons-container').find('div[type=addtofavs]');
        $addToFavsDiv
        .data('favourite', Remove)
        .find('i').removeClass('fav fav-on').addClass(Remove ? 'fav-on' : 'fav');
    }
    return false;
}

function ToggleFavouriteInListing(obj, Remove, contextWindow) {
    contextWindow = contextWindow || window;
    var $div = $("#divFav_" + obj, contextWindow.document);
    //change the class for the fav on listinglist map popup
    var $listinglistfavonmap = $("[id$='" + "liFavOnMap_" + obj + "']", contextWindow.document);
    if (Remove) {
        $div.removeClass('fav fav-on').addClass("fav-on");
        $div.attr("onclick", "AddRemoveFavourite('" + obj + "',false)");
        if ($listinglistfavonmap.length > 0) {
            $listinglistfavonmap.removeClass('fav fav-on').addClass("fav-on");
        }
        InsertGoogleTagManagerEvent('Add to Favourites', 'Click', 'Listing List Add to Favourites');
    }
    else {
        $div.removeClass('fav fav-on').addClass("fav");
        $div.attr("onclick", "AddRemoveFavourite('" + obj + "',true)");
        if ($listinglistfavonmap.length > 0) {
            $listinglistfavonmap.removeClass('fav fav-on').addClass("fav");
        }
    }
    return false;
}

function UpdateMyFavouritesDatagrid() {
    var win = window;
    if (!win.remFavText && window.parent)
        win = window.parent; // if called from frame then reference this frame's parent window

    function process(tableData) {
        var innerdiv = win.document.getElementById('divMFDatagrid');
        innerdiv.innerHTML = tableData.value;

        window.FavouriteListingKeys = [];
        $('#tblRecentFavs tr').each(function () {
            window.FavouriteListingKeys.push($(this).attr('listing_key'));
        });
    }

    if (AjaxAsynchMethodsForFavourites && AjaxAsynchMethodsForFavourites.UpdateDataGrid) {
        var jqXHRpromise = AjaxAsynchMethodsForFavourites.UpdateDataGrid({
            removeFavourite: win.remFavText,
            noFavourites: win.noFavText,
            MaxListings: win.maxFavs,
            CookieExpDays: win.favCookieExp,
            Lang: win.langMF,
            EncLang: win.encLangMF,
            FormatRegionID: win.formatRegionId
        });
        jqXHRpromise.done(function (response) {
            var tableData = eval('(' + response + ')');
            process(tableData);
        });
    }
    else {
        var tableData = win.SmartModuleMyRegistration.SmartModuleFullMyFavourites.UpdateDataGrid(win.remFavText, win.noFavText, win.maxFavs, win.favCookieExp, win.langMF, win.encLangMF, win.formatRegionId);
        process(tableData);
    }
}

function AddRemoveFavourite(obj, Add) {
    if (Add) {
        var jqXHRpromise = AjaxAsynchMethodsForFavourites.AddPropertyToFavourites(obj)
    }
    else {
        var jqXHRpromise = AjaxAsynchMethodsForFavourites.RemovePropertyFromFavourites(obj);
    }

    jqXHRpromise.done(function () {
        updateMyFavoritesButtons(obj);
        ToggleFavourite(obj, Add);

        var win = window;

        ToggleFavouriteInListing(obj, Add, win);

        if (typeof (win.FavClicked) != 'undefined') win.FavClicked({ ListingKey: obj, Checked: Add });

        if (typeof (UpdateMyFavouritesDatagrid) != 'undefined') UpdateMyFavouritesDatagrid();
    });
}

function AddRemoveFavouriteListingFull(obj, Add) {
    AddRemoveFavourite(obj, Add);
}


function sizeAdjust(imgObj) {
    imgObj = document.getElementById('SLIDESIMG');
    imgObj.style.visibility = 'hidden';
    imgObj.style.height = 'auto';
    imgObj.style.display = 'inline';
    if (imgObj.height > 375) imgObj.style.height = 375;
    imgObj.style.visibility = 'visible';
}

function swap(imageID, imageNumber, imageCount, ofTranslation) {
    try {
        SLIDES.pause();

        SLIDES.goto_slide(imageNumber - 1);
    }
    catch (ex) {
        alert(ex.description);
    }
}

function GotoPage(val) {
    $(window).scrollTop(0);
    document.getElementById("CurrentPage").value = val;
    AutoSearch();
}

function setMapList(map) {
    var imgmap = document.getElementById("imgMap");
    var imglist = document.getElementById("imgList");
    var lnkmap = document.getElementById("lnkMap");
    var lnklist = document.getElementById("lnkList");
    document.getElementById("maplist").value = map;
    if (map) {
        imgmap.src = "/common/images/interface/check_on.png";
        imglist.src = "/common/images/interface/check_off.png";
        lnkmap.style.color = "Red";
        lnklist.style.color = "Gray";
    } else {
        imgmap.src = "/common/images/interface/check_off.png";
        imglist.src = "/common/images/interface/check_on.png";
        lnkmap.style.color = "Gray";
        lnklist.style.color = "Red";
    }
}

function toggleMapSearch(lnk, img, hid) {
    if (typeof (lnk) != 'undefined' && typeof (img) != 'undefined' && typeof (hid) != 'undefined') {
        hid.value = (hid.value == '' || hid.value == 1) ? 0 : 1;
        toggleMapSearchImage(lnk, img, hid);
    }
}

function toggleMapSearchImage(lnk, img, hid) {
    if (lnk != null && typeof (lnk) != 'undefined' && img != null && typeof (img) != 'undefined' && hid != null && typeof (hid) != 'undefined') {
        if (hid.value == 1) {
            img.src = "/common/images/interface/check_on.png";
        } else {
            img.src = "/common/images/interface/check_off.png";
        }
    }
}

var debugPanel = (function () {

    var panel = null;
    var isFixed = false;

    var getPanel = function (rows) {
        var height1 = 20 * rows;
        var height2 = parseInt(height1 - (height1 * 0.25));

        return (
        $("<table id='debugPanel-container' cellpadding=0 cellspacing=0 style='width:100%; height:" + height1 + "px;'><tr><td style='vertical-align:top'> " +
          " <div style='width:100%; height:100%; background-color:Chartreuse'> " +
          "  <fieldset style='border:1px inset black; width:99%; height:" + height2 + "px; font-family:Arial; font-size:10px'> " +
          "   <legend><b>Debug Panel&nbsp; " +
          "   <a href=# onclick=\"$('#debugPanel-container-msg').html('');$('#debugPanel-container').hide();\" style='color:red' title='hide debug panel (also clears accumulated messages)'>x</a></b></legend> " +
          "   <div style='width:100%; height:100%; overflow-y:auto; overflow-x:hidden' id='debugPanel-container-msg'></div> " +
          "  </fieldset> " +
          " </div> " +
          "</td></tr></table> ")
          .css('position', 'fixed')
          .css('left', 0)
          .css('top', 0)
          .css('font-color', 'black')).get(0);
    }

    var write = function (msg, rows, delim) {
        if (!rows) rows = 2;
        if (!delim) delim = "|";
        if (isFixed) delim = "";

        if (panel) {
            $(panel).show();
        } else {
            $(getPanel(rows)).appendTo(document.body);
            panel = $('#debugPanel-container').get(0);
        }

        var panelMsg = $('#debugPanel-container-msg').get(0);

        var html = $(panelMsg).html();
        html = (isFixed ? "" : html) + msg + "&nbsp;" + delim + "&nbsp;";
        $(panelMsg).html(html);
    }

    return { // we use global var: isFixed to avoid passing it as param to function: write
        write: function (msg, rows, delim) { isFixed = false; write(msg, rows, delim); },
        writeFixed: function (msg, rows) { isFixed = true; write(msg, rows); }
    }
})();

function addOption(elementRef, optionText, optionValue) {
    var newOption = document.createElement('option');

    newOption.appendChild(document.createTextNode(optionText));
    newOption.setAttribute('value', optionValue);
    elementRef.appendChild(newOption);
}

function setUpPriceRange(elementRef, currencyCode, category, translation, regionID) {
    elementRef.options.length = 0;
    MainWebService.instance().getPriceRange(currencyCode, category, translation, regionID).done(function (data) {
        var priceRangeValues =  ServiceBase.getResponseValueObj(data);
       // var priceRangeValues = Gryphtech.Slingshot.SlingshotAddin.AjaxMethods.GetPriceRange(currencyCode, category, translation, regionID);
        var arrayOfPriceRanges = priceRangeValues.value.split('@');
        for (var i = 0; i <= arrayOfPriceRanges.length - 1; i++) {
            var curPriceRange = arrayOfPriceRanges[i].split('|');
            if (curPriceRange.length == 2) {
                addOption(elementRef, curPriceRange[1], curPriceRange[0]);
            }
        }

        var text = "";
        if (elementRef.options.length > 0) {
            text = elementRef.options[0].innerHTML;
        }
        if ($("[id$='" + elementRef.id + "'] span").length > 0) {
            $("[id$='" + elementRef.id + "'] span")[0].innerText = $("[id$='" + elementRef.id + "'] span")[0].innerHTML = text;
        }

    }).fail(function (xhr) { });
}

var blnForSale = 1;
function ValidatePriceRange() {
    if (blnForSale == 1 && document.getElementById(ddlMinPriceClientID).value > 0 && document.getElementById(ddlMaxPriceClientID).value > 0 && parseInt(document.getElementById(ddlMinPriceClientID).value) > parseInt(document.getElementById(ddlMaxPriceClientID).value)) {
        alert(PriceRangeValidationMessage);
        return false;
    }
    else if (blnForSale == 0 && document.getElementById(ddlRentalMinPriceClientID).value > 0 && document.getElementById(ddlRentalMaxPriceClientID).value > 0 && parseInt(document.getElementById(ddlRentalMinPriceClientID).value) > parseInt(document.getElementById(ddlRentalMaxPriceClientID).value)) {
        alert(PriceRangeValidationMessage);
        return false;
    }
    return true;
}

function SetSearchType(type) {
    if (document.getElementById('FTSQSearchType') != null) {
        document.getElementById('FTSQSearchType').value = type;
    }
    else {
        document.getElementById('QSearchType').value = type;
    }
}

function SetCurrency(currencyCode, ddlCurrencyClientId, lblCurrencyClientId, regionID) {
    document.getElementById('Currency').value = currencyCode;
    var ddlCurrency = document.getElementById(ddlCurrencyClientId);
    var lblCurrency = document.getElementById(lblCurrencyClientId);
    for (var i = 0; i < ddlCurrency.options.length; i++) {
        if (ddlCurrency.options[i].value == currencyCode) {
            ddlCurrency.selectedIndex = -1;
            ddlCurrency.selectedIndex = i;
            break;
        }
    }

    var oldCurrency = lblCurrency.innerHTML;

    if (currencyCode == "GBP") {
        lblCurrency.innerHTML = "&pound;";
    }
    else if (currencyCode == "EUR") {
        lblCurrency.innerHTML = "&euro;";
    }
    else if (currencyCode == "FRF") {
        lblCurrency.innerHTML = "&#x20a3;";
    }
    else if (currencyCode == "INR") {
        lblCurrency.innerHTML = "Rs.";
    }
    else if (currencyCode == "BRL") {
        lblCurrency.innerHTML = "R$";
    }
    else if (currencyCode == "NIS") {
        lblCurrency.innerHTML = "&#8362;";
    }
    else if (currencyCode == "PYG") {
        lblCurrency.innerHTML = "&#8370;";
    }
    else if (currencyCode == "TZS") {
        lblCurrency.innerHTML = "x/y";
    }
    else if (currencyCode == "UAH") {
        lblCurrency.innerHTML = "&#8372;";
    }
    else if (currencyCode == "NGN") {
        lblCurrency.innerHTML = "&#8358;";
    }
    else if (currencyCode == "OMR") {
        lblCurrency.innerHTML = "OMR";
    }
    else if (currencyCode == "CLP") {
        lblCurrency.innerHTML = "&#36;";
    }
    else if (currencyCode == "MNT") {
        lblCurrency.innerHTML = "&#8366;";
    }
    else if (currencyCode == "BOB") {
        lblCurrency.innerHTML = "Bs";
    }
    else if (currencyCode == "CLF") {
        lblCurrency.innerHTML = "UF"; // Chilean Unidad de Fomento CR #98061
    }
    else if (currencyCode == "AMD") {
        lblCurrency.innerHTML = "&#1423;"; // Armenian Dram CR # 98194
    }
    else if (currencyCode == "MYR") {
        lblCurrency.innerHTML = "RM"; // Malaysian Ringgit CR # 104054
    }
    else if (currencyCode == "LKR") {
        lblCurrency.innerHTML = "Rs."; // Sri Lanka Rupees CR # 107193
    }
    else if (currencyCode == "GHS") {
        lblCurrency.innerHTML = "GH&#8373;"; //  GHS - Ghanaian Cedi CR # 110279
    }
    else if (currencyCode == "THB") {
        lblCurrency.innerHTML = "&#3647;"; //  THB - Thai baht CR # 110849
    }
    else {
        lblCurrency.innerHTML = currencyCode;
    }

    if (oldCurrency != lblCurrency.innerHTML) {
        setUpPriceRange(document.getElementById(ddlMinPriceClientID), currencyCode, "MinPriceRange", MinPriceTranslation, regionID);
        setUpPriceRange(document.getElementById(ddlMaxPriceClientID), currencyCode, "MaxPriceRange", MaxPriceTranslation, regionID);
        setUpPriceRange(document.getElementById(ddlRentalMinPriceClientID), currencyCode, "RentalMinPriceRange", MinPriceTranslation, regionID);
        setUpPriceRange(document.getElementById(ddlRentalMaxPriceClientID), currencyCode, "RentalMaxPriceRange", MaxPriceTranslation, regionID);
    }

    if (currentTab != null) {
        AutoSearch();
    }
}

function SetCombinedPropertyType(obj, target1, target2) {
    SetDropdownValue(obj.value);
    var data = obj.value.split(',');
    if (data.length == 2) {
        if (document.getElementById(target1) != null)
            document.getElementById(target1).value = data[0];

        if (document.getElementById(target2) != null)
            document.getElementById(target2).value = data[1];
    }
}

function ShowHidePropertyType(obj, divResObj, divComObj) {
    if (obj != null) {
        if (obj.value == 2) {
            //Residential
            if (divResObj != null) {
                divResObj.style.display = "inline";
            }
            if (divComObj != null) {
                divComObj.style.display = "none";
            }
        } else if (obj.value == 1) {
            //Commercial
            if (divResObj != null) {
                divResObj.style.display = "none";
            }
            if (divComObj != null) {
                divComObj.style.display = "inline";
            }
        }
    }
}


function killBackSpace(e) {
    e = e ? e : window.event;
    var t = e.target ? e.target : e.srcElement ? e.srcElement : null;
    if (t && t.tagName && (t.type && /(password)|(text)|(file)/.test(t.type.toLowerCase())) || t.tagName.toLowerCase() == 'textarea')
        return true;
    var k = e.keyCode ? e.keyCode : e.which ? e.which : null;
    if (k == 8) {
        if (e.preventDefault)
            e.preventDefault();
        return false;
    };
    return true;
};


Number.prototype.roundTo1Decimal = function () {
    return Math.round(this * 10) / 10
}


Number.prototype.roundTo3Decimals = function () {
    return Math.round(this * 1000) / 1000
}


function getNumberOfDaysAgo(date) {
    var today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);

    var date = date.split('T')[0];
    var yymmdd = date.split('-');
    var date = new Date(yymmdd[0], yymmdd[1] - 1, yymmdd[2]);

    var delta = today - date;

    return Math.round(delta / 1000 / 60 / 60 / 24);
}


var timerLeft = "";
var timerRight = "";

function move_left(isClass) {
    clearTimeout(timerRight);
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }

    var scroll_clipper = document.getElementById(divScrollerClientID);
    scrollBefore = scroll_clipper.scrollLeft;
    scroll_clipper.scrollLeft += 2;
    timerRight = setTimeout("move_left(" + useClass + ")", 10);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnrightClientID).setAttribute("class", "chevron-left");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnleftClientID).setAttribute("class", "chevron-right-grey");
        }
        else {
            document.getElementById(btnleftClientID).setAttribute("class", "chevron-right");
        }
    }
    else {
        //Turn on the arrow on the other side, since it can now scroll that way
        document.getElementById(btnrightClientID).src = "/common/images/icon_action_left.gif";

        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnleftClientID).src = "/common/images/icon_action_grey.gif";
        }
    }
}


function move_right(isClass) {
    clearTimeout(timerLeft);

    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }

    //Scroll div
    var scroll_clipper = document.getElementById(divScrollerClientID);
    scrollBefore = scroll_clipper.scrollLeft;
    scroll_clipper.scrollLeft -= 2;
    timerLeft = setTimeout("move_right(" + useClass + ")", 10);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnleftClientID).setAttribute("class", "chevron-right");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnrightClientID).setAttribute("class", "chevron-left-grey");
        }
        else {
            document.getElementById(btnrightClientID).setAttribute("class", "chevron-left");
        }
    }
    else {
        //Turn on the arrow on the other side, since it can now scroll that way
        document.getElementById(btnleftClientID).src = "/common/images/icon_action.gif";

        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnrightClientID).src = "/common/images/icon_action_left_grey.gif";
        }
    }
}

function stopMe() {
    clearTimeout(timerRight);
    clearTimeout(timerLeft);
}

function move_left_click(isClass) {
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }
    var scroll_clipper = document.getElementById(divScrollerClientID);
    var scrollBefore = scroll_clipper.scrollLeft;
    var scrollDifference = scrollBefore / 110;

    var scrollAmount = 0;
    if (scrollDifference == Math.round(scrollDifference)) {
        scroll_clipper.scrollLeft += 110;
    } else {
        scrollDifference = parseInt(scrollDifference) + 1;
        scrollAmount = (110 * scrollDifference) - scrollBefore;
        scroll_clipper.scrollLeft += scrollAmount;
    }

    //scroll_clipper.scrollLeft +=  (110 + scrollAmount);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnrightClientID).setAttribute("class", "chevron-left");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnleftClientID).setAttribute("class", "chevron-right-grey");
        }
        else {
            document.getElementById(btnleftClientID).setAttribute("class", "chevron-right");
        }
    }
    else {
        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnleftClientID).src = "/common/images/icon_action_grey.gif";
        }
    }
}

function move_right_click(isClass) {
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }
    var scroll_clipper = document.getElementById(divScrollerClientID);
    var scrollBefore = scroll_clipper.scrollLeft;
    var scrollDifference = scrollBefore / 110;
    var scrollAmount = 0;
    if (scrollDifference == Math.round(scrollDifference)) {
        scroll_clipper.scrollLeft -= 110;
    } else {
        scrollDifference = parseInt(scrollDifference) + 1;
        scrollAmount = 110 - ((110 * scrollDifference) - scrollBefore);
        scroll_clipper.scrollLeft -= scrollAmount;
    }

    //scroll_clipper.scrollLeft -= (110+scrollAmount);  

    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnleftClientID).setAttribute("class", "chevron-right");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnrightClientID).setAttribute("class", "chevron-left-grey");
        }
        else {
            document.getElementById(btnrightClientID).setAttribute("class", "chevron-left");
        }
    }
    else {
        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnrightClientID).src = "/common/images/icon_action_left_grey.gif";
        }
    }
}

/* Revised  methods */
function navigate_left(isClass, divScrollerObj, btnRightObj, btnLeftObj, type) {
    clearTimeout(timerRight);
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }

    var scroll_clipper = document.getElementById(divScrollerObj);
    scrollBefore = scroll_clipper.scrollLeft;
    scroll_clipper.scrollLeft += 2;
    timerRight = setTimeout("left_move(" + useClass + ",'" + type + "')", 10);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnRightObj).setAttribute("class", "chevron-left");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnLeftObj).setAttribute("class", "chevron-right-grey");
        }
        else {
            document.getElementById(btnLeftObj).setAttribute("class", "chevron-right");
        }
    }
    else {
        //Turn on the arrow on the other side, since it can now scroll that way
        document.getElementById(btnRightObj).src = "/common/images/icon_action_left.gif";
        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnLeftObj).src = "/common/images/icon_action_grey.gif";
        }
    }
}

function navigate_right(isClass, divScrollerObj, btnRightObj, btnLeftObj, type) {
    clearTimeout(timerLeft);

    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }

    //Scroll div
    var scroll_clipper = document.getElementById(divScrollerObj);
    scrollBefore = scroll_clipper.scrollLeft;
    scroll_clipper.scrollLeft -= 2;
    timerLeft = setTimeout("right_move(" + useClass + ", '" + type + "')", 10);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnLeftObj).setAttribute("class", "chevron-right");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnRightObj).setAttribute("class", "chevron-left-grey");
        }
        else {
            document.getElementById(btnRightObj).setAttribute("class", "chevron-left");
        }
    }
    else {
        //Turn on the arrow on the other side, since it can now scroll that way
        document.getElementById(btnLeftObj).src = "/common/images/icon_action.gif";

        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnRightObj).src = "/common/images/icon_action_left_grey.gif";
        }
    }
}

function navigate_left_click(isClass, divScrollerObj, btnRightObj, btnLeftObj) {
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }
    var scroll_clipper = document.getElementById(divScrollerObj);
    var scrollBefore = scroll_clipper.scrollLeft;
    var scrollDifference = scrollBefore / 110;

    var scrollAmount = 0;
    if (scrollDifference == Math.round(scrollDifference)) {
        scroll_clipper.scrollLeft += 110;
    } else {
        scrollDifference = parseInt(scrollDifference) + 1;
        scrollAmount = (110 * scrollDifference) - scrollBefore;
        scroll_clipper.scrollLeft += scrollAmount;
    }

    //scroll_clipper.scrollLeft +=  (110 + scrollAmount);
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnRightObj).setAttribute("class", "chevron-left");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnLeftObj).setAttribute("class", "chevron-right-grey");
        }
        else {
            document.getElementById(btnLeftObj).setAttribute("class", "chevron-right");
        }
    }
    else {
        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnLeftObj).src = "/common/images/icon_action_grey.gif";
        }
    }
}

function navigate_right_click(isClass, divScrollerObj, btnRightObj, btnLeftObj) {
    var useClass = false;
    if (typeof (isClass) != "undefined" && isClass != null) {
        useClass = isClass;
    }
    var scroll_clipper = document.getElementById(divScrollerObj);
    var scrollBefore = scroll_clipper.scrollLeft;
    var scrollDifference = scrollBefore / 110;
    var scrollAmount = 0;
    if (scrollDifference == Math.round(scrollDifference)) {
        scroll_clipper.scrollLeft -= 110;
    } else {
        scrollDifference = parseInt(scrollDifference) + 1;
        scrollAmount = 110 - ((110 * scrollDifference) - scrollBefore);
        scroll_clipper.scrollLeft -= scrollAmount;
    }
    scrollAfter = scroll_clipper.scrollLeft;

    if (useClass) {
        document.getElementById(btnLeftObj).setAttribute("class", "chevron-right");
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnRightObj).setAttribute("class", "chevron-left-grey");
        }
        else {
            document.getElementById(btnRightObj).setAttribute("class", "chevron-left");
        }
    }
    else {
        //check for end of scroll, if it is grey out the arrow
        if (scrollBefore == scrollAfter) {
            document.getElementById(btnRightObj).src = "/common/images/icon_action_left_grey.gif";
        }
    }
}

function left_move(isClass, type) {
    if (typeof (type) != 'undefined') {
        if (type == 'rent') {
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                navigate_left(isClass, Feature_Rented_PropertyRef.scroller, Feature_Rented_PropertyRef.right, Feature_Rented_PropertyRef.left, type);
            }
        }
        else if (type == 'list') {
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                navigate_left(isClass, Feature_Listed_PropertyRef.scroller, Feature_Listed_PropertyRef.right, Feature_Listed_PropertyRef.left, type);
            }
        }
        else if (type == 'sold') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                navigate_left(isClass, Feature_Sold_PropertyRef.scroller, Feature_Sold_PropertyRef.right, Feature_Sold_PropertyRef.left, type);
            }
        }
    }
}

function right_move(isClass, type) {
    if (typeof (type) != 'undefined') {
        if (type == 'rent') {
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                navigate_right(isClass, Feature_Rented_PropertyRef.scroller, Feature_Rented_PropertyRef.right, Feature_Rented_PropertyRef.left, type);
            }
        }
        else if (type == 'list') {
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                navigate_right(isClass, Feature_Listed_PropertyRef.scroller, Feature_Listed_PropertyRef.right, Feature_Listed_PropertyRef.left, type);
            }
        }
        else if (type == 'sold') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                navigate_right(isClass, Feature_Sold_PropertyRef.scroller, Feature_Sold_PropertyRef.right, Feature_Sold_PropertyRef.left, type);
            }
        }
    }
}

function left_move_click(isClass, type) {
    if (typeof (type) != 'undefined') {
        if (type == 'rent') {
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                navigate_left_click(isClass, Feature_Rented_PropertyRef.scroller, Feature_Rented_PropertyRef.right, Feature_Rented_PropertyRef.left);
            }
        }
        else if (type == 'list') {
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                navigate_left_click(isClass, Feature_Listed_PropertyRef.scroller, Feature_Listed_PropertyRef.right, Feature_Listed_PropertyRef.left);
            }
        }
        else if (type == 'sold') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                navigate_left_click(isClass, Feature_Sold_PropertyRef.scroller, Feature_Sold_PropertyRef.right, Feature_Sold_PropertyRef.left, type);
            }
        }
    }
}

function right_move_click(isClass, type) {
    if (typeof (type) != 'undefined') {
        if (type == 'rent') {
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                navigate_right_click(isClass, Feature_Rented_PropertyRef.scroller, Feature_Rented_PropertyRef.right, Feature_Rented_PropertyRef.left);
            }
        }
        else if (type == 'list') {
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                navigate_right_click(isClass, Feature_Listed_PropertyRef.scroller, Feature_Listed_PropertyRef.right, Feature_Listed_PropertyRef.left);
            }
        }
        else if (type == 'sold') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                navigate_right_click(isClass, Feature_Sold_PropertyRef.scroller, Feature_Sold_PropertyRef.right, Feature_Sold_PropertyRef.left, type);
            }
        }
    }
}


// Asynch version of AjaxMethods (move all global AJAX methods here eventually to improve performance)
var AjaxAsynchMethodsForFavourites = new function () {
    var url1 = "/ajaxpro/SmartModuleMyRegistration.SmartModuleFullMyFavourites,SmartModuleMyFavourites.ashx";
    //var url2 =
    var callMethod = function (name, params, url) {
        url = url || url1;
        //CR84541_mmasri: Required for offices and agents sites
        //The subSiteUrl parameter contains the base url which is required to create a siteID in the RequestContext
        if (typeof (window.officeAgentUrl) != 'undefined') {
            url = url + '?subSiteUrl=' + window.officeAgentUrl;
            if (url.substr(url.length - 1, 1) == '/') {
                url = url.substr(0, url.length - 1);
            }
        }
        var jqXHRpromise = $.ajax({ // ajax returns promise object (newer version of jQuery required)
            type: "POST",
            url: url,
            data: JSON.stringify(params),
            contentType: "application/json; charset=utf-8",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-AjaxPro-Method", name);
            }
        });
        return jqXHRpromise;
    }

    this.AddPropertyToFavourites = function (listingKey) {
        var params = { ListingKey: listingKey, MaxListings: maxFavs, CookieExpDays: window.cookieExp || window.favCookieExp, Lang: langMF, EncLang: encLangMF }
        return callMethod('AddPropertyToFavourites', params);
    }

    this.RemovePropertyFromFavourites = function (listingKey) {
        var params = { ListingKey: listingKey, CookieExpDays: window.cookieExp || window.favCookieExp }
        return callMethod('RemovePropertyFromFavourites', params);
    }

    this.IsMyFavourite = function (listingKey) {
        return callMethod('IsMyFavourite', { ListingKey: listingKey });
    }

    this.IsAtLeastOneMyFavourite = function (listingKeys) {
        return callMethod('IsAtLeastOneMyFavourite', { ListingKeys: listingKeys });
    }

    this.UpdateDataGrid = function (params) {
        return callMethod('UpdateDataGrid', params);
    }
}



// usage example: "Posted {0} days ago by {1}".replacePlaceholders(3, "Karol") will return: "Posted 3 days ago by Karol"
String.prototype.replacePlaceholders = function (vals) {
    var str = this;
    var placeholder, i = -1;
    while (true) {
        i++;
        placeholder = '{' + i + '}';
        if (str.indexOf(placeholder) == -1) {
            break;
        }
        str = str.replace(placeholder, arguments[i])
    }
    return str;
}


var longDescriptionSlideUpDownToggler = new function () {

    var process = function (params) {
        //  Description
        var charsLimit = params && !isNaN(params.charsLimit) ? params.charsLimit : 1000;
        var $container = $('#description-container');
        var $div1 = $container.find('div:first');
        var div1Len = $div1.text().length;
        if (div1Len <= charsLimit) {
            $('#see-description-container').hide();
            return;
        }

        var text = ($div1.html().substr(0, charsLimit) + '...'); //.replace(/\r\n|\r|\n/gi, "<br />");

        var $div2 = $('<div>' + text + '</div>');

        $div2.appendTo($container);
        $div1.hide();

        function toggle(expand) {
            if (expand) {
                $div1.show();
                $div2.hide();
            }
            else {
                $div1.hide();
                $div2.show();
            }
        }

        var $toggler = $('#see-description-container');

        $toggler.data('up', true).on('click', function () {
            var isUP = $toggler.data('up');
            toggle(isUP);
            // toggle text
            var $text = $toggler.find('i:first').next();
            $text.text(params.translations[isUP ? 'collapse' : 'expand']);
            // toggle css class
            $toggler.removeClass('see-less see-more').addClass(isUP ? 'see-less' : 'see-more');
            // update toggler's state
            $toggler.data('up', !isUP);
        });
    }


    this.initialize = function (params) {
        process(params);
    }
}

function PrintPage(flag) {
    if (typeof (flag) != 'undefined' && flag != '' && flag.toLowerCase() == 'true') {
        window.focus();
        setTimeout(function () { window.print(); }, 1500);
        InsertGoogleTagManagerEvent('Print Property', 'Click', 'Listing Full Print Property');
    }
    if ($("a[id$='aViewListingRegionSite']").length > 0) {
        $("a[id$='aViewListingRegionSite']").bind({
            click: function () {
                InsertGoogleTagManagerEvent('View In Regional WebSite', 'Click', 'Listing Full view listing on Regional Website');
            }
        });
    }
}

function InsertGtmPdf() {
    InsertGoogleTagManagerEvent('PDF Brochure', 'Click', 'Listing Full PDF Brochure');
}

function InsertOAGtm(category, action, label) {
    if (typeof (GTEventName) == 'undefined' || GTEventName == null)
        return;

    if ((GTEventName == 'GTOFFICE_EVENT' || GTEventName == 'GTAGENT_EVENT')) {
        if ((typeof (dataLayer) != 'undefined') && (dataLayer != null)) {
            dataLayer.push({ 'event': GTEventName, 'eventCategory': category, 'eventAction': action, 'eventLabel': label });
        }
    }
}

function InsertMRGtm(type) {
    if (typeof (CurrentMRTab) == 'undefined' || CurrentMRTab == null)
        return;

    if (CurrentMRTab == 'rec') {
        category = 'Recently Viewed Module';
        label = 'My Recently Viewed';
        actprefix = 'Recently Viewed';
    }
    else if (CurrentMRTab == 'fav') {
        category = 'Favourites Module';
        label = 'My Favourites';
        actprefix = 'Favourites';
    }
    else if (CurrentMRTab == 'con') {
        category = 'My Contact Requests Module';
        label = 'My Contact Requests';
        actprefix = 'Contact Requests';
    }

    if (type == 'listing') {
        action = actprefix + ' Listing';
        label = label + ' Listing';
    }
    else if (type == 'agent') {
        action = 'Agent Name';
        label = label + ' Agent Name Link';
    }
    else if (type == 'office') {
        action = 'Office Name';
        label = label + ' Office Name Link';
    }
    else if (type == 'send') {
        category = 'Leads';
        action = 'Send Message - ' + label;
        label = label + ' Contact Request to Agent';
    }
    else {
        return false;
    }

    InsertGoogleTagManagerEvent(category, action, label);
}

function InsertGoogleTagManagerEvent(category, action, label) {
    if (typeof (dataLayer) == 'undefined' || dataLayer == null)
        return;

    if ((typeof GTEventName != 'undefined') && (GTEventName != null)) {
        if (GTEventName != 'GTOFFICE_EVENT' && GTEventName != 'GTAGENT_EVENT') {
            dataLayer.push({ 'event': GTEventName, 'eventCategory': category, 'eventAction': action, 'eventLabel': label });
        }
    }
    else {
        dataLayer.push({ 'event': 'GT_EVENT', 'eventCategory': category, 'eventAction': action, 'eventLabel': label });
    }
}

eventsAllowed = true;
function AllowEvents(allow) {
    eventsAllowed = allow;
}

var ListingListAutoSearchTimeOut;
var timeOutInMS = 2000;
var enableAutoSearch = true;
function SetValueAutoSearch(obj, target) {
    if (eventsAllowed) {
        InsertGoogleTagManagerEvent('New Search', 'Change', 'Listing List Search Parameter Changed');
    }

    if (target == 'SortBy') {
        var selectedSortValue = obj.options[obj.selectedIndex].value;
        if (eventsAllowed) {
            InsertGoogleTagManagerEvent('Sort Order', 'Change', selectedSortValue);
            InsertOAGtm('Listings Search Results', 'Sort Order Change', selectedSortValue);
        }
    }

    if (target == 'ComRes') {
        var text = "";

        var count = $("[id$='ddlPropertyType']").length;
        for (var i = 0; i < count; i++) {
            try {
                text = $("[id$='ddlPropertyType']")[i].options[0].innerHTML;
            }
            catch (ex) {
            }
        }
        if ($("[id$='ddlPropertyType'] span").length > 0) {
            $("[id$='ddlPropertyType'] span")[0].innerText = $("[id$='ddlPropertyType'] span")[0].innerHTML = text;

        }
        $('#PropertyType').val('');
    }

    if (target == 'MLSID') {
        geoCriteriaChanged = true;
    }

    clearTimeout(ListingListAutoSearchTimeOut);
    SetValue(obj, target);
    SetTimer(target);
}

function SetStatusValueAutoSearch(obj, target, defaultVal) {
    clearTimeout(ListingListAutoSearchTimeOut);
    SetStatusValue(obj, target, defaultVal);
    SetTimer(target);
}

function AutoSearch2(target) {
    clearTimeout(ListingListAutoSearchTimeOut);
    SetTimer(target);
}

function AutoSearch() {
    clearTimeout(ListingListAutoSearchTimeOut);
    SetTimer('');
}

function SetTimer(target) {
    if (enableAutoSearch) {
        if (target != 'page') {
            $("#CurrentPage").val("1");
        }

        if (target == 'geo' && ($("#PolyGon").val() != "" || $("#RadiusMeter").val() != "")) {
            CancelShape();
        }
        ajaxSearch();
    }
}

var pendingRequest = false;
var callAlertFunction = false;

function LLSearch(criteriaChanged) {
    ajaxSearch();
};



function IsLatestSafari() {

    function get_browser_info() {
        var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return { name: 'IE ', version: (tem[1] || '') };
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\bOPR\/(\d+)/)
            if (tem != null) { return { name: 'Opera', version: tem[1] }; }
        }
        M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
        return {
            name: M[0],
            version: M[1]
        };
    }
    var safari = get_browser_info();

    return (safari.name == "Safari" && safari.version >= 8)
}

var ignoreHashChange = false;
function ajaxSearch() {

    if ((pendingRequest) && ((currentTab != "map" && currentTab != "glmap") || IsLatestSafari())) {
        return;
    }

    if ($("#currency_changed").val() == "true") {
        $("#currency_changed").val('false');
        window.location.reload();
        return;
    }

    pendingRequest = true;

    if (typeof (criteriaChanged) == "undefined" || criteriaChanged == true) {
        $("[id$='CriteriaChanged']").val('true');
    }

    var showWaitMessage = currentTab != "map" || currentTab == "map" && currentSwiftMap == null;
    if (showWaitMessage) {
        ShowWaitImg();
    };

    $.ajax({
        url: getListingSearchUrl(),

        type: "GET",
        datatype: "json",
        success: function (response) {
            HideWaitImg();
            var newHash = "#" + getListingSearchArgs();
            if (window.location.hash != newHash) {
                ignoreHashChange = true;
                window.location.hash = newHash;
            }
            if (response.error) {
                $("#ll-content-container").html(response.error);
            } else if ((currentTab != "map" && currentTab != "glmap") || currentSwiftMap == null) {
                $("#ll-content-container").html(response.llContentContainerHtml);
            }

            if ((currentTab == "map" || currentTab == "glmap") && response.mapListings) {
                mapArray = response.mapListings;
            };

            $("#h1-title-tag").html($.trim(response.h1TitleHtml));
            $("meta[name='title']").attr("content", $.trim(response.h1TitleHtml + " | " + response.siteName));
            $("meta[name='description']").attr("content", $.trim(response.descriptionHtml));


            if (response.renderTime)
                $("#debug").text("Db time: [" + response.dbTime + "] ms; Render time: [" + response.renderTime + "] ms");
            if (currentTab != "map" && currentTab != "glmap")
                showBubble();
            else {
                loadSwiftMap(response);
            }
        },
        error: function (obj, txt, ex) {
            HideWaitImg();
            $("#ll-content-container").text("error: " + txt + "; exception: " + ex);
        },
        complete: function () {
            pendingRequest = false;
            pageLoad();
            SetPersonalizationCookie();
            if (callAlertFunction == true) {
                ApplyAlert();
                callAlertFunction = false;
            }
            
        }
    });

};

function SetPersonalizationCookie() {
    var mode = getUrlParameter("mode");
    if (mode && mode == "glmap") {
        document.cookie = 'PersonalizationMap=' + window.location.hash + '; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
        document.cookie = 'PersonalizationGallery=; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
    } else {
        document.cookie = 'PersonalizationMap=; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
        if ((window.location.search.substring(1) == "" || window.location.search.substring(1).indexOf("SearchKey") > -1) && window.location.hash != "") {
            document.cookie = 'PersonalizationRegion=' + window.location.hash + '; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
        }
        else {
            document.cookie = 'PersonalizationGallery=' + window.location.search.substring(1) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
        }
    }
    var currentDate = new Date();
    document.cookie = 'PersonalizationDate=' + currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds() + ';';
}

function addSearchCriterion(arguments, name, value) {
    if (arguments.length == 0)
        return name + "=" + value;
    return arguments + "&" + name + "=" + encodeURIComponent(value);
};

function addArgFromHiddenField(args, name, selector) {
    if ($(selector).val() && $(selector).val() !== "0")
        return addSearchCriterion(args, name, $(selector).val());
    return args;
};

function getBaseURL() {
    var value = getUrlParameter("debug");
    if (value && value == "1")
        return "/handlers/listinglist.ashx?debug=1&";
    else
        return "/handlers/listinglist.ashx?";
};

function getListingSearchUrl() {
    var url = getBaseURL();
    url = url.concat(getListingSearchArgs());
    return url;
};

function getListingSearchArgs() {
    var mode = getUrlParameter("mode");
    if (mode && mode == "glmap") {
        return getGlListingSearchArgs();
    }

    if (IsLatestSafari()) {
        return getListingSearchArgs_Safari();
    }

    var args = "";
    args = addSearchCriterion(args, "mode", currentTab);
    if ($("#TransactionType").val()) {
        if ($("#TransactionType").val() == 'For Rent/Lease' || $("#TransactionType").val() == 'Holiday/Short Term Rental')
            args = addSearchCriterion(args, "tt", 260);
        else
            args = addSearchCriterion(args, "tt", 261);
    }
    args = addArgFromHiddenField(args, "mlsid", "#MLSID");
    args = addArgFromHiddenField(args, "cr", "#ComRes");
    args = addArgFromHiddenField(args, "r", "#RegionRowId");
    args = addArgFromHiddenField(args, "p", "#ProvinceId");
    if ($("#ProvinceId").val() != "0") {
        $("#MultipleProvinceId").val("0");
    }
    args = addArgFromHiddenField(args, "pm", "#MultipleProvinceId");
    args = addArgFromHiddenField(args, "c", "#CityId");
    args = addArgFromHiddenField(args, "st", "#Street");
    args = addArgFromHiddenField(args, "pt", "#PropertyType");
    args = addArgFromHiddenField(args, "min", "#MinPrice");
    args = addArgFromHiddenField(args, "max", "#MaxPrice");
    args = addArgFromHiddenField(args, "rmin", "#RentalMinPrice");
    args = addArgFromHiddenField(args, "rmax", "#RentalMaxPrice");
    var ad = $("#AvailabilityDate").val();
    if (ad)
        args = addSearchCriterion(args, "ad", ad.replace(/\//g, "-"));
    args = addArgFromHiddenField(args, "ptu", "#priceTypeUID");
    args = addArgFromHiddenField(args, "pc", "#PropertyCategory");
    args = addArgFromHiddenField(args, "msu", "#MarketStatusUID");
    args = addArgFromHiddenField(args, "d", "#Development");
    args = addArgFromHiddenField(args, "cur", "#Currency");
    args = addArgFromHiddenField(args, "b", "#MinNumOfBedrooms");
    args = addArgFromHiddenField(args, "rm", "#TotalNumOfRooms");
    args = addArgFromHiddenField(args, "f", "#FloorLevel");
    args = addArgFromHiddenField(args, "e", "#EnergyRatings");
    args = addArgFromHiddenField(args, "oa", "#chkActive");
    args = addArgFromHiddenField(args, "ooh", "#chkOpenHouse");
    args = addArgFromHiddenField(args, "oos", "#chkOnSaleOnly");
    args = addArgFromHiddenField(args, "la", "#ListingsAdded");
    args = addArgFromHiddenField(args, "ps", "#NumOfParkingSpaces");
    args = addArgFromHiddenField(args, "sq", "#SqMeter");
    args = addArgFromHiddenField(args, "sb", "#SortBy");
    args = addArgFromHiddenField(args, "page", "#CurrentPage");
    args = addArgFromHiddenField(args, "sc", "#SelectedCountryID");
    args = addArgFromHiddenField(args, "zip1", "#Zip1");
    args = addArgFromHiddenField(args, "zip2", "#Zip2");
    args = addArgFromHiddenField(args, "zip1", "#Zip3");
    args = addArgFromHiddenField(args, "poly", "#PolyGon");
    args = addArgFromHiddenField(args, "cradius", "#RadiusMeter");
    args = addArgFromHiddenField(args, "clat", "#RadiusLat");
    args = addArgFromHiddenField(args, "clng", "#RadiusLng");
    if (getLocalZoneList()) {
        args = addSearchCriterion(args, "lzl", getLocalZoneList());
    }
    if (currentTab == "map") {
        if (currentSwiftMap) {
            var bounds = currentSwiftMap.getBounds();
            if (bounds) {
                var center = bounds.getCenter();
                if (hasDrawMap && keepzoomlevel) {
                    args = addSearchCriterion(args, "lat", $("#hidLat").val());
                    args = addSearchCriterion(args, "lng", $("#hidLng").val());
                } else {
                    args = addSearchCriterion(args, "lat", center.lat());
                    args = addSearchCriterion(args, "lng", center.lng());
                }
                if (!geoCriteriaChanged) {
                    var ne = bounds.getNorthEast();
                    var sw = bounds.getSouthWest();
                    if (hasDrawMap && keepzoomlevel) {
                        args = addSearchCriterion(args, "zoom", $("#hidzoom").val());
                        args = addSearchCriterion(args, "nelat", $("#hidNeLat").val());
                        args = addSearchCriterion(args, "nelng", $("#hidNeLng").val());
                        args = addSearchCriterion(args, "swlat", $("#hidSwLat").val());
                        args = addSearchCriterion(args, "swlng", $("#hidSwLng").val());
                    } else {
                        args = addSearchCriterion(args, "zoom", currentSwiftMap.getZoom());
                        args = addSearchCriterion(args, "nelat", ne.lat());
                        args = addSearchCriterion(args, "nelng", ne.lng());
                        args = addSearchCriterion(args, "swlat", sw.lat());
                        args = addSearchCriterion(args, "swlng", sw.lng());
                        $("#hidNeLat").val(ne.lat());
                        $("#hidNeLng").val(ne.lng());
                        $("#hidSwLat").val(sw.lat());
                        $("#hidSwLng").val(sw.lng());
                        $("#hidLat").val(center.lat());
                        $("#hidLng").val(center.lng());
                        $("#hidzoom").val(currentSwiftMap.getZoom());
                    }
                }
            }
        } else {
            args = addArgFromUrl(args, "zoom");
            args = addArgFromUrl(args, "lat");
            args = addArgFromUrl(args, "lng");
            args = addArgFromUrl(args, "nelat");
            args = addArgFromUrl(args, "nelng");
            args = addArgFromUrl(args, "swlat");
            args = addArgFromUrl(args, "swlng");
        };
    };
    args = addSearchCriterion(args, "sid", currentSiteId.replace(/[\{\}]/g, ""));

    var macroOfficeId = getUrlParameter("MacroOfficeId") ? getUrlParameter("MacroOfficeId") : getUrlParameter("moid");
    var officeId = getUrlParameter("OfficeID") ? getUrlParameter("OfficeID") : getUrlParameter("oid");
    var agentId = getUrlParameter("AgentID") ? getUrlParameter("AgentID") : getUrlParameter("aid");

    if (macroOfficeId)
        args = addSearchCriterion(args, "moid", macroOfficeId);
    if (officeId)
        args = addSearchCriterion(args, "oid", officeId);
    if (agentId)
        args = addSearchCriterion(args, "aid", agentId);

    if (getUrlParameter("do") == "1") {
        args = addSearchCriterion(args, "do", getUrlParameter("do"))
    }

    return args;
};

function addSearchCriterion_Safari(arguments, name, value) {
    if (arguments.length > 0)
        searchArgs = searchArgs.concat("&");
    searchArgs = searchArgs.concat(name);
    searchArgs = searchArgs.concat("=");
    searchArgs = searchArgs.concat(value);
    return " ";
};

function addArgFromHiddenField_Safari(args, name, selector) {
    if ($(selector).val() && $(selector).val() !== "0")
        addSearchCriterion_Safari(args, name, $(selector).val());
    return " ";
};

function addArgFromUrl_Safari(args, name) {
    var urlParam = getUrlParameter(name);
    if (urlParam) {
        addSearchCriterion_Safari(args, name, urlParam);
    };
    return " ";
};

var searchArgs = "";
function getListingSearchArgs_Safari() {
    var args = "";
    searchArgs = "";

    args = addSearchCriterion_Safari(args, "mode", currentTab);

    if ($("#TransactionType").val()) {
        if ($("#TransactionType").val() == 'For Rent/Lease' || $("#TransactionType").val() == 'Holiday/Short Term Rental')
            args = addSearchCriterion_Safari(args, "tt", 260);
        else
            args = addSearchCriterion_Safari(args, "tt", 261);
    }

    args = addArgFromHiddenField_Safari(args, "mlsid", "#MLSID");
    args = addArgFromHiddenField_Safari(args, "cr", "#ComRes");
    args = addArgFromHiddenField_Safari(args, "r", "#RegionRowId");
    args = addArgFromHiddenField_Safari(args, "p", "#ProvinceId");
    if ($("#ProvinceId").val() != "0") {
        $("#MultipleProvinceId").val("0");
    }
    args = addArgFromHiddenField_Safari(args, "pm", "#MultipleProvinceId");
    args = addArgFromHiddenField_Safari(args, "c", "#CityId");
    args = addArgFromHiddenField_Safari(args, "st", "#Street");
    args = addArgFromHiddenField_Safari(args, "pt", "#PropertyType");
    args = addArgFromHiddenField_Safari(args, "min", "#MinPrice");
    args = addArgFromHiddenField_Safari(args, "max", "#MaxPrice");
    args = addArgFromHiddenField_Safari(args, "rmin", "#RentalMinPrice");
    args = addArgFromHiddenField_Safari(args, "rmax", "#RentalMaxPrice");
    var ad = $("#AvailabilityDate").val();
    if (ad)
        args = addSearchCriterion_Safari(args, "ad", ad.replace(/\//g, "-"));
    args = addArgFromHiddenField_Safari(args, "ptu", "#priceTypeUID");
    args = addArgFromHiddenField_Safari(args, "pc", "#PropertyCategory");
    args = addArgFromHiddenField_Safari(args, "msu", "#MarketStatusUID");
    args = addArgFromHiddenField_Safari(args, "d", "#Development");
    args = addArgFromHiddenField_Safari(args, "cur", "#Currency");
    args = addArgFromHiddenField_Safari(args, "b", "#MinNumOfBedrooms");
    args = addArgFromHiddenField_Safari(args, "rm", "#TotalNumOfRooms");
    args = addArgFromHiddenField_Safari(args, "f", "#FloorLevel");
    args = addArgFromHiddenField_Safari(args, "e", "#EnergyRatings");
    args = addArgFromHiddenField_Safari(args, "oa", "#chkActive");
    args = addArgFromHiddenField_Safari(args, "ooh", "#chkOpenHouse");
    args = addArgFromHiddenField_Safari(args, "oos", "#chkOnSaleOnly");
    args = addArgFromHiddenField_Safari(args, "la", "#ListingsAdded");
    args = addArgFromHiddenField_Safari(args, "ps", "#NumOfParkingSpaces");
    args = addArgFromHiddenField_Safari(args, "sq", "#SqMeter");
    args = addArgFromHiddenField_Safari(args, "sb", "#SortBy");
    args = addArgFromHiddenField_Safari(args, "page", "#CurrentPage");
    args = addArgFromHiddenField_Safari(args, "sc", "#SelectedCountryID");
    args = addArgFromHiddenField_Safari(args, "zip1", "#Zip1");
    args = addArgFromHiddenField_Safari(args, "zip2", "#Zip2");
    args = addArgFromHiddenField_Safari(args, "zip1", "#Zip3");
    args = addArgFromHiddenField_Safari(args, "poly", "#PolyGon");
    args = addArgFromHiddenField_Safari(args, "cradius", "#RadiusMeter");
    args = addArgFromHiddenField_Safari(args, "clat", "#RadiusLat");
    args = addArgFromHiddenField_Safari(args, "clng", "#RadiusLng");

    if (getLocalZoneList()) {
        args = addSearchCriterion_Safari(args, "lzl", getLocalZoneList());
    }

    if (currentTab == "map") {
        if (currentSwiftMap) {
            var bounds = currentSwiftMap.getBounds();
            if (bounds) {
                var center = bounds.getCenter();

                if (hasDrawMap && keepzoomlevel) {
                    args = addSearchCriterion_Safari(args, "lat", $("#hidLat").val());
                    args = addSearchCriterion_Safari(args, "lng", $("#hidLng").val());
                } else {
                    args = addSearchCriterion_Safari(args, "lat", center.lat());
                    args = addSearchCriterion_Safari(args, "lng", center.lng());
                }
                if (!geoCriteriaChanged) {
                    var ne = bounds.getNorthEast();
                    var sw = bounds.getSouthWest();
                    if (hasDrawMap && keepzoomlevel) {
                        args = addSearchCriterion_Safari(args, "zoom", $("#hidzoom").val());
                        args = addSearchCriterion_Safari(args, "nelat", $("#hidNeLat").val());
                        args = addSearchCriterion_Safari(args, "nelng", $("#hidNeLng").val());
                        args = addSearchCriterion_Safari(args, "swlat", $("#hidSwLat").val());
                        args = addSearchCriterion_Safari(args, "swlng", $("#hidSwLng").val());
                    } else {
                        args = addSearchCriterion_Safari(args, "zoom", currentSwiftMap.getZoom());
                        args = addSearchCriterion_Safari(args, "nelat", ne.lat());
                        args = addSearchCriterion_Safari(args, "nelng", ne.lng());
                        args = addSearchCriterion_Safari(args, "swlat", sw.lat());
                        args = addSearchCriterion_Safari(args, "swlng", sw.lng());
                        $("#hidNeLat").val(ne.lat());
                        $("#hidNeLng").val(ne.lng());
                        $("#hidSwLat").val(sw.lat());
                        $("#hidSwLng").val(sw.lng());
                        $("#hidLat").val(center.lat());
                        $("#hidLng").val(center.lng());
                        $("#hidzoom").val(currentSwiftMap.getZoom());
                    }
                }
            }
        } else {
            args = addArgFromUrl_Safari(args, "zoom");
            args = addArgFromUrl_Safari(args, "lat");
            args = addArgFromUrl_Safari(args, "lng");
            args = addArgFromUrl_Safari(args, "nelat");
            args = addArgFromUrl_Safari(args, "nelng");
            args = addArgFromUrl_Safari(args, "swlat");
            args = addArgFromUrl_Safari(args, "swlng");
        };
    };

    args = addSearchCriterion_Safari(args, "sid", currentSiteId.replace(/[\{\}]/g, ""));

    var macroOfficeId = getUrlParameter("MacroOfficeId") ? getUrlParameter("MacroOfficeId") : getUrlParameter("moid");
    var officeId = getUrlParameter("OfficeID") ? getUrlParameter("OfficeID") : getUrlParameter("oid");
    var agentId = getUrlParameter("AgentID") ? getUrlParameter("AgentID") : getUrlParameter("aid");

    if (macroOfficeId)
        args = addSearchCriterion_Safari(args, "moid", macroOfficeId);
    if (officeId)
        args = addSearchCriterion_Safari(args, "oid", officeId);
    if (agentId)
        args = addSearchCriterion_Safari(args, "aid", agentId);

    if (getUrlParameter("do") == "1") {
        args = addSearchCriterion(args, "do", getUrlParameter("do"))
    }

    return searchArgs;
};


function getLocalZoneList() {
    var checkedValues = $('input[name="LocalZoneID"]:checked').map(function () {
        return this.value;
    }).get().join('|');
    return checkedValues;
};


function addArgFromUrl(args, name) {
    var urlParam = getUrlParameter(name);
    if (urlParam) {
        args = addSearchCriterion(args, name, urlParam);
    };
    return args;
};

function LLSorty(value) {
    $("[id$='SortBy']").val(value);
    LLSearch(false);
}

function getUrlParameter(paramName) {

    function extractParameter(paramName, source) {
        var splitted = source.split('&');
        for (var i = 0; i < splitted.length; i++) {
            var item = splitted[i].split('=');
            if (item[0] == paramName) {
                return item[1];
            }
        }
    };

    function getHashParameter(paramName) {
        var hash = window.location.hash.substring(1);
        return extractParameter(paramName, hash);
    };

    var pageUrl = window.location.search.substring(1);
    var result = extractParameter(paramName, pageUrl);
    if (result) return result;

    return getHashParameter(paramName);
};

var prevTab = null;
var currentTab = null;
var firstMapLoad = true;

function LLChangeView(tab, doNotSearch) {
    function toggleMapLayout(previousTab, currentTab) {
        if ((previousTab == "map" || currentTab == "map") || (previousTab == "glmap" || currentTab == "glmap")) {
            $(".myremax_column").toggle();
            $(".sort-mode-changer").toggle();
        }
        prevTab = previousTab
    };

    if (pendingRequest || currentTab == tab) return;
    doNotSearch = typeof (doNotSearch) == 'boolean' ? doNotSearch : false;
    $("#divGalleryView").removeClass('tab current').addClass('tab');
    $("#divListView").removeClass('tab current').addClass('tab');
    $("[id$=divMapView]").removeClass('tab current').addClass('tab');
    $(".gallery-tab-active").removeClass('gallery-tab-active').addClass('gallery-tab');
    $(".list-tab-active").removeClass('list-tab-active').addClass('list-tab');
    $(".map-tab-active").removeClass('map-tab-active').addClass('map-tab');

    toggleMapLayout(tab, currentTab);

    currentTab = tab;

    if (currentTab == "gallery") {
        $("#divGalleryView").removeClass('tab').addClass('tab current');
        $(".gallery-tab").removeClass('gallery-tab').addClass('gallery-tab-active');
        $(".listinglist-container").removeClass('map-view');
        $(".search-filters").removeClass('search-filters-map-view');
        $(".results-container ").removeClass('results-container-map-view');
        currentSwiftMap = null;
        if (hasDrawMap) {
            hasSwitchedTab = true;
            resetMarker = true;
            keepzoomlevel = true;
        } else {
            CancelShape();
        }
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Toggle View', 'Gallery View');
        }
        $("#leadAdsListingSearchResultsFullBanner").css('display', 'block');
    } else if (currentTab == "list") {
        $("#divListView").removeClass('tab').addClass('tab current');
        $(".list-tab").removeClass('list-tab').addClass('list-tab-active');
        $(".listinglist-container").removeClass('map-view');
        $(".search-filters").removeClass('search-filters-map-view');
        $(".results-container ").removeClass('results-container-map-view');
        currentSwiftMap = null;
        if (hasDrawMap) {
            hasSwitchedTab = true;
            resetMarker = true;
            keepzoomlevel = true;
        } else {
            CancelShape();
        }
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Toggle View', 'List View');
        }
        $("#leadAdsListingSearchResultsFullBanner").css('display', 'block');
    } else if (currentTab == "map" || currentTab == "glmap") {
        firstMapLoad = true;
        $("[id$=divMapView]").removeClass('tab').addClass('tab current');
        $(".map-tab").removeClass('map-tab').addClass('map-tab-active');
        if (currentTab == "map") {
            $(".listinglist-container").addClass('map-view');
            $(".search-filters").addClass('search-filters-map-view');
            $(".results-container ").addClass('results-container-map-view');
        }
        if (eventsAllowed) {
            InsertOAGtm('Listings Search Results', 'Toggle View', 'Map View');
        }
        if (hasDrawMap) {
            $("#map-draw-area").css('display', 'block');
        }
        $("#leadAdsListingSearchResultsFullBanner").css('display', 'none');
    }

    if (eventsAllowed) {
        InsertGoogleTagManagerEvent('Listing List View Change', 'Change', tab);
    }

    if (!doNotSearch) {
        //LLSearch(false);
        ajaxSearch();
    }
};

function isValid() {
    var isPageValid = false;
    //had to suppress the messagebox  before I call the Page_ClientValidate method. If not  would  happen twice.   
    if (Page_ValidationSummaries && Page_ValidationSummaries[0] && Page_ValidationSummaries[0].showmessagebox) {
        var showMessagesOption = Page_ValidationSummaries[0].showmessagebox;
        Page_ValidationSummaries[0].showmessagebox = "false";
        isPageValid = Page_ClientValidate();
        Page_ValidationSummaries[0].showmessagebox = showMessagesOption; //set it  back to orignal  way
    }
    return isPageValid;
}

var contactSource = "";
function SendContact(obj, type, triggerCaptchaSubmitted) {

    if (!isValid()) { $("#divProfileContact [id*='btnClientSideSubmit_smartmoduleprofilecontact']").removeAttr("disabled"); }

    if (obj.toLowerCase() == "profile") {
        contactSource = "profile";
        if (Page_ClientValidate("ProfileContact")) {
            if ($("[id$='txtComments2']").val() != '') {
                return false;
            }
            var response = null;
            var FromEmail = PstrFromEmail;
            var FromName = PstrFromName;

            var RegionID = PRegionID;
            var Subject = PSubject;
            var ToEmail = PstrToEmail;
            var ToName = PstrToName;
            var CCEmail = PstrCCEmail;
            var CCName = PstrCCName;
            var BCCEmail = PstrBCCEmail;
            var BCCName = PstrBCCName;
            var HitsOfficeID = PHitsOfficeID;
            var submittedForAgentID = PsubmittedForAgentID;
            var AgentIDToSaveAgenda = PAgentIDToSaveAgenda;
            var salutation = "";
            var firstName = "";
            var lastName = "";
            if ($("[id$='txtName']").val() != "") {
                lastName = $("[id$='txtName']").val();
            } else {
                salutation = $("[id$='ddlTitle'] select").text();
                firstName = $("[id$='txtFirstName']").val();
                lastName = $("[id$='txtLastName']").val();
            }
            var phone = $("[id$='txtPhone']").val();
            var request = $("[id$='txtRequest']").val();
            var email = $("[id$='txtEmailAddress']").val();
            var street = $("[id$='txtStreet']").val();
            var city = $("[id$='txtCity']").val();
            var postalCode = $("[id$='txtPostalCode']").val();
            var HostURL = PHostURL;
            var EmailBody = PstrEmailTitle;
            if ($("[id$='txtEmailAddress']").val() != "") {
                EmailBody = EmailBody + PstrEmailAddressLabel + $("[id$='txtEmailAddress']").val() + "<br>"
            }
            if ($("[id$='txtName']").val() != "") {
                EmailBody = EmailBody + PstrEmailNameLabel + $("[id$='txtName']").val() + "<br>"
            }
            if ($("[id$='txtFirstName']").val() != "") {
                EmailBody = EmailBody + PstrEmailNameLabel + $("[id$='ddlTitle'] select").text() + " " + $("[id$='txtFirstName']").val() + " " + $("[id$='txtLastName']").val() + "<br>"
            }
            if ($("[id$='txtPhone']").val() != "") {
                EmailBody = EmailBody + PstrEmailPhoneLabel + $("[id$='txtPhone']").val() + "<br>"
            }
            if ($("[id$='txtStreet']").val() != "") {
                EmailBody = EmailBody + PstrEmailStreetLabel + $("[id$='txtStreet']").val() + "<br>"
            }
            if ($("[id$='txtCity']").val() != "") {
                EmailBody = EmailBody + PstrEmailCityLabel + $("[id$='txtCity']").val() + "<br>"
            }
            if ($("[id$='txtPostalCode']").val() != "") {
                EmailBody = EmailBody + PstrEmailPostalCodeLabel + $("[id$='txtPostalCode']").val() + "<br>"
            }
            if ($("[id$='txtRequest']").val() != "") {
                EmailBody = EmailBody + PstrEmailCommentsLabel + "<br>" + "------------------" + "<br>" + $("[id$='txtRequest']").val() + "<br>"
            }

            var GTfltID = "";
            var GTfltValue = "";
            if ($("[id^=GTSPMFLT_]").length > 0) {
                GTfltID = $("[id^=GTSPMFLT_]").attr("id");
                if ($("[id^=GTSPMFLT_]").val() != null) {
                    GTfltValue = $("[id^=GTSPMFLT_]").val();
                }
            }
            resetMinMaxPrice
            var listingKey = "";
            var listingID = 0;
            var curSiteId = PSiteId;

            if (typeof (type) != 'undefined' && type != '' && typeof (triggerCaptchaSubmitted) == 'undefined') {
                if (type == 'agent') {
                    if (typeof (GTMCampaign) != 'undefined' && GTMCampaign == "true") {
                        InsertGoogleTagManagerEvent('Agent Profile - Campaign ', 'Contact Agent', 'Send Message');
                    }
                    InsertGoogleTagManagerEvent('Send us a message ', 'onclick', 'AgentProfile-ContactRequest');
                    InsertOAGtm('Agent Profile', 'Leads', 'Send');
                }
                else if (type == 'office') {
                    if (typeof (GTMCampaign) != 'undefined' && GTMCampaign == "true") {
                        InsertGoogleTagManagerEvent('Office Profile - Campaign ', 'Contact Us', 'Send Message');
                    }
                    InsertGoogleTagManagerEvent('Send us a message ', 'onclick', 'OfficeProfile-ContactRequest');
                    InsertOAGtm('Office Profile', 'Leads', 'Send');
                }
            }

            $("#divProfileContact [id*='btnClientSideSubmit_smartmoduleprofilecontact']").attr("disabled", "disabled");
            //if (triggerCaptchaSubmitted !== true)
            //    triggerCaptchaSubmitted = false;
            //else {
            //    $("#captcha-container").find("input[type=submit]").attr("disabled", "disabled");
            //}


            triggerCaptchaSubmitted = true;

            SmartModuleProfileContactService.instance().submitContact(FromEmail, FromName, EmailBody, RegionID, Subject,
                ToEmail, ToName, CCEmail, CCName, BCCEmail, BCCName, HitsOfficeID, submittedForAgentID,
                AgentIDToSaveAgenda, firstName, lastName, phone, request, email, HostURL, listingKey, listingID,
                curSiteId, GTfltID, GTfltValue, salutation, street, city, postalCode, triggerCaptchaSubmitted,
                "", smartmoduleprofilecontactVm.captcha_response_token).done(function (data) {
                var dataSuccess = ServiceBase.getResponseValueObj(data);

                OnSuccess(dataSuccess);
            }).fail(function (xhr) { });
        }

    }
    else if (obj.toLowerCase() == "listingfull") {
        contactSource = "listingfull"
        if (Page_ClientValidate("ListingFullContact")) {
            $("#divLoading").show();
            var response = null;
            var FromEmail = $("[id$='txtEmail']").val(); //PstrFromEmail;
            var FromName = $("[id$='txtFullName']").val();//we are using fullname

            var RegionID = PRegionID;
            var Subject = PSubject;
            var ToEmail = PstrToEmail;
            var ToName = PstrToName;
            var CCEmail = PstrCCEmail;
            var CCName = PstrCCName;
            var BCCEmail = PstrBCCEmail;
            var BCCName = PstrBCCName;
            var HitsOfficeID = PHitsOfficeID;
            var submittedForAgentID = PsubmittedForAgentID;
            var AgentIDToSaveAgenda = PAgentIDToSaveAgenda;
            //using fullname here and set the lastname =fullname, no firstname from the form.
            var firstName = "";
            var lastName = $("[id$='txtFullName']").val();
            var request = $("[id$='txtMessage']").val();
            var email = $("[id$='txtEmail']").val();

            var phone = $("[id$='txtPhone']").val();
            var HostURL = PHostURL;
            var EmailBody = PstrEmailTitle;
            if ($("[id$='txtEmailAddress']").val() != "") {
                EmailBody = EmailBody + PstrEmailAddressLabel + $("[id$='txtEmail']").val() + "<br>"
            }
            if ($("[id$='txtFullName']").val() != "") {
                EmailBody = EmailBody + PstrEmailNameLabel + $("[id$='txtFullName']").val() + "<br>"
            }
            if ($("[id$='txtPhone']").val() != "") {
                EmailBody = EmailBody + PstrEmailPhoneLabel + $("[id$='txtPhone']").val() + "<br>"
            }
            if ($("[id$='txtMessage']").val() != "") {
                EmailBody = EmailBody + PstrEmailCommentsLabel + "<br>" + "------------------" + "<br>" + $("[id$='txtMessage']").val() + "<br>"
            }

            var extraEmailBody = PstrExtraEmailBody;

            EmailBody = EmailBody + PstrExtraEmailBody;
            var listingKey = PstrListingKey;
            var listingID = PstrListingID;
            var curSiteId = PSiteId;

            SmartModuleProfileContactService.instance().sendProfileContactEmail(FromEmail, FromName, EmailBody, RegionID, Subject, ToEmail, ToName, CCEmail, CCName, BCCEmail, BCCName, HitsOfficeID, submittedForAgentID, AgentIDToSaveAgenda, firstName, lastName, phone, request, email, HostURL, listingKey, listingID, curSiteId).done(function (data) {
                var dataSuccess = ServiceBase.getResponseValueObj(data);

                OnSuccess(dataSuccess);
            }).fail(function (xhr) { });
        }

    }

}

function OnSuccess(e) {
    var response = JSON.parse(e.value);
    if (response.captchaVisible) {
        $("#captcha-container").html(response.html);
    }
    if (response.captcha != undefined) {
        alert(response.captcha);
        $("#divProfileContact [id*='btnClientSideSubmit_smartmoduleprofilecontact']").removeAttr("disabled");
    }
    else {
        $("#captcha-container").empty();
        if (response.status == true) {
            if (contactSource == "profile") {
                $("#divProfileEmailSuccessMessage").css("display", "");
                $("#divProfileContact").css("display", "none");
                $("#divProfileContact [id*='btnSave']").removeAttr("disabled");
            }
            else if (contactSource == "listingfull") {
                $("#divLoading").hide();
                $("#divListingFullContact").css("display", "none");
                $("#divListingFullContactThankYou").css("display", "");
            }
        }
        else {
            if (contactSource == "profile") {
                $("#divProfileContact [id*='btnClientSideSubmit_smartmoduleprofilecontact']").removeAttr("disabled");
            }
        }
    }
};
function OnFailed() {
};


//START LOADING DIV
var ShowLoadImg = true;
var waitingDiv = null;

function SetLoadingDiv(srcDiv) {

    if (srcDiv != null) {
        waitingDiv = srcDiv;
    }

}

function ShowWaitImg() {
    if (ShowLoadImg && (waitingDiv != null)) {
        var screenWidth;
        var screenHeight;
        if ((window.screen.width - 10) > 0) {
            screenWidth = (window.screen.width - 10);
        }

        if ((window.screen.height - 210) > 0) {
            screenHeight = (window.screen.height - 210);
        }

        waitingDiv.style.width = document.documentElement.clientWidth;
        waitingDiv.style.height = document.documentElement.clientHeight;
        waitingDiv.style.display = "block";

    }
}

function HideWaitImg() {
    if (waitingDiv != null) {
        waitingDiv.style.display = "none";
    }
}
//END OF LOADING DIV

function ToggleOptions() {
    $("#toggleExtendedOptions").toggle();
}

function ShowMoreOptions() {
    $("[id$='divMoreOptions']").css('display', '');
    $("[id$='divLess']").css('display', '');
    $("[id$='divMore']").css('display', 'none');
}

function ShowLessOptions() {
    $("[id$='divMore']").css('display', '');
    $("[id$='divLess']").css('display', 'none');
    $("[id$='divMoreOptions']").css('display', 'none');
}

function HideMoreOrLessOptions() {
    $("[id$='divMoreOptions']").css('display', 'none');
    $("[id$='divMore']").css('display', 'none');
    $("[id$='divLess']").css('display', 'none');
}

function ShowContactRequestInfo(id) {
    var divShowId = "#" + "divShow_" + id;
    var divCollapseId = "#" + "divCollaps_" + id;
    $(divShowId).css('display', 'none');
    $(divCollapseId).css('display', '');
}

function HideContactRequestInfo(id) {
    var divShowId = "#" + "divShow_" + id;
    var divCollapseId = "#" + "divCollaps_" + id;
    $(divShowId).css('display', '');
    $(divCollapseId).css('display', 'none');
}
//set searching mlsid to hidden field
function SetListingListSearchMLSID() {

    var mlsid = $("[id$='txtMLSID']").val();
    if (mlsid != null && mlsid != emptyMLSIDSearchTrans && mlsid != "") {
        $('#MLSID').val(mlsid);
        $("[id$='CriteriaChanged']").val('true');
    }
}


function showQSBackImages(imgarray) {
    var thediv = $(".panorama-div");
    if (imgarray.length == 1) {
        thediv.css("background-image", "url('" + imgarray[0] + "')");
    }
    else if (imgarray.length > 1) {
        var spot = Math.floor(Math.random() * imgarray.length);
        thediv.css("background-image", "url('" + imgarray[spot] + "')");
    }
}

function resetMinMaxPrice(obj) {
    if (defaultMinMaxPrice(obj)) return;
    else if ($("[id$='" + obj + "'] span").length > 0) {
        $("[id$='" + obj + "'] span")[0].innerHTML = $("[id$='" + obj + "'] select option[value='-1']").text();
    }
}

function defaultMinMaxPrice(obj) {
    var flag = false;
    var regionID = getRegionID();

    if (regionID === "24" && $("[id$='" + obj + "'] option[value='5000']").length > 0) {
        $('#' + obj).val('5000');
        flag = true;
    }
    return flag;
}

//variable with regionid will change from page to page
function getRegionID() {
    if (typeof freeTextRegionID !== 'undefined' && freeTextRegionID !== '') {
        return freeTextRegionID;
    } else if (typeof RegionId !== 'undefined' && RegionId !== '') {
        return RegionId;
    } else if (typeof formatRegionId !== 'undefined' && formatRegionId !== '') {
        return formatRegionId;
    } else if (typeof siteRegionID !== 'undefined' && siteRegionID !== '') {
        return siteRegionID;
    } else {
        return "";
    }
}


var lFull_image_cont_height;
var lFull_Image_useWeb = false;
var navTopOffset = 0;
var windowWidth = 0;
var containerWidth = 0;
var thumbWidth = 215; //$("[id$='thumb-container']").width();    //when jquery gets the size, it's not the right info
var imageWidthSetByBrowser = 0;
var imageHeightSetByBrowser = 0;
var webImageWidth = 0;
var breadCrumbsHeight = 0;
var gmapStreetViewHeight = 0;
function lFull_AdjustImageSize() {
    if (typeof (isForPrint) != "undefined" && isForPrint != null && isForPrint == false) {
        windowWidth = $(window).width();
        containerWidth = $("div .maincontent_cell").width();

        var windowHeight = $(window).height();

        var headerHeight = $(".tr1td1").height();
        // If null then global site
        if (headerHeight == null) {
            headerHeight = $("#mast").height();
        }

        breadCrumbsHeight = $(".listfull-nav-div row").height();
        //150 is the value of the height from the bottom of the image to still have the agent image visible
        var bottomHeightToShowAgentDetail = 150;
        lFull_image_cont_height = parseInt(windowHeight - headerHeight - bottomHeightToShowAgentDetail);

        if ($("div .gallery_container_large").length > 0) {
            if (windowHeight < 900) {
                lFull_Image_useWeb = true;
                $("div .gallery_container_large").css('display', 'none');
            }
            else {
                $("[id$='gallery_container']").css('display', 'none');
            }
            showPlayOverlay(false);

            if (lFull_image_cont_height <= 375 || lFull_Image_useWeb) {
                lFull_image_cont_height = 375;
            }

            if (lFull_image_cont_height > 705 + breadCrumbsHeight && !lFull_Image_useWeb) {
                lFull_image_cont_height = 705 + breadCrumbsHeight;
            }
        }
        else {
            lFull_image_cont_height = 477.578125;
            lFull_Image_useWeb = true;
        }

        if (lFull_Image_useWeb) {
            $("[id$='gallery-map-container']").attr('class', 'gallery-map-container row');
            $("[id$='main_photo_container']").attr('class', 'main-photo-container row');
        }
        else {
            $("[id$='gallery-map-container']").attr('class', 'gallery-map-container-large row');
            $("[id$='main_photo_container']").attr('class', 'main-photo-container-large row');
        }
        LFull_SetContainerHeightNotPhoto();
    }
}


function LFull_SetContainerHeightNotPhoto(className) {
    if (typeof (className) == "undefined" || className == "photo") {
        navTopOffset = $("[id$='listfull_nav']").height();
    }
    if (lFull_Image_useWeb) {
        imageWidthSetByBrowser = 500;
        imageHeightSetByBrowser = 375;
        LFull_SetContainerHeight_Web();
    }
    else {
        imageWidthSetByBrowser = 1000;
        imageHeightSetByBrowser = 750;
        LFull_SetContainerHeight_Large_BasedOnWidth();
    }
}

function LFull_SetContainerHeight_Web() {
    var scrollerOffset = 20;
    var maxWidth = containerWidth - thumbWidth;
    var scrollerCalcHeight = lFull_image_cont_height - scrollerOffset;
    gmapStreetViewHeight = scrollerCalcHeight + 10;

    $("[id$='gallery_container']").css('height', parseInt(scrollerCalcHeight + 8)); //8 came from css paddings

    //CR#84488_mmasri: Check if there is one image only then the it should be centered by setting the width to 100%
    if ($('.gallery_container_small .webImage').length == '1') {
        $("[id$='gallery_container']").css('width', '100%');
        $(".slideshow-overlay").css('width', '100%');
        $(".gallery_container_small").css('width', '100%');
    }
    else {
        $("[id$='gallery_container']").css('width', parseInt(maxWidth));
    }

    $("[id$='gallery_container']").css('overflow', 'hidden');

    webImageWidth = maxWidth / 2;
    $(".webImage").css('width', parseInt(webImageWidth));
    $(".webImage").css('height', parseInt(scrollerCalcHeight));

    $("[id$='thumb-scroller']").css('height', parseInt(scrollerCalcHeight + 3));//3 came from css paddings

    if ($("[u$='thumbnavigator']").height() > 200) {
        $("[id$='gallery-map-streetview']").css('height', parseInt(scrollerCalcHeight + 10));
        $("[id$='gallery-map-map']").css('height', parseInt(scrollerCalcHeight + 10));
    }
    else
    {
        $("[id$='gallery-map-streetview']").css('height', parseInt(scrollerCalcHeight + 153.333));
        $("[id$='gallery-map-map']").css('height', parseInt(scrollerCalcHeight + 153.333));
    }
}

function LFull_SetContainerHeight_Large_BasedOnWidth() {
    $("div .gallery_container_large").css('height', lFull_image_cont_height - breadCrumbsHeight);
    $("[id$='slideshow_btn_large']").css('height', lFull_image_cont_height - breadCrumbsHeight);

    var mapContainerHeight = lFull_image_cont_height - navTopOffset;
    $("[id$='gallery-map-container']").css('height', mapContainerHeight);
    $("[id$='gallery-map-map']").css('height', mapContainerHeight);


    var bottomOffset = 102;
    var thumbScrollerHeight = lFull_image_cont_height - bottomOffset;
    $("[id$='thumb-scroller']").css('height', thumbScrollerHeight);


    var newImageWidth = containerWidth - thumbWidth;
    if (windowWidth < containerWidth || containerWidth <= 940) {
        //container Width has scrollbar
        newImageWidth = 720;
    }

    var ratioImageWidth = newImageWidth / imageWidthSetByBrowser;
    var newImageHeight = parseInt(imageHeightSetByBrowser * ratioImageWidth);
    var imgTopOffset = parseInt((newImageHeight - (lFull_image_cont_height - breadCrumbsHeight)) / 2) * -1;

    $("[id$='SLIDESIMG']").css('height', newImageHeight);
    $("[id$='SLIDESIMG']").css('width', newImageWidth);
    $("[id$='SLIDESIMG']").css('top', imgTopOffset);
}

function SetPageForPrint() {
    $("a").attr("href", "javascript:void('0');");
    $("a").attr("target", "");
    $("button").attr("disabled", "disabled");
    $("select").attr("disabled", "disabled");
}

function showPlayOverlay(show) {
    if (show) {
        $("[id$='slideshow-overlay-container']").show();
    }
    else {
        $("[id$='slideshow-overlay-container']").hide();
    }
}

function SubmitOnEnter(controlID, submitBtnID) {
    $("[id$='" + controlID + "']").on('keyup', function (e) {
        if (e.which == 13 || e.keyCode == 13) {
            $("[id$='" + submitBtnID + "']").click();
        }
    });
}
function HideContactPopup(element, control) {
    $(control).css('display', 'none');
    $(element).find('.chevron-up').removeClass('chevron-up').addClass('chevron-down');
    $(element).css('position', '');
    $(element).css('z-index', '');
    
    $("#blackout").css('display', 'none');

    if ($(element).attr('id') == 'link_toolbar_contact_top' || $(element).attr('id') == 'link_toolbar_contact_bottom') {
        $('#listfull_contact_top').css('z-index', '4');
    }

    $('#blackout').off('click', false); //explicity  unbind  so that the  hide  is  never  fired  accidentally.
}

function OpenContactMe(element, control) {
    $("#listfull_contact_top").removeClass('hidden-xs');
    if ($(control).css('display') == 'none') {
        $(control).css('display', 'block');
        $(element).find('.chevron-down').removeClass('chevron-down').addClass('chevron-up');
        $(element).css('position', 'relative');
        $(element).css('z-index', '4');
        
        $("#blackout").css('display', 'block');

        if ($(element).attr('id') == 'link_toolbar_contact_top' || $(element).attr('id') == 'link_toolbar_contact_bottom') {
            $('#listfull_contact_top').css('z-index', '3');
        }

        if ($('#blackout').css('display') == 'block') {
            $('#blackout').on('click', function (e) {
                HideContactPopup(element, control);
                $('#allContent').css('display', 'block');
                $('#AlertBox').css('display', 'none');
                $('#AlertBoxMessage2').css('display', 'none');
                $("#listfull_contact_top").addClass('hidden-xs');
            });
        }
    }
    else {
        HideContactPopup(element, control);
    }
}

function OpenProfileContactMe(element, slidediv) {
    if ($("#blackout").css('display') == 'none') {
        $(window).scrollTop(0);
        $("#blackout").css('display', 'block');
        $(element).css('z-index', '99');
        $(slidediv).slideUp('slow');
    }
    else {
        $(element).css('z-index', '');
        $(slidediv).slideDown('slow');
        $("#blackout").css('display', 'none');
        $('#blackout').off('click', false);
    }
}

function OpenFavOrRecentPopup(element) {
    if ($("#blackout").css('display') == 'none') {
        $("#blackout").css('display', 'block');

        $(element).show();
        $(element).css('z-index', '4');

        if ($('#blackout').css('display') == 'block') {
            $('#blackout').on('click', function (e) {
                HideFavOrRecentPopup(element);
            });
        }
    }
    else {
        HideFavOrRecentPopup(element);
    }
}

function HideFavOrRecentPopup(element) {
    $(element).hide();
    $(element).css('z-index', '');

    $("#blackout").css('display', 'none');
    $('#blackout').off('click', false); //explicity  unbind  so that the  hide  is  never  fired  accidentally.
}

/*Photo swipe on Listing full*/
function GoToLFullPageSlides() {
    (function (window, PhotoSwipe) {
        var options = {
            captionAndToolbarOpacity: 1,
            captionAndToolbarAutoHideDelay: 0,
            autoStartSlideshow: true,
            allowUserZoom: false,
            enableDrag: false,
            doubleTapSpeed: 500
        },
            instance = PhotoSwipe.attach(window.document.querySelectorAll('ul.gallery a'), options);
        instance.show(0);

        $(".ps-uilayer").click(function () {
            instance.hide();
        });

        $(".ps-caption").css('display', 'block');
    }(window, window.Code.PhotoSwipe));
}

this.showBubble = function () {
    $(".development-on").mouseenter(function (e) {
        var $dev_name = $(this).attr("developname");
        var $dev_short_name = $(this).attr("developshortname");
        var $dev_img = $(this).attr("developimg");
        var $dev_lnk = $(this).attr("developlink");

        $(this).append('<div class="tooltip_bubble">'

            + '<table  border="0" cellspacing="0" cellpadding="0" style="height:55px; width: 100%;">'
            + '<tr><td>'
            + '<a target="_blank" href="' + $dev_lnk + '"><img width="70" height="50" src="' + $dev_img + '" alt="' + $dev_short_name + '"/></a>'
            + '</td>'
            + '<td class="development_lbl">'
                + '<a target="_blank" href="' + $dev_lnk + '">&nbsp;<span title="' + $dev_name + '">' + $dev_short_name + '</span>&nbsp;<img border="0" src="/common/images/arrow_listfull_group.gif" alt="" /></a>'
            + '</td></tr></table>'

            + '</div>');
        var position = $(this).position();
        var bubbleleft = position.left;
        var bubbletop = position.top + 30;
        $(".development-on > div.tooltip_bubble").css("top", "" + bubbletop + "px");

        $(".development-on > div.tooltip_bubble").css("left", "" + bubbleleft + "px");
        //$(".development-off > div.tooltip_bubble").position($(this).position());
        $(".development-on > div.tooltip_bubble").fadeIn(300);
    });

    $(".development-on").mouseleave(function () {
        $(".development-on > div.tooltip_bubble").fadeOut(300).delay(300).queue(function () {
            $(this).remove();
            $(this).dequeue();
        });
    });

}

function OpenListingGalleryMap(MapID, lat, lng) {
    var curItem = $("[id$='" + MapID + "']").parent();
    var curPhoto = $(curItem).children(".gallery-photo");
    if ($(curPhoto).css("display") == null || $(curPhoto).css("display").toLowerCase().indexOf("block") > -1) {
        $(curPhoto).css("display", "none");

        $("[id$='" + MapID + "']").css("display", "block");
        $(curItem).find('[id$="liMap"]').attr("class", "photo");

        var mapClientID = $("[id$='" + MapID + "']").attr('id');

        var opts = {
            infoWindowContent: "",
            infoWindowOnMarkerClick: false,
            zoom: 13,
            addressToSetZoomOn: "",
            marker: {
                icon: "/common/images/GoogleMaps/pointer_1.png",
                shadow: "/common/images/GoogleMaps/shadow_1.png",
                title: ""
            },
            disabled: true
        }

        maps.GoogleVer3['initialize'](mapClientID, lat, lng, opts);

        InsertGoogleTagManagerEvent('Map Result', 'Click', 'Gallery Map');

    }
    else {
        $("[id$='" + MapID + "']").css("display", "none");
        $(curPhoto).css("display", "block");
        $(curItem).find('[id$="liMap"]').attr("class", "map");

    }

}

function OpenListingListMap(MapID, lat, lng) {

    var curPopup = $("[id$='" + MapID + "']").parent();
    if ($(curPopup).css("display") == "none") {
        InsertGoogleTagManagerEvent('Map Result', 'Click', 'Listing List Map');
    }

    $(curPopup).css("display", "block");

    var imgid = "img0";

    if (MapID.match(/Map[\w]+/g) != null) {
        imgid = MapID.match(/Map[\w]+/g).toLocaleString().replace("Map", "img");
    }
    var position = $("[id$='" + imgid + "']").position(); //img position


    $("[id$='" + MapID + "']").css("display", "block");

    var mapClientID = $("[id$='" + MapID + "']").attr('id');

    var opts = {
        infoWindowContent: "",
        infoWindowOnMarkerClick: false,
        zoom: 13,
        addressToSetZoomOn: "",
        marker: {
            icon: ResidentialMarkerIconPath,
            shadow: ResidentialMarkerShadowPath,
            title: ""
        },
        disabled: true
    }

    maps.GoogleVer3['initialize'](mapClientID, lat, lng, opts);
    $(curPopup).css('z-index', '300000');
    if ($("[id$='hiddenRTL']").val().toLowerCase() == "false") {

        $(curPopup).css(position); //put map to the img postion
    }
    else {

        position.left = position.left - 350;

        $(curPopup).css(position);

    }
    $("#blackout").css('display', 'block');
    $('#blackout').on('click', function (e) {
        HideListingListMap(MapID);
    });
}
function HideListingListMap(MapID) {
    var curPopup = $("[id$='" + MapID + "']").parent();
    $("#blackout").css('display', 'none');
    $('#blackout').off('click', false);
    $(curPopup).css('display', 'none');
}

function ListingListFavOnMap(id) {
    var favonmapprefix = "liFavOnMap_";
    var favprefix = "divFav_"
    var favonmapid = null;
    var favid = null;

    if (id.match(/liFavOnMap_[\w-]+/g) != null) {
        favid = id.match(/liFavOnMap_[\w-]+/g).toLocaleString().replace(favonmapprefix, favprefix);
    }

    $("[id$='" + favid + "']").click();
}


function RecentlyTransactedProperty(control, isRTL) {
    if ($(control).length > 0) {
        //var width = $(control).width() - 20;
        //if ((width > 535) || (width <= 0)) {
        //    width = 535;
        //}
        var width = "100%";

        $(control).addClass('box-generic')
        // to fix  page scaling
        if ($("[id$='divRecentlySoldProperties']").length > 0) {
            // $("[id$='divRecentlySoldProperties']").width(width + 85);
        }
        if ($("[id$='divRecentlyRentedProperties']").length > 0) {
            //  $("[id$='divRecentlyRentedProperties']").width(width + 85);
        }
        if ($("[id$='divRecentlyListedProperties']").length > 0) {
            // $("[id$='divRecentlyListedProperties']").width(width + 85);
        }
        ///control width - multiple  insertion scenario
        if ($("[id$='divScroller']").length > 0) {
            $("[id$='divScroller']").width(width);
            $("[id$='divRecentlySoldPropertiesOnReady']").show();
        }
        if ($("[id$='divRentScroller']").length > 0) {
            $("[id$='divRentScroller']").width(width);
            $("[id$='divRecentlyRentedPropertiesOnReady']").show();
        }
        if ($("[id$='divListScroller']").length > 0) {
            $("[id$='divListScroller']").width(width);
            $("[id$='divRecentlyListedPropertiesOnReady']").show();
        }

        if (isRTL == '0') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                $('#' + Feature_Sold_PropertyRef.right).attr("class", "chevron-left-grey");
            }
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                $('#' + Feature_Rented_PropertyRef.right).attr("class", "chevron-left-grey");
            }
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                $('#' + Feature_Listed_PropertyRef.right).attr("class", "chevron-left-grey");
            }
        }
        else if (isRTL == '1') {
            if (typeof (Feature_Sold_PropertyRef) != 'undefined') {
                $('#' + Feature_Sold_PropertyRef.left).attr("class", "chevron-right-grey");
            }
            if (typeof (Feature_Rented_PropertyRef) != 'undefined') {
                $('#' + Feature_Rented_PropertyRef.left).attr("class", "chevron-right-grey");
            }
            if (typeof (Feature_Listed_PropertyRef) != 'undefined') {
                $('#' + Feature_Listed_PropertyRef.left).attr("class", "chevron-right-grey");
            }
        }
    }
}


function ValidateLFContactMe(sender, args) {
    var flag = true;
    if (sender.ControlPosition == 'header') {
        if ($('#divProfileContact_header').find('[id$="txtEmail"]').val() == '' && $('#divProfileContact_header').find('[id$="txtPhone"]').val() == '') { flag = false; }
    } else if (sender.ControlPosition == 'actionbar_top') {
        if ($('#divProfileContact_actionbar_top').find('[id$="txtEmail"]').val() == '' && $('#divProfileContact_actionbar_top').find('[id$="txtPhone"]').val() == '') { flag = false; }
    } else if (sender.ControlPosition == 'actionbar_bottom') {
        if ($('#divProfileContact_actionbar_bottom').find('[id$="txtEmail"]').val() == '' && $('#divProfileContact_actionbar_bottom').find('[id$="txtPhone"]').val() == '') { flag = false; }
    } else {
        if ($('#divListingFullContact').find('[id$="txtEmail"]').val() == '' && $('#divListingFullContact').find('[id$="txtPhone"]').val() == '') { flag = false; }
    }
    args.IsValid = flag;
    return;
}

function ValidateLFPopupContactMe(sender, args) {
    var flag = true;
    if (sender.ControlPosition == 'actionbar_top') {
        if ($('#popout_toolbar_top').find('[id$="txtEmail"]').val() == '' && $('#popout_toolbar_top').find('[id$="txtPhone"]').val() == '') { flag = false; }
    } else if (sender.ControlPosition == 'actionbar_bottom') {
        if ($('#popout_toolbar_bottom').find('[id$="txtEmail"]').val() == '' && $('#popout_toolbar_bottom').find('[id$="txtPhone"]').val() == '') { flag = false; }
    } else if ($('#divProfileContact').find('[id$="txtEmail"]').val() == '' && $('#divProfileContact').find('[id$="txtPhone"]').val() == '') { flag = false; }
    args.IsValid = flag;
    return;
}

function ValidateCFContactMe(sender, args) {
    var flag = true;
    if ($('#divContactMe').find('[id$="txtEmailAddress"]').val() == '' && $('#divContactMe').find('[id$="txtPhone"]').val() == '') { flag = false; }
    args.IsValid = flag;
    return;
}

function CheckCountrySelected() {
    if ($("#btnSelectCountry").data("selected-country") == -1) {
        document.getElementById('ShowCountrypopup_Global').value = 1;
        ShowCountries('countrypopup_Global');
        visibilityToggle('countrypopup_Global');
        return false;
    }

}
function CheckCountrySelectedEvent(id) {
    if ($("#btnSelectCountry").data("selected-country") == -1) {
        document.getElementById(id).style.display = 'none';
        ShowCountries('countrypopup_Global');
        visibilityToggle('countrypopup_Global');
        return false;
    }
}
//QS 
function InitializeQS() {
    document.onclick = checkState;
    var hidComRes = $("#divSMLQS_F").find("[id$='ComRes']");
    if ($("#divSMLQS_F").find("[id$='rbComResResidential']").is(':checked')) {
        $(hidComRes).val($("#divSMLQS_F").find("[id$='rbComResResidential']").val());
    }
    else {
        $(hidComRes).val($("#divSMLQS_F").find("[id$='rbComResCommercial']").val());
    }

    if ($("#divSMLQS_F").find("input[id$='TransactionType']").val() == '' || $("#divSMLQS_F").find("input[id$='TransactionType']").val() == '0') {
        var hidtransType = $("#divSMLQS_F").find("input[id$='TransactionType']");
        if ($("#divSMLQS_F").find("[id$='rbTransactionTypeSale']").is(':checked')) {
            $(hidtransType).val($("#divSMLQS_F").find("[id$='rbTransactionTypeSale']").val());
        }
        else if ($("#divSMLQS_F").find("[id$='rbTransactionTypeRent']").is(':checked')) {
            $(hidtransType).val($("#divSMLQS_F").find("[id$='rbTransactionTypeRent']").val());
        }
    }
}

function ForceCountrySelection() {
    if ($("#btnSelectCountry").data("selected-country") == -1) {
        alert(SmartModuleListingQuickSearch_FreeText.CountryMsg);
        return false;
    } else {

        if (typeof (GTMCampaign) != 'undefined' && GTMCampaign == "true") {
            InsertGoogleTagManagerEvent('Landing Page - Campaign', 'Search Module', 'Search');
        }

        FTS.ValidateSubmitSearch();
    }
}

function pageLoad() {
    //$("html, body").animate({ scrollTop: 0 }, 400);
    $(".ajax-page-link").off("click");
    $(".ajax-page-link").click(function (event) {
        event.preventDefault();
        $("#CurrentPage").val($(this).data("page"));
        AutoSearch2("page");
    });

    $(".ajax-page-link-m").off("click");
    $(".ajax-page-link-m").on({
        "contextmenu": function (e) {
            e.preventDefault();
        }
    });
    $(".ajax-page-link-m").click(function (event) {
        event.preventDefault();
        GotoPage($(this).data("page"));
        AutoSearch();
    });

    $(".sendMessage").click(function (event) {
        event.preventDefault();
        var self = $(this);
        var data = {
            hitType: "listinglist",
            lang: langMF,
            type: "listing",
            listingKey: self.data("listing-key")
        };

        if (self.data("agentid")) {
            data.agentId = self.data("agentid");
        }
        else {
            throw "Either agentId or officeId must be specified."
        };

        $.ajax({
            type: "GET",
            url: "/handlers/contactform.ashx",
            data: data,
            success: function (response) {
                $("#contactFormPopup").show();
                $("#blackout").show();
                $("#contactFormPopup").html(response.html);
                contactFormControl.init();
            }
        });
    });
};

function GTag(control) {
    var v1 = Page_ClientValidate("ListingFullContact_" + control);
    if (!v1) {
        return false;
    }
    if (control == 'contact_form_right') {
        InsertOAGtm('Listing Full', 'Leads', 'Send message');
    }
    else if (control == 'header') {
        InsertOAGtm('Listing Full', 'Leads', 'Contact Me');
    }
    return true;
};

function GtmMap(scope) {
    InsertGoogleTagManagerEvent(scope + ' Profile', 'Click', 'Click on Google Map - ' + scope + ' Profile');
};

var formHasTermsAndConditionsCheckbox = false;
var formHasGDPRCheckbox = false;
var chkTermsAndConditionsChecked = false;
var chkGDPRChecked = false;

function attachTermsAndConditionsScript(checkbox, button) {
    formHasTermsAndConditionsCheckbox = true;
    $(button).attr("disabled", "disabled"); // disabled by default
    $(checkbox).click(function () {
        chkTermsAndConditionsChecked = $(this).is(':checked');
        toggleEnabledDisabledState(button);
    });
};

function attachGDPRScript(checkbox, button) {
    formHasGDPRCheckbox = true;
    $(button).attr("disabled", "disabled"); // disabled by default
    $(checkbox).click(function () {
        chkGDPRChecked = $(this).is(':checked');
        toggleEnabledDisabledState(button);
    });
}

function toggleEnabledDisabledState(control) {
    $(control).attr("disabled", "disabled");
    if (formHasTermsAndConditionsCheckbox && formHasGDPRCheckbox) {
        if (chkTermsAndConditionsChecked && chkGDPRChecked) {
            $(control).removeAttr("disabled");
        }
    }
    if (formHasTermsAndConditionsCheckbox && !formHasGDPRCheckbox) {
        if (chkTermsAndConditionsChecked) {
            $(control).removeAttr("disabled");
        }
    }
    if (!formHasTermsAndConditionsCheckbox && formHasGDPRCheckbox) {
        if (chkGDPRChecked) {
            $(control).removeAttr("disabled");
        }
    }
}

$.fn.center = function () {
    this.css("position", "fixed");
    //this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
    //    $(window).scrollTop()) + "px");
    this.css("top", "50%");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
        $(window).scrollLeft()) + "px");
    return this;
};

$(function () {
    $("#contact-visible-marker").parent().show();
});


function recaptcha_onload() {
    recaptchaHelper.recaptchaOnloadCallback();
};

function recaptchaVm(containerId, recaptchaKey, validationCallback) {
    var self = this;
    self.recaptcha_containerId = containerId;
    self.recaptchaWidgetId = -1;
    self.captcha_response_token = "";
    self.validationResponse_callback = validationCallback;
    self.validate_captcha = function () {
        try {
            grecaptcha.reset(self.recaptchaWidgetId);
        } catch (e) {
        }
        grecaptcha.execute(self.recaptchaWidgetId);
    };
    self.create_captcha = function() {
        $("#" + self.recaptcha_containerId).html("");

        self.recaptchaWidgetId = grecaptcha.render(
            self.recaptcha_containerId,
            {
                "sitekey": recaptchaKey,
                "size": "invisible",
                "callback": function (response) {
                    self.captcha_response_token = response;
                    self.validationResponse_callback(response);
                }
            },
            true);
    };

    recaptchaHelper.addRender_onloadCallback(function() {
        self.create_captcha();
    });

};

var recaptchaHelper = {
    _recaptchaLoaded: false,
    recaptchaOnloadCallback: function () {
        recaptchaHelper._recaptchaLoaded = true;
        $.each(recaptchaHelper._onloadHandlerArray,
            function (index, handler) {
                handler();
            });
    },
    _onloadHandlerArray: [],
    addRender_onloadCallback: function (handler) {
        if (!recaptchaHelper._recaptchaLoaded) {
            recaptchaHelper._onloadHandlerArray.push(handler);
        } else {
            handler();
        }
    }
};



function showCaptcha() {
    $("#captcha-popup").center();
};

function loadRecaptcha() {
    Recaptcha.create("6LeEC_USAAAAAHOyEVR_lrel8NOrDH68xgjRV1ZJ", "recaptcha-container", {
        theme: "red",
        callback: Recaptcha.focus_response_field
    });
};

var countrySelectorLoaded = false;

$.fn.countrySelector = function (controlType, language, countryChangedCallback) {
    var self = $(this);

    function loadCountrySelector(controlType, language, countryChangedCallback) {
        $.ajax({
            method: "GET",
            url: "/handlers/countrylist.ashx?action=control&type=" + controlType + "&lang=" + language,
            dataType: "json",
            success: function (response) {
                $("#country-selector-popup").html(response.html);
                $("#country-selector-popup").show();
                $("#btn-country-selector-close").click(function (e) {
                    e.preventDefault();
                    $("#country-selector-popup").hide();
                });

                $(".js-country-selected").click(function (event) {
                    event.preventDefault();

                    $("#selected-country-enuname").val($(this).data("country-enuname"));
                    $("#selected-country-name").text($(this).data("country-name"));
                    $("#selected-country-flag").removeClass();
                    $("#selected-country-flag").addClass("flags f-" + $(this).data("country-code"));

                    self.data("region-id", $(this).data("region-id"));
                    self.data("region-row-id", $(this).data("region-row-id"));
                    self.data("country-code", $(this).data("country-code"));
                    self.data("country-enuname", $(this).data("country-enuname"));
                    self.data("country-name", $(this).data("country-name"));

                    $("#country-selector-popup").hide();
                    if (countryChangedCallback) {
                        countryChangedCallback();
                    }

                });
            },
            complete: function () {
                $("#country-selector-popup").hide();
                countrySelectorLoaded = true;
                if (typeof setCountryName !== 'undefined' && $.isFunction(setCountryName)) {
                    setCountryName();
                }
            }
        });
    };

    loadCountrySelector(controlType, language, countryChangedCallback);

    $(this).unbind('click').bind('click', function (e) {
        e.preventDefault();
        if (countrySelectorLoaded) {
            $("#country-selector-popup").toggle();
        }
        else {
            loadCountrySelector(controlType, language, countryChangedCallback);
        }
    });
};

// Global Slider JavaScript Copied from GTSlider //
(
    function (custom) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory); //check that these dependencies are loaded
        }
        else if (typeof exports === 'object') {
            custom(require('jquery')); //check that these dependencies are loaded before
        }
        else {
            custom(jQuery);
        }
    }

    (function ($) {
        /*position - start slide position, navigators - left and right  buttons, indicators - navigator bullets,  animate - animation  between the slides, interval  - animation interval in milliseconds*/
        var __moduleName = "SlideThis", __attributes = { position: 0, navigator: true, indicators: false, animate: true, interval: 1000, hover: false, automatic: false, delayinterval: 2000, imgHover: false };

        this._create = function (_container, options) {
            this._attributes = $.extend({}, __attributes, options);
            this._defaults = __attributes;
            this._name = __moduleName;
            var _view = _container.find(".viewport:first"),
            _elements = _container.find(".overview:first"),
            _lstItems = 0,
            _btnNext = _container.find(".next:first"),
            _btnPrevious = _container.find(".prev:first"),
            _indicators = _container.find(".bullet"),
            _viewWidth = 0,
            _animateItems = {},
            _noOfVisibleItems = 0,
            _itemWidth = 0,
            me = this,
            _navindex = (typeof (ISRTL) !== 'undefined' && ISRTL == 'True') ? me._totalItems - 1 : 0,
            _isPreview = false,
            _forceStop = false;

            this.destroy = function () {
                me._stop();
            };

            this.stop = function () {
                if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True') {
                    this._move(me._totalItems - 1, 'btn');
                }
                else {
                    this._move(0, 'btn');
                }
                me._forceStop = true;
            };

            this.start = function () {
                me._forceStop = false;
            };

            this._load = function () {
                me._initialize();
                if (me._attributes.navigator) {
                    me._registerEvents();
                    if (me._attributes.hover) {
                        me._registerHoverEvents();
                    }
                }
                else {
                    if (typeof (_btnNext) != 'undefined') {
                        _btnNext.toggleClass('disable', true);
                    }
                }



                if (me._attributes.imgHover) {
                    me._registerimgHoverEvents();
                }

                if (me._attributes.indicators) {
                    me._registerIndicatorEvents();
                    if (!me._attributes.hover) {
                        me._attributes.hover = true;
                    }
                }

                if (me._attributes.automatic) {
                    if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True') {
                        _elements.css('left', -(me._totalItems - 1) * _itemWidth);
                        _navindex = me._totalItems - 1;
                        me._movedelayNS(me._totalItems - 1);
                    } else {
                        me._movedelayNS(0, 'btn');
                    }
                }
                return me;
            }

            this._initialize = function () {
                _lstItems = _elements.children();
                if (_lstItems[0].className == 'property-detail-slide') {
                    me._isPreview = true;
                }
                _viewWidth = _view[0]["offsetWidth"];
                _itemWidth = _lstItems.first().outerWidth(true);
                me._totalItems = _lstItems.length;
                me._currentItem = (me._attributes.position > 0) ? me._attributes.position : (typeof (ISRTL) !== 'undefined' && ISRTL == 'True') ? me._totalItems - 1 : 0;
                _noOfVisibleItems = Math.ceil(_viewWidth / _itemWidth) + 1;
                if (_noOfVisibleItems > me._totalItems)
                    _noOfVisibleItems = me._totalItems;
                if (me._isPreview) {
                    var containerWidth = _itemWidth * (me._totalItems);
                }
                else {
                    var containerWidth = _itemWidth * (me._totalItems + _noOfVisibleItems);
                    _elements.append(_lstItems.slice(0, _noOfVisibleItems).clone());
                }
                _elements.css('width', containerWidth);
                me._forceStop = false;
                me._updateData();

                return me;
            };

            this._registerHoverEvents = function () {
                _btnPrevious.mouseenter(function () {
                    me.moveRTL();
                });
                _btnPrevious.mouseleave(function () {
                    if (me._attributes._timehandleID > 0) {
                        clearTimeout(me._attributes._timehandleID);
                    }
                    return false;
                });
                _btnNext.mouseenter(function () {
                    me.moveLTR();
                });
                _btnNext.mouseleave(function () {
                    if (me._attributes._timehandleID > 0) {
                        clearTimeout(me._attributes._timehandleID);
                    }
                    return false;
                });
            }

            this._registerimgHoverEvents = function () {
                _view.mouseenter(function () {
                    me._stop();
                });
                _view.mouseleave(function () {
                    me._startNS();
                    return false;
                });
            }

            this._registerEvents = function () {
                if (!me._attributes.hover) {
                    if (me._attributes.navigator) {
                        _btnPrevious.click(function () {
                            me._move(me._currentItem - 1, 'btn');
                            me._stop();
                            return false;
                        });
                        _btnNext.click(function () {
                            me._move(me._currentItem + 1, 'btn');
                            me._stop();
                            return false;
                        });
                    }
                }
            }

            this._registerIndicatorEvents = function () {
                if (me._attributes.indicators) {
                    _container.on("click", ".bullet", function () {
                        me._move($(this).attr("data-slide-no"), 'li');
                        return false;
                    });
                }
            }

            this.moveRTL = function () {
                me._move(parseInt(_navindex) - 1, 'btn');
                me._attributes._timehandleID = setTimeout(function () {
                    me.moveRTL();
                }, me._attributes.interval);
            }

            this.moveLTR = function () {
                me._move(parseInt(_navindex) + 1, 'btn');
                me._attributes._timehandleID = setTimeout(function () {
                    me.moveLTR();
                }, me._attributes.interval);
            }

            this._start = function () {
                if (me._attributes.animate) {
                    clearTimeout(me._attributes._timehandleID);
                    me._movedelay();
                }
            }

            this._startNS = function () {
                if (me._attributes.animate) {
                    clearTimeout(me._attributes._timehandleID);
                    me._movedelayNS(parseInt(_navindex));
                }
            }

            this._stop = function () {
                clearTimeout(me._attributes._timehandleID);
                return me;
            }




            this._movedelay = function (index, navtype) {
                if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True')
                    me._move(parseInt(_navindex) - 1, 'btn');
                else
                    me._move(parseInt(_navindex) + 1, 'btn');
                me._attributes._timehandleID = setTimeout(function () {
                    me._movedelay();
                }, me._attributes.delayinterval);
            }


            this._movedelayNS = function (index, navtype) {
                var photonum = (index % me._totalItems) + 1;
                if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True')
                    photonum = ((me._totalItems - index - 1) % me._totalItems) + 1;
                if (me._attributes.counter)
                    $(".photo-count-text").text(photonum + '/' + me._totalItems);
                me._attributes._timehandleID = setTimeout(function () {
                    me._movedelay();
                }, me._attributes.delayinterval);
            }

            this._updateData = function () {
                if (typeof me._attributes.itemChange == "function")
                    me._attributes.itemChange($(_lstItems[me._currentItem]));
            };

            this._move = function (index, navtype) {
                if (!me._forceStop) {
                    if (!me._attributes.hover) {

                        var _Item = Math.min(index, (me._totalItems - _noOfVisibleItems)) || 0;
                        me._currentItem = (_Item > 0) ? _Item : 0;
                        _animateItems['left'] = -me._currentItem * _itemWidth;
                        if (navtype === 'li') {
                            me._currentIndicator = index;
                        }
                        else {
                            me._currentIndicator = (typeof (me._currentIndicator) == 'undefined') ? 0 : me._currentIndicator;
                            var _tmpIndex = parseInt(me._currentIndicator || 0);
                            me._currentIndicator = ((me._currentIndicator > index) ? (_tmpIndex - 1) : (_tmpIndex + 1)) || 0;
                        }
                        this._initializeNavigators(me._currentIndicator);
                    }
                    else {

                        _navindex = index;
                        me._currentItem = _navindex % me._totalItems;

                        if (_navindex < 0) {
                            me._currentItem = _navindex = me._totalItems - 1;
                            if (!me._isPreview) {
                                _elements.css('left', -(me._totalItems) * _itemWidth);
                            }
                        }

                        if (me._isPreview) {
                            if (_navindex > me._totalItems - 1) {
                                me._currentItem = _navindex = 0;
                            }
                        }
                        else {
                            if (_navindex > me._totalItems) {
                                me._currentItem = _navindex = 1;
                                _elements.css('left', 0);
                            }
                        }

                        _animateItems['left'] = -(_navindex * _itemWidth);
                        if (me._isPreview) {
                            if (_navindex == 0 && !(typeof player === "undefined")) {
                                if (!(typeof (ISRTL) !== 'undefined' && ISRTL == 'True')) {
                                    player.playVideo();
                                }
                            }
                            else if (_navindex == me._totalItems - 1 && !(typeof player === "undefined")) {
                                if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True') {
                                    player.playVideo();
                                }
                            }
                        }
                        this._initializeNavigators(me._currentItem);
                    }


                    _elements.animate(
                        _animateItems,
                        {
                            queue: false,
                            duration: this._attributes.animate ? this._attributes.interval : 0,
                            complete: function () {

                                _container.trigger("move", [_lstItems[me._currentItem], me._currentItem]);
                            }
                        }
                   );

                    me._updateData();
                }
                return me;
            };

            this._initializeNavigators = function (index) {
                var photonum = (index % me._totalItems) + 1;
                if (typeof (ISRTL) !== 'undefined' && ISRTL == 'True')
                    photonum = ((me._totalItems - index - 1) % me._totalItems) + 1;
                if(me._attributes.counter)
                    $(".photo-count-text").text(photonum + '/' + me._totalItems);


                if (me._attributes.navigator) {
                    if (me._attributes.hover) {
                        _btnPrevious.toggleClass('disable', false);
                        _btnNext.toggleClass('disable', false);
                    }
                    else {
                        /*_btnPrevious.toggleClass("disable", index <= 0);
                        _btnNext.toggleClass("disable", index >= (me._totalItems - 1)); */
                    }
                }

                if (me._attributes.indicators) {
                    _indicators.removeClass("active");
                    $(_indicators[index]).addClass("active");
                }
            }
            return this._load();
        }

        $.fn[__moduleName] = function (_attributes) {
            return this.each(function () {
                if (_attributes === "destroy") {
                    var plugin = $(this).data("plug-in_" + __moduleName);
                    plugin.destroy();
                }
                else if (_attributes === "stop") {
                    var plugin = $(this).data("plug-in_" + __moduleName);
                    if (plugin != undefined) {
                        plugin.stop();
                    }
                }
                else if (_attributes === "start") {
                    var plugin = $(this).data("plug-in_" + __moduleName);
                    if (plugin != undefined) {
                        plugin.start();
                    }
                }
                else {
                    if (!$.data(this, "plug-in_" + __moduleName)) {
                        var obj = new _create($(this), _attributes);
                        $.data(this, "plug-in_" + __moduleName, obj);
                    }
                }
            });
        }
    })
);

var currentSwiftMap;
var swiftMapPopup;
var markers = [];
var polygons = [];
var circles = [];
var drawingManager;
var existedOverlay;
var radiusMeter;
var radiusLat;
var radiusLng;
var polygonList;
var hasDrawMap = false;
var hasSwitchedTab = false;
var resetMarker = true;
var defaultzoomlevel;
var keepzoomlevel = false;
var _googleMap_apply_click_alert_timeoutIds = [];
var _shapeJustComplete;

function ApplyShape() {
    $("#zoom-level-draw").css('display', 'none');
    if (radiusMeter && radiusMeter != "") {
        $("#RadiusMeter").val(radiusMeter);
        $("#RadiusLat").val(radiusLat);
        $("#RadiusLng").val(radiusLng);
    } else if (polygonList && polygonList != "") {
        $("#PolyGon").val(polygonList);
    }

    if (typeof (regionRowDropDownID) === "undefined") {
        populateFilter();
    }
};

function ApplyAlert() {    
    ClearMessageTimeouts();
    $("#polygon-galleryview-alert").css('display', 'none');
    $("#apply-click-alert").css('display', 'none');
    _googleMap_apply_click_alert_timeoutIds.push(window.setTimeout(function() {
        var polygonGalleryViewStatus = getCookie("PolygonGalleryViewAlert");
        if (mapArray.length >= 1 && pendingRequest == false && polygonGalleryViewStatus != 1) {
            $("#polygon-galleryview-alert").css('display', 'block');
        }
        if (mapArray.length < 1 && pendingRequest == false) {
            $("#apply-click-alert").css('display', 'block');
        }
    }, 2000));
}

function ClearMessageTimeouts() {
    if (_googleMap_apply_click_alert_timeoutIds.length > 0) {

        $.each(_googleMap_apply_click_alert_timeoutIds,
            function (index, item) {
                window.clearTimeout(_googleMap_apply_click_alert_timeoutIds[index]);
            });

        _googleMap_apply_click_alert_timeoutIds.length = 0;
    }
};

function setPolygonGalleryViewAlertCookie() {
    createCookie("PolygonGalleryViewAlert", 1, 30);
    $("#polygon-galleryview-alert").css('display', 'none');
}

function CancelShape() {
    ClearMessageTimeouts();
        

    $("#map-draw-area").css('display', 'none');
    $("#drawmap-circle-distance").css('display', 'none');
    $("#apply-click-alert").css('display', 'none');
    $("#polygon-galleryview-alert").css('display', 'none');
    $("#draw-new-alert").css('display', 'none');
    $("#PolyGon").val("");
    $("#RadiusMeter").val("");
    $("#RadiusLat").val("");
    $("#RadiusLng").val("");
    $("#hidLat").val("");
    $("#hidLng").val("");
    $("#hidzoom").val("");
    $("#hidSwLat").val("");
    $("#hidSwLng").val("");
    $("#hidNeLat").val("");
    $("#hidNeLng").val("");

    if (typeof searchBarParamsHelper != "undefined") {
        searchBarParamsHelper.clear();
    }
    

    radiusMeter = "";
    radiusLat = "";
    radiusLng = "";
    polygonList = "";
    hasDrawMap = false;
    hasSwitchedTab = false;
    resetMarker = true;
    keepzoomlevel = false;
    circles = [];
    polygons = [];
    $("#custom-btnCircle").removeAttr('disabled');
    $("#custom-btnPolygon").removeAttr('disabled');
    if (existedOverlay != null) {
        existedOverlay.setMap(null);
        drawingManager.setMap(currentSwiftMap);
        if (typeof (regionRowDropDownID) === "undefined") {
            populateFilter();
        }
    }
}

$.fn.swiftMap = function (args) {
    var self = this;
    GroupOverlay.prototype = new google.maps.OverlayView();
    GroupOverlay.prototype.onAdd = function () {
        function getSizeCssClass(text) {
            if (parseInt(text) == 1) return "lc-one ";
            if (text.length <= 2) return "lc-small ";
            if (text.length <= 4) return "lc-medium ";
            return "lc-large ";
        };
        function getStatusCssClass(status) {
            if (status == 167 || status == 169) return "lc-sold";
            return "";
        };

        var a = document.createElement("a");
        a.href = "#";
        a.className = "listing-cluster " + getSizeCssClass(this.text) + getStatusCssClass(this.status);
        a.style.position = "absolute";

        if (parseInt(this.text) > 1) {
            var div = document.createElement("div");
            div.className = "cluster-text";
            div.innerHTML = this.text;

            a.appendChild(div);
        }

        this.a = a;

        this.getPanes().overlayMouseTarget.appendChild(a);

        var self = this;
        google.maps.event.addDomListener(this.a, "click", function (event) {
            keepzoomlevel = false;
            event.preventDefault();
            if (self.keys && self.keys.length > 0)
                loadPopup(self);
            else
                centerAndZoom(self);
        });
    };
    GroupOverlay.prototype.draw = function () {
        var overlayProjection = this.getProjection();

        var center = overlayProjection.fromLatLngToDivPixel(this.position);

        this.a.style.left = center.x + "px";
        this.a.style.top = center.y + "px";
    };
    GroupOverlay.prototype.onRemove = function () {
        this.a.parentNode.removeChild(this.a);
        this.a = null;
        if (this.hasPopup)
            closeSwiftMapPopup();
    };

    function GroupOverlay(data) {
        this.position = data.position;
        this.text = data.text;
        this.single = data.single;
        this.status = data.status;
        this.keys = data.keys;
        this.setMap(data.map);
        this.hasPopup = false;
    };

    function closeSwiftMapPopup() {
        if (swiftMapPopup) {
            swiftMapPopup.close();
        }
        markers.forEach(function (item) {
            item.hasPopup = false;
        });
    };


    function getPopupSearchArgs() {
        var urlhash;
        var mode = getUrlParameter("mode");

        if (mode && mode == "glmap") {
            urlhash = "mode=glpopup";
        } else {
            urlhash = "mode=popup";
        }

        if (getUrlParameter("sc") != undefined && getUrlParameter("sc") != null) {
            urlhash = urlhash + "&sc=" + getUrlParameter("sc");
        }
        if (getUrlParameter("cur") != undefined && getUrlParameter("cur") != null) {
            urlhash = urlhash + "&cur=" + getUrlParameter("cur");
        }
        urlhash = urlhash + "&sid=" + currentSiteId.replace(/[\{\}]/g, "");
        return urlhash;
    }

    function loadPopup(marker) {
        closeSwiftMapPopup();

        $.ajax({
            url: getBaseURL() + getPopupSearchArgs(),
            type: "POST",
            data: {
                keys: marker.keys.join()
            },
            success: function (response) {
                swiftMapPopup = new google.maps.InfoWindow({
                    content: response.llContentContainerHtml,
                    pixelOffset: new google.maps.Size(0, -18)
                });
                google.maps.event.addListener(swiftMapPopup, "domready", function () {
                    $(".virtual-tour-invoker").virtualTour();
                    $(".my-favorite-invoker").myFavorite();
                    google.maps.event.clearListeners(swiftMapPopup, "domready");
                });
                swiftMapPopup.open(currentSwiftMap);
                swiftMapPopup.setPosition(marker.position);
                marker.hasPopup = true;
            },
            complete: function () {
            }
        });
    };

    function resetGeoFilters() {
        AllowEvents(false);
        enableAutoSearch = false;
        if (typeof (regionRowDropDownID) === "undefined") {
            populateFilter();
            //$("#world-fts-input").multiGeoSelect("clear");
        }
        else
            $("#" + regionRowDropDownID).val("0").change();
        geoCriteriaChanged = false;
        enableAutoSearch = true;
        AllowEvents(true);
    };

    function centerAndZoom(marker) {
        currentSwiftMap.setCenter(marker.position);
        if (hasDrawMap && keepzoomlevel) {
            currentSwiftMap.setZoom($("#hidzoom").val());
        } else {
            currentSwiftMap.setZoom(currentSwiftMap.getZoom() + 2);
        }
    };

    function fitBounds(data) {
        if (data.nelat && data.nelng && data.swlat && data.swlng) {
            var bounds = new google.maps.LatLngBounds();
            bounds.extend(new google.maps.LatLng(data.nelat, data.nelng));
            bounds.extend(new google.maps.LatLng(data.swlat, data.swlng));
            currentSwiftMap.fitBounds(bounds);
        };
    };

    function setMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        };

        markers = [];

        $.each(mapArray, function (i, item) {
            var marker = new GroupOverlay({
                position: new google.maps.LatLng(item.lat, item.lng),
                text: item.count.toString(),
                single: item.count == 1,
                map: currentSwiftMap,
                status: item.status,
                keys: item.keys
            });
            markers.push(marker);
        });
    };

    function deleteMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        };
        markers =[];
    }

    function enableDrawingControl() {
        drawingManager.setMap(currentSwiftMap);
        $("#custom-btnCircle").removeAttr("disabled");
        $("#custom-btnPolygon").removeAttr("disabled");
        $("#zoom-level-closer").css('display', 'none');
        $("#zoom-level-draw").css('display', '');
    }

    function disableDrawingControl() {
        $("#custom-btnCircle").attr("disabled", "disabled");
        $("#custom-btnPolygon").attr("disabled", "disabled");
        if (!hasDrawMap) {
            $("#zoom-level-closer").css('display', '');
            $("#zoom-level-draw").css('display', 'none');
        }
    }

    function setDrawingManagerControl() {
        if (currentSwiftMap.zoom >= defaultzoomlevel && !hasDrawMap) {
            enableDrawingControl();
        } else if (currentSwiftMap.zoom < defaultzoomlevel) {
            disableDrawingControl();
        }
    }

    function caculateDistance(radiusmeter) {
        var distance;
        if ($("#LengthUnit").val() != "" && $("#LengthUnit").val() == "kilometres") {
            distance = caculateDistanceInKilometer(radiusmeter);  // Math.round(radiusmeter / 10) / 100;
        } else if ($("#LengthUnit").val() != "" && $("#LengthUnit").val() == "miles") {
            distance = caculateDistanceInMiles(radiusmeter) // Math.round(radiusmeter * 0.0621371192) / 100;
        }
        return distance;
    }

    function caculateDistanceInKilometer(radiusmeter) {
        return Math.round(radiusmeter / 10) / 100;
    }

    function caculateDistanceInMiles(radiusmeter) {
        return Math.round(radiusmeter * 0.0621371192) / 100;
    }

    function setDrawShape() {
            if (hasDrawMap && hasSwitchedTab) {
                hasSwitchedTab = false;
                if (circles && circles.length > 0) {
                    if ($("#RadiusMeter").val() != "0" && $("#RadiusMeter").val() != "") {
                        $("#map-draw-area").css('display', '');
                        ApplyAlert();
                        circles[0].setMap(currentSwiftMap);
                        $("#drawmap-circle-distance-num").text(caculateDistance(radiusMeter));
                        $("#drawmap-circle-distance-num-km-gl").text(caculateDistanceInKilometer(radiusMeter));
                        $("#drawmap-circle-distance-num-miles-gl").text(caculateDistanceInMiles(radiusMeter));
                        $("#drawmap-circle-distance").css('display', '');
                    } else if ($("#RadiusMeter").val() != "0" || $("#RadiusMeter").val() != "") {
                        hasDrawMap = false;
                        circles = [];
                    }
                } else if (polygons && polygons.length > 0) {
                    if ( $("#PolyGon").val() != "0" && $("#PolyGon").val() != "") {
                        $("#map-draw-area").css('display', '');
                        ApplyAlert();
                        polygons[0].setMap(currentSwiftMap);
                    } else if ($("#PolyGon").val() != "0" || $("#PolyGon").val() != "") {
                        hasDrawMap = false;
                        polygons = [];
                    }
                }
            }
    }

    if (currentSwiftMap) {
        defaultzoomlevel = $("#ZoomLevel").val();
        setMarkers();
        if (!hasDrawMap && !keepzoomlevel) {
            fitBounds(args);
        }
        setDrawShape();
        setDrawingManagerControl();
        return;
    };

    var mapOptions = {
        panControl: false,
        maxZoom: $("#MaxZoomLevel").val()
    };

    if ((args.lat || args.lat == 0) && (args.lng || args.lng == 0) && args.zoom) {
        mapOptions.center = new google.maps.LatLng(args.lat, args.lng);
        mapOptions.zoom = args.zoom;
    };

    currentSwiftMap = new google.maps.Map(self[0], mapOptions);
    if (currentSwiftMap) {
        InsertGoogleTagManagerEvent('Google Map Listing Search', 'Map Load Search', 'Google Map Requests');
    }

    fitBounds(args);

    drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT,
            drawingModes: []
        },
        circleOptions: {
            fillColor: '#3598dc',
            fillOpacity: 0.35,
            strokeColor: '#00458b',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            clickable: false,
            editable: true,
            zIndex: 1
        },
        polygonOptions: {
            fillColor: '#3598dc',
            fillOpacity: 0.35,
            strokeColor: '#00458b',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            clickable: false,
            editable: false,
            zIndex: 1
        }

    });


    if ($("#PolyGon").val() != "") {
        var polygonString = $("#PolyGon").val();

        var pArray = polygonString.split(")");

        var polyCoords = [];
        $.each(pArray,
            function (index, poly) {
                if (poly.indexOf(",") === 0) {
                    poly = poly.substr(1, poly.length - 1);
                }

                var pSplit = poly.split(",");
                var lat = $.trim(pSplit[0].replace("(", ""));
                var lng = $.trim(pSplit[1]);

                if (!isNaN(lat) && lat !== "") {
                    polyCoords.push({ lat: parseFloat(lat), lng: parseFloat(lng) });
                }
            });

        existedOverlay = new google.maps.Polygon({
            paths: polyCoords,
            strokeColor: '#00458b',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            fillColor: '#3598dc',
            fillOpacity: 0.35
        });

        polygons[0] = existedOverlay;
        hasDrawMap = true;
        hasSwitchedTab = true;
        defaultzoomlevel = $("#ZoomLevel").val();
        setDrawShape();
        disableDrawingControl();
        currentSwiftMap.setZoom(defaultzoomlevel);
    }
    else if ($("#RadiusMeter").val() != "") {
        var latFloat = parseFloat($("#RadiusLat").val());
        var lngFloat = parseFloat($("#RadiusLng").val());


        existedOverlay = new google.maps.Circle({
            paths: polyCoords,
            strokeColor: '#00458b',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            fillColor: '#3598dc',
            fillOpacity: 0.35,
            center: { lat: latFloat, lng: lngFloat },
            radius: parseFloat($("#RadiusMeter").val())
        });

        circles[0] = existedOverlay;
        hasDrawMap = true;
        hasSwitchedTab = true;
        defaultzoomlevel = $("#ZoomLevel").val();
        setDrawShape();
        disableDrawingControl();
        currentSwiftMap.setZoom(defaultzoomlevel);
    }


    $("#custom-btnCircle").click(function () {
        InsertGoogleTagManagerEvent("Radius Polygon Search", "Click Circle draw tool", "Radius Search");

        CancelShape();

        if (currentSwiftMap.zoom < defaultzoomlevel) {
            return false;
        }
        if (!hasDrawMap) {
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.CIRCLE);
            resetMarker = false;
        }
        return false;
    });

    $("#custom-btnPolygon").click(function () {
        InsertGoogleTagManagerEvent("Radius Polygon Search", "Click Shape draw tool", "Polygon Search");

        CancelShape();

        if (currentSwiftMap.zoom < defaultzoomlevel) {
            return false;
        }
        if (!hasDrawMap) {
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
            resetMarker = false;
        }
        return false;
    });

    $('#apply-click-close').click(function () {
        $("#apply-click-alert").css('display', 'none');
        SetCloseAlertAnalytic();
    });


    $('#polygon-galleryview-alert-close').click(function () {
        $("#polygon-galleryview-alert").css('display', 'none');
        SetCloseAlertAnalytic();
    });


    $('#draw-alert-close').click(function () {
        $("#draw-new-alert").css('display', 'none');
        SetCloseAlertAnalytic();
    });

    $('#zoom-level-closer-span').click(function () {
        $("#zoom-level-closer").css('display', 'none');
        SetCloseAlertAnalytic();
    });

    $('#zoom-level-draw-span').click(function () {
        $("#zoom-level-draw").css('display', 'none');
        SetCloseAlertAnalytic();
    });


    function SetCloseAlertAnalytic() {
        InsertGoogleTagManagerEvent("Radius Polygon Search", "Close alert message", "Alert Messages");
    }


    google.maps.event.addListener(drawingManager, 'drawingmode_changed', function (event) {
        if (currentSwiftMap.zoom < defaultzoomlevel) {
            return false;
        }

        resetGeoFilters();
        closeSwiftMapPopup();
        if (drawingManager.getDrawingMode() && drawingManager.getDrawingMode().toLowerCase() == "polygon") {
            deleteMarkers();
            $("#apply-click-alert").css('display', 'none');
        } else if (drawingManager.getDrawingMode() && drawingManager.getDrawingMode().toLowerCase() == "circle") {
            deleteMarkers();
            $("#apply-click-alert").css('display', 'none');
        } else if (drawingManager.getDrawingMode() == null && !hasDrawMap) {
            $("#apply-click-alert").css('display', 'none');
            setMarkers();
        }
    });

    google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
        _shapeJustComplete = event.type; //used by drawmap-apply click event

        if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
            InsertGoogleTagManagerEvent("Radius Polygon Search", "Draw a Circle", "Radius Search");
            

            if (drawingManager.getMap()) {
                drawingManager.setMap(null);
            }
            existedOverlay = event.overlay;
            hasDrawMap = true;
            resetMarker = false;
            radiusMeter = event.overlay.getRadius();
            radiusLat = event.overlay.getCenter().lat();
            radiusLng = event.overlay.getCenter().lng();
            $("#map-draw-area").css('display', '');
            $("#drawmap-circle-distance").css('display', '');
            $("#drawmap-circle-distance-num").text(caculateDistance(radiusMeter));
            $("#drawmap-circle-distance-num-km-gl").text(caculateDistanceInKilometer(radiusMeter));
            $("#drawmap-circle-distance-num-miles-gl").text(caculateDistanceInMiles(radiusMeter));
        } else if (event.type == google.maps.drawing.OverlayType.POLYGON) {
            InsertGoogleTagManagerEvent("Radius Polygon Search", "Draw an Area", "Polygon Search");


            if (drawingManager.getMap()) {
                drawingManager.setMap(null);
            }
            existedOverlay = event.overlay;
            hasDrawMap = true;
            resetMarker = false;
            polygonList = event.overlay.getPath().getArray();
            $("#drawmap-circle-distance").css('display', 'none');
            $("#map-draw-area").css('display', '');
        }

        $("#custom-btnCircle").attr("disabled", 'disabled');
        $("#custom-btnPolygon").attr("disabled", 'disabled');

        if (drawingManager.getDrawingMode()) {
            drawingManager.setDrawingMode(null);
        }
    });

    google.maps.event.addDomListener(drawingManager, "polygoncomplete", function (polygon) {
        polygons.push(polygon);
    });

    google.maps.event.addDomListener(drawingManager, "circlecomplete", function (circle) {
        circles.push(circle);
        google.maps.event.addListener(circle, 'radius_changed', function () {
            radiusMeter = circle.getRadius();
            radiusLat = circle.getCenter().lat();
            radiusLng = circle.getCenter().lng();
            $("#drawmap-circle-distance-num").text(caculateDistance(radiusMeter));
            $("#drawmap-circle-distance-num-km-gl").text(caculateDistanceInKilometer(radiusMeter));
            $("#drawmap-circle-distance-num-miles-gl").text(caculateDistanceInMiles(radiusMeter));
            if ($("#RadiusMeter").val() != "" && $("#RadiusMeter").val() != "0") {
                ApplyShape();
                callAlertFunction = true;
                ajaxSearch();
            }
        });

        google.maps.event.addListener(circle, 'center_changed', function () {
            radiusMeter = circle.getRadius();
            radiusLat = circle.getCenter().lat();
            radiusLng = circle.getCenter().lng();
            $("#drawmap-circle-distance-num").text(caculateDistance(radiusMeter));
            $("#drawmap-circle-distance-num-km-gl").text(caculateDistanceInKilometer(radiusMeter));
            $("#drawmap-circle-distance-num-miles-gl").text(caculateDistanceInMiles(radiusMeter));
            if ($("#RadiusMeter").val() != "" && $("#RadiusMeter").val() != "0") {
                ApplyShape();
                callAlertFunction = true;
                ajaxSearch();
            }

        });
    });

    $('#drawmap-apply').on('click', function (e) {
        switch (_shapeJustComplete) {
            case google.maps.drawing.OverlayType.CIRCLE:
                InsertGoogleTagManagerEvent("Radius Polygon Search", "Apply drawn Circle", "Radius Search");
                break;
            case google.maps.drawing.OverlayType.POLYGON:
                InsertGoogleTagManagerEvent("Radius Polygon Search", "Apply drawn Area", "Polygon Search");
                break;
        };

        ApplyShape();
        callAlertFunction = true;
        ajaxSearch();
        resetMarker = true;
    });

    $('#drawmap-cancel').on('click', function (e) {
        InsertGoogleTagManagerEvent("Radius Polygon Search", "Clear Radius Polygon Search", "Reset Radius Polygon Search");
        CancelShape();
        ajaxSearch();
    });

    function ClearSearchBar() {
        if (typeof (regionRowDropDownID) === "undefined") {
            $("#world-fts-input").multiGeoSelect('removeAll');
        }
    };

    google.maps.event.addListener(currentSwiftMap, 'dragstart', function () {
        keepzoomlevel = false;
        closeSwiftMapPopup();
    });

    google.maps.event.addListener(currentSwiftMap, 'dragend', function () {
        ClearSearchBar();

        if (resetMarker) {
            keepzoomlevel = false;
            resetGeoFilters();
            ajaxSearch();
        }
    });

    google.maps.event.addListener(currentSwiftMap, 'zoom_changed', function () {
        if (geoCriteriaChanged || firstMapLoad)
            return;

        if (resetMarker) {
            keepzoomlevel = false;
            resetGeoFilters();
            closeSwiftMapPopup();
            ajaxSearch();
        }
    });

    google.maps.event.addListener(currentSwiftMap, 'bounds_changed', function () {

        if (resetMarker) {
            if (geoCriteriaChanged || firstMapLoad) {
                firstMapLoad = false;
                geoCriteriaChanged = false;
                ajaxSearch();
            }
        }
    });

    google.maps.event.addListener(currentSwiftMap, 'click', function (event) {
        keepzoomlevel = false;
        closeSwiftMapPopup();
        //if (hasDrawMap && $("#PolyGon").val() != "") {
        //    if (outsidePolygon(event.latLng.lat(), event.latLng.lng())) {
        //        CancelShape();
        //        ajaxSearch();
        //    }
        //} else if (hasDrawMap && $("#RadiusMeter").val() != "") {
        //    if (outsideCircle(event.latLng.lat(), event.latLng.lng())) {
        //        CancelShape();
        //        ajaxSearch();
        //    }
        //}
    });

    setMarkers();
};

//function outsidePolygon(lat, lng) {
//    var clickP = new google.maps.LatLng(lat, lng);
//    if (google.maps.geometry.poly.containsLocation(clickP, polygons[0])) {
//        return false;
//    } else {
//        return true;
//    }
//}

//function outsideCircle(lat, lng) {
//    var clickP = new google.maps.LatLng(lat, lng);
//    var circleC = new google.maps.LatLng($("#RadiusLat").val(), $("#RadiusLng").val());
//    var distance = google.maps.geometry.spherical.computeDistanceBetween(clickP, circleC);

//    if (distance > $("#RadiusMeter").val()) {
//        return true;
//    } else {
//        return false;
//    }
//}


function loadSwiftMap(data) {
    $("#map-canvas").swiftMap(data);
};

$.fn.popupMap = function (method) {
    this.click(function (event) {
        var parents = $(this).parents(".fluid.thumb");
        var directParent = $(this).parent();

        event.preventDefault();
        var self = $(this);

        var mapDivId = self.data("mapdiv-id");
        var imgId = self.data("img-id");

        var curPopup = $(mapDivId).parent();

        var googleId = mapDivId.replace("#", "");

        if (method === "close") {
            HideListingListMap(googleId);
            return;
        }

        $(curPopup).css("display", "block");

        var position = $(imgId).position();

        $(mapDivId).css("display", "block");

        var opts = {
            infoWindowContent: "",
            infoWindowOnMarkerClick: false,
            zoom: 13,
            addressToSetZoomOn: "",
            marker: {
                icon: ResidentialMarkerIconPath,
                shadow: ResidentialMarkerShadowPath,
                title: ""
            },
            disabled: true
        }

        maps.GoogleVer3['initialize'](googleId, self.data("lat"), self.data("lng"), opts);
        InsertGoogleTagManagerEvent('Google Map Listing Search', 'Map Load Thumbnail List View', 'Google Map Requests');
        $(curPopup).css('z-index', '300000');
        if ($("[id$='hiddenRTL']").val().toLowerCase() == "false") {

            $(curPopup).css(position); //put map to the img postion
        }
        else {

            position.left = position.left - 350;

            $(curPopup).css(position);

        }
        //$("#blackout").css('display', 'block');
        //$('#blackout').on('click', function (e) {
        //    HideListingListMap(googleId);
        //});
    });
};

$.fn.virtualTour = function () {
    this.click(function (event) {
        event.preventDefault();
        var type = $(this).data("link-type");
        var url = $(this).attr("href");

        if (type == "virtual-tour")
            VirtualTourWindow(url);
        else if (type == "multi-media")
            MultiMediaWindow(url);
    });
};

function updateMyFavoritesButtons(listingKey) {
    $(".my-favorite-invoker[data-listing-key='" + listingKey + "']").each(function () {
        var self = $(this);
        if (self.data("is-favorite") === "True") {
            if (self.hasClass("fav-on")) {
                self.removeClass("fav-on");
                self.addClass("fav-off");
            }
            else {
                self.removeClass("gps-fav-on");
                self.addClass("gps-fav-off");
            }
            self.data("is-favorite", "False");
        } else {
            if (self.hasClass("fav-off")) {
                self.addClass("fav-on");
                self.removeClass("fav-off");
            }
            else {
                self.removeClass("gps-fav-off");
                self.addClass("gps-fav-on");
            }
            self.data("is-favorite", "True");
        }
    });
};

$.fn.myFavorite = function () {
    this.click(function (event) {
        event.preventDefault();
        var listingKey = $(this).data("listing-key");

        var IsGPS = false;
        if ($(this).hasClass("gps-fav-on") || $(this).hasClass("gps-fav-off")) {
            IsGPS = true;
        }

        if ($(this).data("is-favorite") === "True") {
            var func = AjaxAsynchMethodsForFavourites.RemovePropertyFromFavourites(listingKey);
        }
        else {
            var func = AjaxAsynchMethodsForFavourites.AddPropertyToFavourites(listingKey);
            InsertOAGtm('Listings Search Results', 'Listing Info', 'Favorite');
        }

        func.done(function () {
            updateMyFavoritesButtons(listingKey);
            if (typeof (UpdateMyFavouritesDatagrid) != 'undefined') {
                UpdateMyFavouritesDatagrid();
            }
            if (IsGPS) {
                $("#html_container").trigger("favToggle");
            }
        });


    });
};

$.fn.toggleMap = function () {
    this.click(function (event) {
        var imgId = $(this).data("img-id");
        var mapId = $(this).data("mapdiv-id");
        var curPhoto = $(imgId);
        var currentMode = $(this).data("mode");

        if (currentMode === "photo") {
            InsertOAGtm('Listings Search Results', 'Listing Info', 'Listing location on map');
            $(this).attr("class", "photo");
            $(this).data("mode", "map");



            $(curPhoto).hide();
            var googleMapId = $(mapId).attr("id");
            $(mapId).show();

            var opts = {
                infoWindowContent: "",
                infoWindowOnMarkerClick: false,
                zoom: 13,
                addressToSetZoomOn: "",
                marker: {
                    icon: ResidentialMarkerIconPath,
                    shadow: ResidentialMarkerIconPath,
                    title: ""
                },
                disabled: true
            }
            var lat = $(this).data("lat");
            var lng = $(this).data("lng");

            maps.GoogleVer3['initialize'](googleMapId, lat, lng, opts);
            InsertGoogleTagManagerEvent('Google Map Listing Search', 'Map Load Thumbnail Gallery View', 'Google Map Requests');
        }
        else {
            $(this).attr("class", "map");
            $(this).data("mode", "photo");
            $(curPhoto).show();
            $(mapId).hide();
        }
    });
};

function imgError(image) {
    image.onerror = "";
    image.src = "/common/images/NoPhoto_listing.jpg";
    return true;
};


// jquery BBQ deparam
(function (h) {
    h.deparam = function (i, j) {
        var d = {}, k = { "true": !0, "false": !1, "null": null }; h.each(i.replace(/\+/g, " ").split("&"), function (i, l) {
            var m; var a = l.split("="), c = decodeURIComponent(a[0]), g = d, f = 0, b = c.split("]["), e = b.length - 1; /\[/.test(b[0]) && /\]$/.test(b[e]) ? (b[e] = b[e].replace(/\]$/, ""), b = b.shift().split("[").concat(b), e = b.length - 1) : e = 0; if (2 === a.length) if (a = decodeURIComponent(a[1]), j && (a = a && !isNaN(a) ? +a : "undefined" === a ? void 0 : void 0 !== k[a] ? k[a] : a), e) for (; f <= e; f++) c = "" === b[f] ? g.length : b[f], m = g[c] =
            f < e ? g[c] || (b[f + 1] && isNaN(b[f + 1]) ? {} : []) : a, g = m; else h.isArray(d[c]) ? d[c].push(a) : d[c] = void 0 !== d[c] ? [d[c], a] : a; else c && (d[c] = j ? void 0 : "")
        }); return d
    }
})(jQuery);
// jquery BBQ deparam - END

// jquery BBQ deparam

function RecordHitGeneric(type, regionid, officeid, agentid, listingid) {
    $.ajax({
        type: "POST",
        url: "/handlers/OfficeAgentProfileRecordHitHandler.ashx",
        data: {
            mode: "RecordHit",
            hitType: type,
            siteRegionID: regionId,
            OfficeID: officeId,
            AgentID: agentId,
            listingID: listingId
        }
    });
}

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }

    document.cookie = name + "=" + value + expires + "; path=/";
}

function ListingListGTM() {
    if (typeof (GTMScript) != 'undefined' && GTMScript == "true") {
        InsertGoogleTagManagerEvent('Listing List - Campaign', 'Contact Agent', 'Send Message');
    }
}

function ListingFullGTM(mlsid) {
    InsertGoogleTagManagerEvent('Listing Full Page View - Campaign', 'View Listing', mlsid);
}

function LandingPageMapGTM() {
    if (typeof (GTMCampaign) != 'undefined' && GTMCampaign == "true") {
        InsertGoogleTagManagerEvent('Landing Page - Campaign', 'Map Search Module', 'Map Search');
    }
}

function clear_form_elements(containerClassOrId, className) {
    $(containerClassOrId + " input." + className).each(function () {
        switch (this.type) {
            case 'password':
            case 'text':
            case 'textarea':
            case 'file':
            case 'select-one':
            case 'select-multiple':
            case 'date':
            case 'number':
            case 'tel':
            case 'email':
                this.value = '';
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
                break;
        }
    });
}


//jquery.visible.min.js
(function (e) { e.fn.visible = function (t, n, r) { var i = e(this).eq(0), s = i.get(0), o = e(window), u = o.scrollTop(), a = u + o.height(), f = o.scrollLeft(), l = f + o.width(), c = i.offset().top, h = c + i.height(), p = i.offset().left, d = p + i.width(), v = t === true ? h : c, m = t === true ? c : h, g = t === true ? d : p, y = t === true ? p : d, b = n === true ? s.offsetWidth * s.offsetHeight : true, r = r ? r : "both"; if (r === "both") return !!b && m <= a && v >= u && y <= l && g >= f; else if (r === "vertical") return !!b && m <= a && v >= u; else if (r === "horizontal") return !!b && y <= l && g >= f } })(jQuery)


//Webservices Api

var serviceBaseInstanceResolver = {
    instanceArray: [],
    getInstance: function (key) {

        var returnInstance = null;

        var instance = $.grep(serviceBaseInstanceResolver.instanceArray,
              function (instanceObj, index) {
                  return instanceObj.key === key;
              });

        if (instance != null && $.isArray(instance) && instance.length > 0) {
            returnInstance = instance[0].value;
        } else {

            var instanceRecord = {
                key: key,
                value: eval("new " + key + "()")
            };

            serviceBaseInstanceResolver.instanceArray.push(instanceRecord);

            returnInstance = instanceRecord.value;
        }

        return returnInstance;
    }
};

function ServiceBase(urlRoot, serviceKey) {
    this.root = urlRoot;
    this.methodName = "";
    this.serviceKey = serviceKey;
    this.getUrl = function () {
        return this.root + "/" + this.methodName;
    };
    //this.data = null;

    this.get = function (data) {
        var endpoint = this.getUrl();

        return $.ajax({
            url: endpoint,
            method: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: data != null ? JSON.stringify(data) : null,
            async: true
        });
    };

    this.post = function (data) {
        var endpoint = this.getUrl();

        return $.ajax({
            url: endpoint,
            method: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: data != null ? JSON.stringify(data) : null,
            async: false
        });
    };

    this.postAsync = function (data) {
        var endpoint = this.getUrl();

        return $.ajax({
            url: endpoint,
            method: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: data != null ? JSON.stringify(data) : null,
            async: true
        });
    };
};


ServiceBase.getResponseValueObj = function(dataResponse) {
    var response = dataResponse;
    response.value = dataResponse.d;
    return response;
};

ServiceBase.toDataViewResponse = function(dataResponse) {
    var response = dataResponse;

    response.value = {
        Rows: JSON.parse(dataResponse.d)
    };

    return response;
};


var SmartModuleProfileContactService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/SmartModuleProfileContactService.asmx");

    this.submitContact = function (strFromEmail
            , strFromName, body, regionID, strSubject
            , strToEmail, strToName, strCCEmail, strCCName
            , strBCCEmail, strBCCName, HitsofficeID
            , submittedForAgentID, AgentIDToSaveAgenda, firstName
            , lastName, phone, request, email, HostURL
            , listingKey, listingID, siteId, hdnSpamFilterID, hdnSpamFilterValue
            , salutation, street, city, postalCode, triggerCaptchaSubmit
            , captchaChallenge, captchaResponse) {
        this.methodName = "SubmitContact";
        var data = {
            strFromEmail : strFromEmail, 
            strFromName : strFromName, 
            body : body, 
            regionID: regionID, 
            strSubject : strSubject, 
            strToEmail : strToEmail, 
            strToName : strToName, 
            strCCEmail : strCCEmail, 
            strCCName : strCCName, 
            strBCCEmail : strBCCEmail, 
            strBCCName : strBCCName, 
            HitsofficeID : HitsofficeID, 
            submittedForAgentID : submittedForAgentID, 
            AgentIDToSaveAgenda : AgentIDToSaveAgenda, 
            firstName : firstName, 
            lastName : lastName, 
            phone : phone, 
            request : request, 
            email : email, 
            HostURL : HostURL, 
            listingKey : listingKey, 
            listingID : listingID, 
            siteId : siteId, 
            hdnSpamFilterID : hdnSpamFilterID, 
            hdnSpamFilterValue : hdnSpamFilterValue, 
            salutation : salutation, 
            street : street, 
            city : city, 
            postalCode : postalCode, 
            triggerCaptchaSubmit : triggerCaptchaSubmit, 
            captchaChallenge : captchaChallenge, 
            captchaResponse : captchaResponse
        };

        return this.post(data);
    };

    this.sendProfileContactEmail = function (strFromEmail
            , strFromName, body, regionID, strSubject
            , strToEmail, strToName, strCCEmail, strCCName
            , strBCCEmail, strBCCName, HitsofficeID
            , submittedForAgentID, AgentIDToSaveAgenda, firstName
            , lastName, phone, request, email, HostURL
            , listingKey, listingID, siteId, hdnSpamFilterID, hdnSpamFilterValue
            , salutation, street, city, postalCode) {
        this.methodName = "SendProfileContactEmail";
        var data = {
            strFromEmail: strFromEmail,
            strFromName: strFromName,
            body: body,
            regionID: regionID,
            strSubject: strSubject,
            strToEmail: strToEmail,
            strToName: strToName,
            strCCEmail: strCCEmail,
            strCCName: strCCName,
            strBCCEmail: strBCCEmail,
            strBCCName: strBCCName,
            HitsofficeID: HitsofficeID,
            submittedForAgentID: submittedForAgentID,
            AgentIDToSaveAgenda: AgentIDToSaveAgenda,
            firstName: firstName,
            lastName: lastName,
            phone: phone,
            request: request,
            email: email,
            HostURL: HostURL,
            listingKey: listingKey,
            listingID: listingID,
            siteId: siteId,
            hdnSpamFilterID: hdnSpamFilterID,
            hdnSpamFilterValue: hdnSpamFilterValue,
            salutation: salutation,
            street: street,
            city: city,
            postalCode: postalCode
        };

        return this.post(data);
    }
};

SmartModuleProfileContactService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("SmartModuleProfileContactService");
};

//var SmartModuleFullMyFavouritesService = function () {
//    this.base = ServiceBase;
//    this.base("/Webservices/SmartModuleFullMyFavouritesService.asmx");

//    this.updateDataGrid = function (remFavText, noFavText, maxFavs, favCookieExp, langMF, encLangMF, formatRegionId) {
//        this.methodName = "UpdateDataGrid";
//        var data = {
//            removeFavourite: remFavText,
//            noFavourites: noFavText,
//            MaxListings: maxFavs,
//            CookieExpDays: favCookieExp,
//            Lang: langMF,
//            EncLang: encLangMF,
//            FormatRegionID: formatRegionId
//        };

//        return this.post(data);
//    };

//    this.isMyFavourite = function (listingKey) {
//        this.methodName = "IsMyFavourite";
//        var data = {
//            ListingKey: listingKey
//        };

//        return this.post(data);
//    }
//};

var SmartModuleMyRecentlyViewedService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/SmartModuleRecentlyViewedService.asmx");

    this.updateDataGrid = function (currentSiteId, noRecentlyViewed, MaxListings, CookieExpDays, Lang, EncLang, FormatRegionID) {
        this.methodName = "UpdateDataGrid";
        var data = {
            currentSiteId : currentSiteId,
            noRecentlyViewed: noRecentlyViewed,
            MaxListings: MaxListings,
            CookieExpDays: CookieExpDays,
            Lang: Lang,
            EncLang: EncLang,
            FormatRegionID: FormatRegionID
        };

        return this.post(data);
    };

    this.updateDataGrid_Async = function (currentSiteId, noRecentlyViewed, MaxListings, CookieExpDays, Lang, EncLang, FormatRegionID) {
        this.methodName = "UpdateDataGrid";
        var data = {
            currentSiteId : currentSiteId,
            noRecentlyViewed: noRecentlyViewed,
            MaxListings: MaxListings,
            CookieExpDays: CookieExpDays,
            Lang: Lang,
            EncLang: EncLang,
            FormatRegionID: FormatRegionID
        };

        return this.postAsync(data);
    };

    this.updateDataGridListingFull = function (currentSiteId, noRecentlyViewed, MaxListings, CookieExpDays, Lang, EncLang, FormatRegionID) {
        this.methodName = "UpdateDataGridListingFull";
        var data = {
            currentSiteId: currentSiteId,
            noRecentlyViewed: noRecentlyViewed,
            MaxListings: MaxListings,
            CookieExpDays: CookieExpDays,
            Lang: Lang,
            EncLang: EncLang,
            FormatRegionID: FormatRegionID
        };

        return this.post(data);
    };

    this.updateDataGridListingFull_Async = function (currentSiteId, noRecentlyViewed, MaxListings, CookieExpDays, Lang, EncLang, FormatRegionID) {
        this.methodName = "UpdateDataGridListingFull";
        var data = {
            currentSiteId: currentSiteId,
            noRecentlyViewed: noRecentlyViewed,
            MaxListings: MaxListings,
            CookieExpDays: CookieExpDays,
            Lang: Lang,
            EncLang: EncLang,
            FormatRegionID: FormatRegionID
        };

        return this.postAsync(data);
    };

    this.adPropertyToRecentlyViewed = function (listingKey, MaxListings, CookieExpDays, Lang, EncLang) {
        this.methodName = "AddPropertyToRecentlyViewed";
        var data = {
            ListingKey: listingKey,
            MaxListings: MaxListings,
            CookieExpDays: CookieExpDays,
            Lang: Lang,
            EncLang: EncLang
        };

        return this.post(data);
    };

    this.isRecentlyViewed = function (listingKey) {
        this.methodName = "IsRecentlyViewed";
        var data = {
            ListingKey: listingKey
        };

        return this.post(data);
    }
};

var SmartModuleFullMyFavouritesService = function () 
{
    this.base = ServiceBase;
    this.base("/Webservices/SmartModuleFullMyFavouritesService.asmx");

    this.updateDataGrid = function (currentSiteId, remFavText, noFavText, maxFavs, favCookieExp, langMF, encLangMF, formatRegionId) {
        this.methodName = "UpdateDataGrid";
        var data = {
            currentSiteId: currentSiteId,
            removeFavourite: remFavText,
            noFavourites: noFavText,
            MaxListings: maxFavs,
            CookieExpDays: favCookieExp,
            Lang: langMF,
            EncLang: encLangMF,
            FormatRegionID: formatRegionId
        };

        return this.post(data);
    };

    this.updateDataGrid_Async = function (currentSiteId, remFavText, noFavText, maxFavs, favCookieExp, langMF, encLangMF, formatRegionId) {
        this.methodName = "UpdateDataGrid";
        var data = {
            currentSiteId : currentSiteId,
            removeFavourite: remFavText,
            noFavourites: noFavText,
            MaxListings: maxFavs,
            CookieExpDays: favCookieExp,
            Lang: langMF,
            EncLang: encLangMF,
            FormatRegionID: formatRegionId
        };

        return this.postAsync(data);
    };

    this.isMyFavourite = function (listingKey) {
        this.methodName = "IsMyFavourite";
        var data = {
            ListingKey: listingKey
        };

        return this.post(data);
    }
};

var ListingFullHeaderService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/LstingFullHeaderService.asmx");

    this.refineSearch = function (currentSiteId, paramString) {
        this.methodName = "RefineSearch";
        var data = {
            currentSiteId: currentSiteId, 
            paramString: paramString
        };

        return this.post(data);
    }
};

var MainWebService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/MainWebService.asmx");

    this.getTranslations = function (TranslationManagerId, TranslationItemId, DatabaseConnectionName, TranslationGroupId, LanguageRequestParameterName, languageCode) {
        this.methodName = "GetTranslations";
        var data = {
            TranslationManagerId: TranslationManagerId,
            TranslationItemId: TranslationItemId,
            DatabaseConnectionName: DatabaseConnectionName,
            TranslationGroupId: TranslationGroupId,
            LanguageRequestParameterName: LanguageRequestParameterName,
            languageCode: languageCode
        };
        return this.post(data);
    };

    this.getLocations = function (currentSiteId, Like, RegionID, LanguageCode, ShowResultsWithNoListings, EncodingLanguage) {
        this.methodName = "GetLocations";
        var data = {
            currentSiteId: currentSiteId,
            Like: Like,
            RegionID: RegionID,
            LanguageCode: LanguageCode,
            ShowResultsWithNoListings: ShowResultsWithNoListings,
            EncodingLanguage: EncodingLanguage
        };
        return this.post(data);
    };

    this.getSimilarLocations = function (regionId, ShowResultsWithNoListings, searchText, noOfRowsToDisplay) {
        this.methodName = "GetSimilarLocations";
        var data = {
            regionId: regionId,
            ShowResultsWithNoListings: ShowResultsWithNoListings,
            searchText: searchText,
            noOfRowsToDisplay: noOfRowsToDisplay
        };
        return this.post(data);
    };

    this.getLocationsById = function (currentSiteId, LocationIds, RegionID, LanguageCode, ShowResultsWithNoListings, EncodingLanguage) {
        this.methodName = "GetLocationsById";
        var data = {
            currentSiteId: currentSiteId,
            LocationIds: LocationIds,
            RegionID: RegionID,
            LanguageCode: LanguageCode,
            ShowResultsWithNoListings: ShowResultsWithNoListings,
            EncodingLanguage: EncodingLanguage
        };
        return this.post(data);
    };

    this.getCountryFlagList = function (CountryID, LanguageCode) {
        this.methodName = "GetCountryFlagList";
        var data = {
            CountryID: CountryID,
            LanguageCode: CountryID
        };
        return this.post(data);
    };

    this.getRegionRows = function (RegionID, LanguageCode, MinInternetCount, OfficeAgent, EncodingLanguage) {
        this.methodName = "GetRegionRows";
        var data = {
            RegionID: RegionID,
            LanguageCode: LanguageCode,
            MinInternetCount: MinInternetCount,
            OfficeAgent: OfficeAgent,
            EncodingLanguage: EncodingLanguage
        };
        return this.post(data);
    };

    this.getProvinces = function (SiteRegionID, RegionID, RegionRowID, LanguageCode, MinInternetCount, OfficeAgent, EncodingLanguage, OfficeAgentId) {
        this.methodName = "GetProvinces";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            LanguageCode: LanguageCode,
            MinInternetCount: MinInternetCount,
            OfficeAgent: OfficeAgent,
            EncodingLanguage: EncodingLanguage,
            OfficeAgentId: OfficeAgentId
        };
        return this.post(data);
    };

    this.getProvinceList = function (SiteRegionID, RegionID, RegionRowID, LanguageCode, MinInternetCount, OfficeAgent, EncodingLanguage, OfficeAgentId) {
        this.methodName = "GetProvinceList";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            LanguageCode: LanguageCode,
            MinInternetCount: MinInternetCount,
            OfficeAgent: OfficeAgent,
            EncodingLanguage: EncodingLanguage,
            OfficeAgentId: OfficeAgentId
        };

        return this.post(data);
    };

    this.getCities = function (SiteRegionID, RegionID, RegionRowID, ProvinceID, LanguageCode, MinInternetCount, SearchType, OfficeAgent, EncodingLanguage, OfficeAgentId) {
        this.methodName = "GetCities";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            ProvinceID: ProvinceID,
            LanguageCode: LanguageCode,
            MinInternetCount: MinInternetCount,
            SearchType: SearchType,
            OfficeAgent: OfficeAgent,
            EncodingLanguage: EncodingLanguage,
            OfficeAgentId: OfficeAgentId
        };
        return this.post(data);
    };

    this.getCityList = function (SiteRegionID, RegionID, RegionRowID, ProvinceID, LanguageCode, MinInternetCount, SearchType, OfficeAgent, EncodingLanguage, OfficeAgentId) {
        this.methodName = "GetCityList";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            ProvinceID: ProvinceID,
            LanguageCode: LanguageCode,
            MinInternetCount: MinInternetCount,
            SearchType: SearchType,
            OfficeAgent: OfficeAgent,
            EncodingLanguage: EncodingLanguage,
            OfficeAgentId: OfficeAgentId
        };
        return this.post(data);
    };

    this.getLocalZones = function (SiteRegionID, RegionID, RegionRowID, ProvinceID, CityID, LanguageCode, EncodingLanguage, OfficeAgent) {
        this.methodName = "GetLocalZones";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            ProvinceID: ProvinceID,
            CityID: CityID,
            LanguageCode: LanguageCode,
            EncodingLanguage: EncodingLanguage,
            OfficeAgent: OfficeAgent
        };
        return this.post(data);
    };

    this.getLocalZonesE = function (SiteRegionID, RegionID, RegionRowID, ProvinceID, CityID, LanguageCode, EncodingLanguage, OfficeAgent, OfficeAgentID) {
        this.methodName = "GetLocalZonesE";
        var data = {
            SiteRegionID: SiteRegionID,
            RegionID: RegionID,
            RegionRowID: RegionRowID,
            ProvinceID: ProvinceID,
            CityID: CityID,
            LanguageCode: LanguageCode,
            EncodingLanguage: EncodingLanguage,
            OfficeAgent: OfficeAgent,
            OfficeAgentID: OfficeAgentID
        };
        return this.post(data);
    };

    this.getPropertyTypes = function (RegionID, LanguageCode, ComRes) {
        this.methodName = "GetPropertyTypes";
        var data = {
            RegionID: RegionID,
            LanguageCode: LanguageCode,
            ComRes: ComRes
        };
        return this.post(data);
    };

    this.getRegionURL = function (regionID) {
        this.methodName = "GetRegionURL";
        var data = {
            regionID: regionID
        };
        return this.post(data);
    };

    this.getLanguagesSpokenByRegion = function (RegionID, LanguageCode, EncodingLanguage) {
        this.methodName = "GetLanguagesSpokenByRegion";
        var data = {
            RegionID: RegionID,
            LanguageCode: LanguageCode,
            EncodingLanguage: EncodingLanguage
        };
        return this.post(data);
    };

    this.isRegionSlingshot = function (regionID) {
        this.methodName = "IsRegionSlingshot";
        var data = {
            regionID: regionID
        };
        return this.post(data);
    };

    this.getListingPhotos = function (listingImageKey) {
        this.methodName = "GetListingPhotos";
        var data = {
            listingImageKey: listingImageKey
        };
        return this.post(data);
    };

    this.getDevelopmentList = function (CountryID, ProvinceID, EncodingLanguage) {
        this.methodName = "GetDevelopmentList";
        var data = {
            CountryID: CountryID,
            ProvinceID: ProvinceID,
            EncodingLanguage: EncodingLanguage
        };
        return this.post(data);
    };

    this.getAgentsFromOfficeIds = function (officeIds, includeMacroOffice, groupMacroOffice, ownerOfficeId) {
        this.methodName = "GetAgentsFromOfficeIds";
        var data = {
            officeIds: officeIds,
            includeMacroOffice: includeMacroOffice,
            groupMacroOffice: groupMacroOffice,
            ownerOfficeId: ownerOfficeId
        };
        return this.post(data);
    };

    this.getAgentListHtmlFromOfficeIds = function (officeIds, includeMacroOffice, groupMacroOffice, ownerOfficeId) {
        this.methodName = "GetAgentListHtmlFromOfficeIds";
        var data = {
            officeIds: officeIds,
            includeMacroOffice: includeMacroOffice,
            groupMacroOffice: groupMacroOffice,
            ownerOfficeId: ownerOfficeId
        };
        return this.post(data);
    };

    this.saveBuyerMatchFeedback = function (buyerMatchKey, listingkey, rating, exceptionid, comments) {
        this.methodName = "SaveBuyerMatchFeedback";
        var data = {
            buyerMatchKey: buyerMatchKey,
            listingkey: listingkey,
            rating: rating,
            exceptionid: exceptionid,
            comments: comments
        };
        return this.post(data);
    };


    this.saveBuyerMatchFeedbackAgentConnectLikeDislike = function (webUserId, listingKey, exceptionId) {
        this.methodName = "SaveBuyerMatchFeedbackAgentConnectLikeDislike";
        var data = {
            webUserId: webUserId,
            listingKey: listingKey,
            exceptionId: exceptionId
        };
        return this.postAsync(data);
    };

    this.saveBuyerMatchFeedbackAgentConnectComment = function (webUserId, listingKey, rating, exceptionId, comments) {
        this.methodName = "SaveBuyerMatchFeedbackAgentConnectComment";
        var data = {
            webUserId: webUserId,
            listingKey: listingKey,
            rating: rating,
            exceptionId: exceptionId,
            comments: comments
        };
        return this.postAsync(data);
    };


    this.saveBuyerMatchFeedbackByWebUserId = function (webUserId, listingkey, rating, exceptionid, comments) {
        this.methodName = "SaveBuyerMatchFeedbackByWebUserId";
        var data = {
            webUserId: webUserId,
            listingkey: listingkey,
            rating: rating,
            exceptionid: exceptionid,
            comments: comments
        };
        return this.post(data);
    };

    this.recordHit = function (officeID, agentID, listingID, hitType, notes) {
        this.methodName = "RecordHit";
        var data = {
            officeID: officeID,
            agentID: agentID,
            listingID: listingID,
            hitType: hitType,
            notes: notes
        };
        return this.post(data);
    };

    this.recordHit_Async = function (officeID, agentID, listingID, hitType, notes) {
        this.methodName = "RecordHit";
        var data = {
            officeID: officeID,
            agentID: agentID,
            listingID: listingID,
            hitType: hitType,
            notes: notes
        };
        return this.postAsync(data);
    };

    this.getPriceRange = function (currencyCode, transactionType, translation, regionID) {
        this.methodName = "GetPriceRange";
        var data = {
            currencyCode: currencyCode,
            transactionType: transactionType,
            translation: translation,
            regionID: regionID
        };
        return this.post(data);
    };

    this.getPriceRange_Async = function (currencyCode, transactionType, translation, regionID) {
        this.methodName = "GetPriceRange";
        var data = {
            currencyCode: currencyCode,
            transactionType: transactionType,
            translation: translation,
            regionID: regionID
        };
        return this.postAsync(data);
    };

    this.echo = function (text) {
        this.methodName = "Echo";

        var data = {
            text: text
        };

        return this.postAsync(data);
    };

    this.saveBuyerMatchComment = function (bmkey, lstkey, exceptionid, comment) {
        this.methodName = "SaveBuyerMatchComment";

        var data = {
            bmKey: bmkey,
            lstKey: lstkey,
            exceptionId: exceptionid,
            comment: comment
        };
        return this.postAsync(data);
    };

}

var SmartModuleLanguageSelectorService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/SmartModuleLanguageSelectorService.asmx");

    this.setHeight = function(height) {
        this.methodName = "SetHeight";
        var data = {
            height: height
        };

        return this.post(data);
    };
};

var ListingSearchService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/ListingSearchService.asmx");

    this.getCountAJAX = function (Searchkey, currentSiteId, sParamType, sParamNewValue) {
        this.methodName = "GetCountAJAX";
        var data = {
            Searchkey: Searchkey, 
            currentSiteId: currentSiteId, 
            sParamType: sParamType, 
            sParamNewValue: sParamNewValue
        };
        return this.post(data);
    }
    this.updateCountAJAX = function (Searchkey, currentSiteId, sParamType, sParamNewValue) {
        this.methodName = "updateCountAJAX";
        var data = {
            Searchkey: Searchkey, 
            currentSiteId: currentSiteId, 
            sParamType: sParamType, 
            sParamNewValue: sParamNewValue
        };
        return this.post(data);
    }
};

var AddressCheckerService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/AddressCheckerService.asmx");

    this.getProvinces = function (Statement, RegionID, LanguageCode) {
        this.methodName = "GetProvinces";
        var data = {
            Statement: Statement, 
            RegionID: RegionID, 
            LanguageCode: LanguageCode
        };
        return this.post(data);
    }
    this.getCities = function (Statement, RegionID, LanguageCode) {
        this.methodName = "GetCities";
        var data = {
            Statement: Statement,
            RegionID: RegionID,
            LanguageCode: LanguageCode
        };
        return this.post(data);
    }
};

var FreeTextHelperService = function() {
    this.base = ServiceBase;
    this.base("/Webservices/FreeTextHelperService.asmx");

    this.getSimilarLocations_Async = function(regionId, searchText, LanguageCode, exclude, IsSellerSearch) {
        this.methodName = "GetSimilarLocations";
        var data = {
            regionId: regionId,
            searchText: searchText,
            LanguageCode: LanguageCode,
            exclude: exclude,
            IsSellerSearch: IsSellerSearch
        };

        return this.postAsync(data);
    };

};


var RecruitmentPageContactFormService = function() {
    this.base = ServiceBase;
    this.base("/Webservices/RecruitmentPageContactFormService.asmx");

    this.submitForm_Async = function(name, email, phone, zipCode, message, officeId, officeName, city, recapchaToken) {
        this.methodName = "SubmitForm";
        var inputobj = {
            name: name,
            email: email,
            phone: phone,
            zipCode: zipCode,
            message: message,
            officeId: officeId,
            officeName: officeName,
            city: city,
            recapchaToken: recapchaToken
        };

        var data = {
            input: inputobj
        };

        return this.postAsync(data);
    };
};

var ListingFullContactMeService = function() {
    this.base = ServiceBase;
    this.base("/Webservices/ListingFullContactMeService.asmx");

    this.submitListingFullContactMe = function (title, fullName, lastName, email, phone, message, comments, captchaResponse, street, city, postalCode, listingKey, alternateAgentId) {
        this.methodName = "SubmitContactMeForm";

        var data = {
            title: title,
            fullName: fullName,
            lastName:lastName,
            email: email,
            phone: phone,
            message:message,
            comments: comments,
            captchaResponse: captchaResponse,
            street: street,
            city: city,
            postalCode: postalCode,
            listingKey: listingKey,
            sAgentID: alternateAgentId
        };

        return this.postAsync(data);
    };


};


var SmartModuleFooterService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/SmartModuleFooterService.asmx");

    this.getDynamicFooterLinks = function (footerLinksArgs) {
        this.methodName = "GetDynamicFooterLinks";

        var data = {
            input: {
                CityIds: footerLinksArgs.cityIds,
                ProvinceIds: footerLinksArgs.provinceIds,
                RegionRowIds: footerLinksArgs.regionRowIds,
                CountryIds: footerLinksArgs.countryIds,
                ListingKey: footerLinksArgs.listingKey,
                OfficeId: footerLinksArgs.officeId,
                AgentId: footerLinksArgs.agentId,
                Type: footerLinksArgs.type,
                Cr: footerLinksArgs.cr,
                MlsId: footerLinksArgs.mlsid
    }
        };

        return this.postAsync(data);
    };
};

var MyProfileBuyerMatchService = function() {
    this.base = ServiceBase;
    this.base("/Webservices/MyProfileBuyerMatchService.asmx");
    this.getNewView = function (webUserId) {
        this.methodName = "GetNewView";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.getPagedView = function(webUserId, pageNum, paginationContext) {
        this.methodName = "GetPagedView";

        var data = {
            webUserId: webUserId,
            pageNum: pageNum,
            paginationContext: paginationContext
        };

        return this.postAsync(data);
    };

    this.getBuyerMatchCriteria = function (webUserId) {
        this.methodName = "GetBuyerMatchCriteria";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.getAgentConnectMyListings = function (webUserId, listingsForSaleKeys) {
        this.methodName = "GetAgentConnectMyListings";

        var data = {
            webUserId: webUserId,
            listingsForSaleKeys : listingsForSaleKeys
        };

        return this.postAsync(data);
    };

    this.unsubscribeAutomaticBuyerMatch = function (buyerMatchKey, buyerMatchId, agentId, webUserId) {
        this.methodName = "UnsubscribeAutomaticBuyerMatch";

        var data = {
            buyerMatchKey: buyerMatchKey,
            buyerMatchId: buyerMatchId,
            agentId: agentId,
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

};

MyProfileBuyerMatchService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("MyProfileBuyerMatchService");
};


var AgentConnectManageMyAgentsService = function () {
    this.base = ServiceBase;
    this.base("/Webservices/AgentConnectManageMyAgentsService.asmx");
    this.getMyAgents = function (webUserId) {
        this.methodName = "GetMyAgents";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.makePreferredAgent = function (webUserId, agentId) {
        this.methodName = "MakePreferredAgent";

        var data = {
            webUserId: webUserId,
            agentId: agentId
        };

        return this.postAsync(data);
    };

    this.removeMyAgent = function (webUserId, agentId, reasonText) {
        this.methodName = "RemoveMyAgent";

        var data = {
            webUserId: webUserId,
            agentId: agentId,
            reasonText: reasonText
        };

        return this.postAsync(data);
    };

    this.submitContactForm = function (webUserId, agentId, commentText) {
        this.methodName = "SubmitContactForm";

        var data = {
            webUserId: webUserId,
            agentId: agentId,
            commentText: commentText
        };

        return this.postAsync(data);
    };

    this.sendListingToMyAgent = function (webUserId, preferredAgentId, listingAgentId, mlsId) {
        this.methodName = "SendListingToMyAgent";

        var data = {
            webUserId: webUserId,
            preferredAgentId: preferredAgentId,
            listingAgentId: listingAgentId,
            mlsId: mlsId
        }
        return this.postAsync(data);
    };

    this.getConnectedToMyAgent = function (webUserId, agentId) {
        this.methodName = "GetConnectedToMyAgent";

        var data = {
            webUserId: webUserId,
            agentId: agentId
        }

        return this.postAsync(data);
    };

    this.getNotConnectedScreen = function (webUserId) {
        this.methodName = "GetNotConnectedScreen";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.getAgentConnectUnknownScreen = function (webUserId) {
        this.methodName = "GetAgentConnectUnknownScreen";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };
}

AgentConnectManageMyAgentsService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("AgentConnectManageMyAgentsService");
};

var MyProfileSignInService = function() {
    this.base = ServiceBase;
    this.base("/Webservices/MyProfileSignInService.asmx");
    this.getAgentConnectGetConnectedScreen = function (webUserId) {
        this.methodName = "GetAgentConnectGetConnectedScreen";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.getAgentConnectConnectedScreen = function (webUserId) {
        this.methodName = "GetAgentConnectConnectedScreen";

        var data = {
            webUserId: webUserId
        };

        return this.postAsync(data);
    };

    this.saveAgentConnectPreferences = function (webUserId, myFavourites, mySavedSearches, myRecentlyViewed) {
        this.methodName = "SaveAgentConnectPreferences";

        var data = {
            webUserId: webUserId,
            myFavourites: myFavourites, 
            mySavedSearches: mySavedSearches, 
            myRecentlyViewed: myRecentlyViewed
        };

        return this.postAsync(data);
    };

};

MyProfileSignInService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("MyProfileSignInService");
};



var DynamicFooterLinks = {
    loadLinks: function (footerLinksArgs) {
        window._dynamicFooterLinksLoaded = true;
        SmartModuleFooterService.instance().getDynamicFooterLinks(footerLinksArgs)
            .done(function (result) {
                $('#DynamicFooterLinks').html(result.d);
            });
    },
    getDynamicFooterLinksArgs: function() {
        var args = {};
        args.cityIds = [];
        args.provinceIds = [];
        args.regionRowIds = [];
        args.countryIds = [];
        args.listingKey = null;
        args.officeId = null;
        args.agentId = null;
        args.type = null;
        args.cr = null;
        args.mlsid = null;
        return args;
    }
};

SmartModuleFooterService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("SmartModuleFooterService");
};

ListingFullContactMeService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("ListingFullContactMeService");
};

RecruitmentPageContactFormService.instance = function () {
    return new serviceBaseInstanceResolver.getInstance("RecruitmentPageContactFormService");
};

FreeTextHelperService.instance = function() {
    return new serviceBaseInstanceResolver.getInstance("FreeTextHelperService");
};

SmartModuleFullMyFavouritesService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("SmartModuleFullMyFavouritesService");
};

SmartModuleMyRecentlyViewedService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("SmartModuleMyRecentlyViewedService");
};

SmartModuleFullMyFavouritesService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("SmartModuleFullMyFavouritesService");
};

ListingFullHeaderService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("ListingFullHeaderService");
};

MainWebService.instance = function () {
    return new serviceBaseInstanceResolver
        .getInstance("MainWebService");
};

SmartModuleLanguageSelectorService.instance = function() {
    return new serviceBaseInstanceResolver
        .getInstance("SmartModuleLanguageSelectorService");
};

ListingSearchService.instance = function() {
    return new serviceBaseInstanceResolver
        .getInstance("ListingSearchService");
};

AddressCheckerService.instance = function() {
    return new serviceBaseInstanceResolver
        .getInstance("AddressCheckerService");
};

// prototype.js
Object.extend = function (dest, source, replace) {
    for (var prop in source) {
        if (replace == false && dest[prop] != null) { continue; }
        dest[prop] = source[prop];
    }
    return dest;
};

Object.extend(Function.prototype, {
    apply: function (o, a) {
        var r, x = "__fapply";
        if (typeof o != "object") { o = {}; }
        o[x] = this;
        var s = "r = o." + x + "(";
        for (var i = 0; i < a.length; i++) {
            if (i > 0) { s += ","; }
            s += "a[" + i + "]";
        }
        s += ");";
        eval(s);
        delete o[x];
        return r;
    },
    bind: function (o) {
        if (!Function.__objs) {
            Function.__objs = [];
            Function.__funcs = [];
        }
        var objId = o.__oid;
        if (!objId) {
            Function.__objs[objId = o.__oid = Function.__objs.length] = o;
        }

        var me = this;
        var funcId = me.__fid;
        if (!funcId) {
            Function.__funcs[funcId = me.__fid = Function.__funcs.length] = me;
        }

        if (!o.__closures) {
            o.__closures = [];
        }

        var closure = o.__closures[funcId];
        if (closure) {
            return closure;
        }

        o = null;
        me = null;

        return Function.__objs[objId].__closures[funcId] = function () {
            return Function.__funcs[funcId].apply(Function.__objs[objId], arguments);
        };
    }
}, false);

Object.extend(Array.prototype, {
    push: function (o) {
        this[this.length] = o;
    },
    addRange: function (items) {
        if (items.length > 0) {
            for (var i = 0; i < items.length; i++) {
                this.push(items[i]);
            }
        }
    },
    clear: function () {
        this.length = 0;
        return this;
    },
    shift: function () {
        if (this.length == 0) { return null; }
        var o = this[0];
        for (var i = 0; i < this.length - 1; i++) {
            this[i] = this[i + 1];
        }
        this.length--;
        return o;
    }
}, false);

Object.extend(String.prototype, {
    trimLeft: function () {
        return this.replace(/^\s*/, "");
    },
    trimRight: function () {
        return this.replace(/\s*$/, "");
    },
    trim: function () {
        return this.trimRight().trimLeft();
    },
    endsWith: function (s) {
        if (this.length == 0 || this.length < s.length) { return false; }
        return (this.substr(this.length - s.length) == s);
    },
    startsWith: function (s) {
        if (this.length == 0 || this.length < s.length) { return false; }
        return (this.substr(0, s.length) == s);
    },
    split: function (c) {
        var a = [];
        if (this.length == 0) return a;
        var p = 0;
        for (var i = 0; i < this.length; i++) {
            if (this.charAt(i) == c) {
                a.push(this.substring(p, i));
                p = ++i;
            }
        }
        a.push(s.substr(p));
        return a;
    }
}, false);

Object.extend(String, {
    format: function (s) {
        for (var i = 1; i < arguments.length; i++) {
            s = s.replace("{" + (i - 1) + "}", arguments[i]);
        }
        return s;
    },
    isNullOrEmpty: function (s) {
        if (s == null || s.length == 0) {
            return true;
        }
        return false;
    }
}, false);

if (typeof addEvent == "undefined")
    addEvent = function (o, evType, f, capture) {
        if (o == null) { return false; }
        if (o.addEventListener) {
            o.addEventListener(evType, f, capture);
            return true;
        } else if (o.attachEvent) {
            var r = o.attachEvent("on" + evType, f);
            return r;
        } else {
            try { o["on" + evType] = f; } catch (e) { }
        }
    };

if (typeof removeEvent == "undefined")
    removeEvent = function (o, evType, f, capture) {
        if (o == null) { return false; }
        if (o.removeEventListener) {
            o.removeEventListener(evType, f, capture);
            return true;
        } else if (o.detachEvent) {
            o.detachEvent("on" + evType, f);
        } else {
            try { o["on" + evType] = function () { }; } catch (e) { }
        }
    };


function OnGoogleRecaptchaLoaded() {
    $(window).trigger('OnGoogleRecaptchaLoaded');
}

$(window).scroll(function () {
    if ($(this).scrollTop() > 50) {

        $('.navbar').addClass('shrink');
        $('#TopNav').addClass('top-nav-shrink');
        if (document.getElementById("TopNav") == null || document.getElementById("TopNav").getElementsByClassName('container') == "undefined" || document.getElementById("TopNav").getElementsByClassName('container').length <= 0) {
            $('#TopNav').css('display', 'none');
        }
        $('.navbar-brand').addClass('menu-shrink');
        $('.navbar-toggle').addClass('menu-shrink');
        $('#Header').addClass('header-shrink');
        $('.userdropdown').addClass('userdrop-shrink');
        $('.nav-brand').addClass('logo-shrink');
        $('.btn-contact').addClass('btn-shrink');
        $('.titlebar-listfull-price').addClass('currency-shrink');
        $('#TopNav h1').addClass('top-nav-title-shrink');
        $('.navbar .container').addClass('nav-container-shrink');
        $('#TopNav .recfav-links span').addClass('recfav-shrink');
        $('.price-type').addClass('currency-shrink');
        $('.nav-name').addClass('nav-name-shrink');
        $('.nav-logo').addClass('small-logo');
        $('.btns-topnav').addClass('properties-btn');
        $('.nav-logo-res').addClass('logo-down');
        $('.office-title-name').addClass('hideit');
        $('.office-location-name').addClass('hideit');
        $('.office-phone-number').addClass('hideit');
        $('.nav-logo-col').addClass('col-logo-shrink');
        $('.nav-logo-comm').addClass('comm-logo-shrink');
        $('.navbar-header .dropdown-toggle').css('display', 'none');
        $('.no-user').addClass('user-shrink');
        $('.registered-user').addClass('user-shrink');
        $('.hdr-logo').addClass('swiss-logo-res');
        $('.dropdown-toggle').addClass('toggle-fix');
     
        
    } else  {

        $('.navbar').removeClass('shrink');
        $('#TopNav').removeClass('top-nav-shrink');
        $('.navbar-brand').removeClass('menu-shrink');
        $('.navbar-toggle').removeClass('menu-shrink');
        $('#Header').removeClass('header-shrink');
        $('.userdropdown').removeClass('userdrop-shrink');
        $('.nav-brand').removeClass('logo-shrink');
        $('.btn-contact').removeClass('btn-shrink');
        $('.titlebar-listfull-price').removeClass('currency-shrink');
        $('#TopNav h1').removeClass('top-nav-title-shrink');
        $('.navbar .container').removeClass('nav-container-shrink');
        $('#TopNav .recfav-links span').removeClass('recfav-shrink');
        $('.price-type').removeClass('currency-shrink');
        $('.nav-name').removeClass('nav-name-shrink');
        $('.nav-logo').removeClass('small-logo');
        $('.btns-topnav').removeClass('properties-btn');
        $('.nav-logo-res').removeClass('logo-down');
        $('.office-title-name').removeClass('hideit');
        $('.office-location-name').removeClass('hideit');
        $('.office-phone-number').removeClass('hideit');
        $('.nav-logo-col').removeClass('col-logo-shrink');
        $('.nav-logo-comm').removeClass('comm-logo-shrink');
        $('.navbar-header .dropdown-toggle').css('display', 'block');
        $('.no-user').removeClass('user-shrink');
        $('.registered-user').removeClass('user-shrink');
        $('.hdr-logo').removeClass('swiss-logo-res');
        $('.dropdown-toggle').removeClass('toggle-fix');
     
    }
});


$(document).ready(function() {
    $(".nav-brand").on("click",
        function() {
            window.location.href = '/default.aspx';
        });
    $('.nav-brand').css('cursor', 'pointer');
});


function MyProfileBuyerMatch() {
    var self = this;
    self.get_BuyerMatchItemModel = function (rowModelId) {
        var bmRecord = null;

        $.each(_buyerMatchNewList,
            function(index, bm) {
                if (bm.id == rowModelId) {
                    bmRecord = bm;
                }
            });

        $.each(_buyerMatchAllList,
            function (index, bm) {
                if (bm.id == rowModelId) {
                    bmRecord = bm;
                }
            });

        $.each(_buyerMatchLikedList,
            function (index, bm) {
                if (bm.id == rowModelId) {
                    bmRecord = bm;
                }
            });


        return bmRecord.val;
    };
    self.showNewProperties = function () {
        $("#buyerMatch_new").show();
        $("#tab_buyerMatchNew").removeClass("active");
        $("#tab_buyerMatchNew").addClass("active");
        $("#buyerMatch_liked").hide();
        $("#tab_buyerMatchLiked").removeClass("active");
        $("#buyerMatch_all").hide();
        $("#tab_buyerMatchAll").removeClass("active");

        self.loadPaginationView(window.webUserId, 1, "BmNew");
    };
    self.showLikedProperties = function () {
        $("#buyerMatch_new").hide();
        $("#tab_buyerMatchNew").removeClass("active");
        $("#buyerMatch_liked").show();
        $("#tab_buyerMatchNew").removeClass("active");
        $("#tab_buyerMatchLiked").addClass("active");
        $("#buyerMatch_all").hide();
        $("#tab_buyerMatchAll").removeClass("active");

        self.loadPaginationView(window.webUserId, 1, "BmLiked");
    };
    self.showAllProperties = function () {
        $("#buyerMatch_new").hide();
        $("#tab_buyerMatchNew").removeClass("active");
        $("#buyerMatch_liked").hide();
        $("#tab_buyerMatchLiked").removeClass("active");
        $("#buyerMatch_all").show();
        $("#tab_buyerMatchAll").removeClass("active");
        $("#tab_buyerMatchAll").addClass("active");


        self.loadPaginationView(window.webUserId, 1, "BmAll");
    };
    self.like_click = function (rowModelId) {
        var row = $("#" + rowModelId);

        if (row.find("#like_label").hasClass("active")) {
            row.find("#divratingcontrol").hide();
            row.find("#divtxtlkd").hide();
            row.find("#like_label").removeClass("active");
        } else {
            row.find("#divratingcontrol").show();
            row.find("#divtxtlkd").show();
            row.find("#like_label").addClass("active");
        }
        return false;
    };
    self.dislike_click = function(rowModelId) {
        var row = $("#" + rowModelId);
        if (row.find("#dislike_label").hasClass("active")) {
            row.find("#divratingcontrol").hide();
            row.find("#divtxtlkd").hide();
            row.find("#dislike_label").removeClass("active");
        } else {
            row.find("#divratingcontrol").hide();
            row.find("#divtxtlkd").show();
            row.find("#dislike_label").addClass("active");
        }

        return false;
    };

    self.SaveBuyerMatchFeedbackLikeDislike = function (rowModelId, listingKey, exceptionId) {
        var webUserId = window.webUserId;

        MainWebService.instance().saveBuyerMatchFeedbackAgentConnectLikeDislike(webUserId, listingKey, exceptionId)
            .done(function (data) {
                var flag = data.d;
                if (flag) {

                    BootstrapShowModalNotification("myProfile_Notification_Success", true, 2);

                    var list = getUrlParameter("list");

                    // LIKE
                    if (exceptionId == 5) {
                        $("#bm_dislike_" + rowModelId).removeClass("btn-like-chosen");
                        $("#bm_dislike_" + rowModelId).prop("disabled", false);

                        $("#bm_like_" + rowModelId).addClass("btn-like-chosen");
                        $("#bm_like_" + rowModelId).prop("disabled", true);

                        $("#hdn_bm_comment_" + rowModelId).val("");
                        $("#bm_comment_notify_" + rowModelId).removeClass("notify-msg-like");
                        $("#bm_comments_btn_" + rowModelId).data("hiderating", "0");

                        InsertGoogleTagManagerEvent("My Property Matches page", "Like Property", "Like Button");

                        $("#bm_comments_btn_" + rowModelId).prop("disabled", false);
                        $("#bm_comments_btn_" + rowModelId).data("exceptionid", exceptionId);
                    }
                    // DISLIKE
                    else if (exceptionId == 6) {
                        $("#bm_like_" + rowModelId).removeClass("btn-like-chosen");
                        $("#bm_like_" + rowModelId).prop("disabled", false);

                        $("#bm_dislike_" + rowModelId).addClass("btn-like-chosen");
                        $("#bm_dislike_" + rowModelId).prop("disabled", true);

                        $("#bm_rating_" + rowModelId).hide();
                        $("#hdn_bm_rating_" + rowModelId).val("0");
                        $("#hdn_bm_comment_" + rowModelId).val("");
                        $("#bm_comment_notify_" + rowModelId).removeClass("notify-msg-like");
                        $("#bm_comments_btn_" + rowModelId).data("hiderating", "1");

                        InsertGoogleTagManagerEvent("My Property Matches page", "Dislike Property", "Dislike Button");

                        if (list == "Liked") {
                            self.showLikedProperties();
                        } else {
                            $("#bm_comments_btn_" + rowModelId).prop("disabled", false);
                            $("#bm_comments_btn_" + rowModelId).data("exceptionid", exceptionId);
                        }
                    }
                } else {
                    BootstrapShowModalNotification("myProfile_Notification_Failed", true, 2);
                }
            })
            .fail(function(xhr) {
                alert("saveBuyerMatchFeedbackAgentConnectLikeDislike : " + xhr);
            });
    };

    self.saveBuyerMatchFeedbackAgentConnectComment = function (rowModelId, listingKey, rating, exceptionId, comments) {
        var webUserId = window.webUserId;

        MainWebService.instance().saveBuyerMatchFeedbackAgentConnectComment(webUserId, listingKey, rating, exceptionId, comments)
            .done(function (data) {
                var flag = data.d;
                if (flag) {

                    if (rating > 0) {
                        $("#bm_rating_" + rowModelId).show();

                        var prefix = 'bm_rating_star_' + rowModelId;

                        $("[id^='" + prefix + "']").each(function() {
                            $(this).removeClass();

                            if ($(this).data("order") <= rating)
                                $(this).addClass("star-on");
                            else
                                $(this).addClass("star-off");
                        });
                    } 

                    $("#hdn_bm_rating_" + rowModelId).val(rating);
                    $("#hdn_bm_comment_" + rowModelId).val(comments);

                    BootstrapShowModalNotification("myProfile_Notification_Success", true, 2);

                    $("#bm_comment_notify_" + rowModelId).removeClass("notify-msg-like");

                    if (comments)
                        $("#bm_comment_notify_" + rowModelId).addClass("notify-msg-like");

                } else {
                    BootstrapShowModalNotification("myProfile_Notification_Failed", true, 2);
                }
            })
            .fail(function (xhr) {
                alert("saveBuyerMatchFeedbackAgentConnectComment : " + xhr);
            });
    };

    self.SaveBuyerMatchFeedback = function (rowModelId) {
        var row = $("#" + rowModelId);
        var item = self.get_BuyerMatchItemModel(rowModelId);
        var likeLbl = row.find("#like_label");
        //var dislikeLbl = row.find("#dislike_label");
        var rating = 0;
        var exceptionid = 5; //item.ExceptionId;

        if (likeLbl.hasClass("active")) {
            rating = row.find("#" + "hid_rctrl_" + rowModelId + "_Liked").val();
            exceptionid = 5;
        } else {
            exceptionid = 6;
        }

        //txtlkd
        //var bmkey = item.BuyerMatchKey;
        var lstkey = item.Listing.ListingKey;
        var comments = row.find("#txtlkd").val();
        var webUserId = window.webUserId;

        MainWebService.instance().saveBuyerMatchFeedbackByWebUserId(webUserId, lstkey, rating, exceptionid, comments).done(function (data) {
            var flag = data.d;
            if (flag) {
                toastr.success("Saved");
                self.reloadControl();
            } else {
                toastr.error("Failed");
            }
        }).fail(function (xhr) { toastr.error("Failed"); });
    };



    self.commentClick = function (rowModelId) {
        var row = $("#" + rowModelId);
        var divComment = row.find("#divComment");
        divComment.toggle();
    };


    self.loadPaginationView = function(webUserId, toPage, paginationContext) {
        ShowWaitImg();

        //switch (paginationContext) {
        //    case "BmNew":
        //        window.BmNewPageNum = toPage;
        //        break;
        //    case "BmLiked":
        //        window.BmLikedPageNum = 0;
        //        break;
        //    case "BmAll":
        //       
        //        break;
        //};

        MyProfileBuyerMatchService.instance().getPagedView(window.webUserId, toPage, paginationContext)
            .done(function (data) {
                HideWaitImg();
                switch (paginationContext) {
                    case "BmNew":
                        $("#buyerMatch_new").html(data.d);
                        break;
                    case "BmLiked":
                        $("#buyerMatch_liked").html(data.d);
                        break;
                    case "BmAll":
                        $("#buyerMatch_all").html(data.d);
                        break;
                };
            })
            .fail(function (xhr) {
                HideWaitImg();
            });
    };


    amplify.subscribe("PaginationPrevious", function (data) {
        self.loadPaginationView(window.webUserId, data.toPage, data.paginationContext);
    });

    amplify.subscribe("PaginationAdHoc", function (data) {
        self.loadPaginationView(window.webUserId, data.toPage, data.paginationContext);
    });

    amplify.subscribe("PaginationNext", function (data) {
        self.loadPaginationView(window.webUserId, data.toPage, data.paginationContext);
    });


};

function clearHash() {
    location.hash = "";
    if (window.history && window.history.pushState) {
        window.history.pushState("", "", window.location.href.split('#')[0]);
    } else {
        window.location.href = window.location.href.replace(/#.*$/, "#");
    }
}

function WebUserDropdownLoad(refurl)
{
    $.ajax({
        type: "GET",
        url: "/handlers/MyProfileLogin.ashx?Lang=" + "<%=Gryphtech.Slingshot.SlingshotAddin.RemaxRequestContext.LanguageCode %>" + refurl,
        success: function (response) {
            $("#myProfileWidget").html(response.html);
        }
    });
}

function removeURLParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts = url.split('?');
    if (urlparts.length >= 2) {

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i = pars.length; i-- > 0;) {
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }
        url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    }
    else {
        return url;
    }
}


/*!
 * Amplify 1.1.2
 *
 * Copyright 2011 - 2013 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 *
 * http://amplifyjs.com
 */
(function (e, t) { var n = [].slice, r = {}, i = e.amplify = { publish: function (e) { if (typeof e != "string") throw new Error("You must provide a valid topic to publish."); var t = n.call(arguments, 1), i, s, o, u = 0, a; if (!r[e]) return !0; i = r[e].slice(); for (o = i.length; u < o; u++) { s = i[u], a = s.callback.apply(s.context, t); if (a === !1) break } return a !== !1 }, subscribe: function (e, t, n, i) { if (typeof e != "string") throw new Error("You must provide a valid topic to create a subscription."); arguments.length === 3 && typeof n == "number" && (i = n, n = t, t = null), arguments.length === 2 && (n = t, t = null), i = i || 10; var s = 0, o = e.split(/\s/), u = o.length, a; for (; s < u; s++) { e = o[s], a = !1, r[e] || (r[e] = []); var f = r[e].length - 1, l = { callback: n, context: t, priority: i }; for (; f >= 0; f--) if (r[e][f].priority <= i) { r[e].splice(f + 1, 0, l), a = !0; break } a || r[e].unshift(l) } return n }, unsubscribe: function (e, t, n) { if (typeof e != "string") throw new Error("You must provide a valid topic to remove a subscription."); arguments.length === 2 && (n = t, t = null); if (!r[e]) return; var i = r[e].length, s = 0; for (; s < i; s++) r[e][s].callback === n && (!t || r[e][s].context === t) && (r[e].splice(s, 1), s--, i--) } } })(this), function (e, t) { function i(e, i) { n.addType(e, function (s, o, u) { var a, f, l, c, h = o, p = (new Date).getTime(); if (!s) { h = {}, c = [], l = 0; try { s = i.length; while (s = i.key(l++)) r.test(s) && (f = JSON.parse(i.getItem(s)), f.expires && f.expires <= p ? c.push(s) : h[s.replace(r, "")] = f.data); while (s = c.pop()) i.removeItem(s) } catch (d) { } return h } s = "__amplify__" + s; if (o === t) { a = i.getItem(s), f = a ? JSON.parse(a) : { expires: -1 }; if (!(f.expires && f.expires <= p)) return f.data; i.removeItem(s) } else if (o === null) i.removeItem(s); else { f = JSON.stringify({ data: o, expires: u.expires ? p + u.expires : null }); try { i.setItem(s, f) } catch (d) { n[e](); try { i.setItem(s, f) } catch (d) { throw n.error() } } } return h }) } var n = e.store = function (e, t, r) { var i = n.type; return r && r.type && r.type in n.types && (i = r.type), n.types[i](e, t, r || {}) }; n.types = {}, n.type = null, n.addType = function (e, t) { n.type || (n.type = e), n.types[e] = t, n[e] = function (t, r, i) { return i = i || {}, i.type = e, n(t, r, i) } }, n.error = function () { return "amplify.store quota exceeded" }; var r = /^__amplify__/; for (var s in { localStorage: 1, sessionStorage: 1 }) try { window[s].setItem("__amplify__", "x"), window[s].removeItem("__amplify__"), i(s, window[s]) } catch (o) { } if (!n.types.localStorage && window.globalStorage) try { i("globalStorage", window.globalStorage[window.location.hostname]), n.type === "sessionStorage" && (n.type = "globalStorage") } catch (o) { } (function () { if (n.types.localStorage) return; var e = document.createElement("div"), r = "amplify"; e.style.display = "none", document.getElementsByTagName("head")[0].appendChild(e); try { e.addBehavior("#default#userdata"), e.load(r) } catch (i) { e.parentNode.removeChild(e); return } n.addType("userData", function (i, s, o) { e.load(r); var u, a, f, l, c, h = s, p = (new Date).getTime(); if (!i) { h = {}, c = [], l = 0; while (u = e.XMLDocument.documentElement.attributes[l++]) a = JSON.parse(u.value), a.expires && a.expires <= p ? c.push(u.name) : h[u.name] = a.data; while (i = c.pop()) e.removeAttribute(i); return e.save(r), h } i = i.replace(/[^\-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-"), i = i.replace(/^-/, "_-"); if (s === t) { u = e.getAttribute(i), a = u ? JSON.parse(u) : { expires: -1 }; if (!(a.expires && a.expires <= p)) return a.data; e.removeAttribute(i) } else s === null ? e.removeAttribute(i) : (f = e.getAttribute(i), a = JSON.stringify({ data: s, expires: o.expires ? p + o.expires : null }), e.setAttribute(i, a)); try { e.save(r) } catch (d) { f === null ? e.removeAttribute(i) : e.setAttribute(i, f), n.userData(); try { e.setAttribute(i, a), e.save(r) } catch (d) { throw f === null ? e.removeAttribute(i) : e.setAttribute(i, f), n.error() } } return h }) })(), function () { function i(e) { return e === t ? t : JSON.parse(JSON.stringify(e)) } var e = {}, r = {}; n.addType("memory", function (n, s, o) { return n ? s === t ? i(e[n]) : (r[n] && (clearTimeout(r[n]), delete r[n]), s === null ? (delete e[n], null) : (e[n] = s, o.expires && (r[n] = setTimeout(function () { delete e[n], delete r[n] }, o.expires)), s)) : i(e) }) }() }(this.amplify = this.amplify || {}), function (e, t) { "use strict"; function n() { } function r(e) { return {}.toString.call(e) === "[object Function]" } function i(e) { var t = !1; return setTimeout(function () { t = !0 }, 1), function () { var n = this, r = arguments; t ? e.apply(n, r) : setTimeout(function () { e.apply(n, r) }, 1) } } e.request = function (t, s, o) { var u = t || {}; typeof u == "string" && (r(s) && (o = s, s = {}), u = { resourceId: t, data: s || {}, success: o }); var a = { abort: n }, f = e.request.resources[u.resourceId], l = u.success || n, c = u.error || n; u.success = i(function (t, n) { n = n || "success", e.publish("request.success", u, t, n), e.publish("request.complete", u, t, n), l(t, n) }), u.error = i(function (t, n) { n = n || "error", e.publish("request.error", u, t, n), e.publish("request.complete", u, t, n), c(t, n) }); if (!f) throw u.resourceId ? "amplify.request: unknown resourceId: " + u.resourceId : "amplify.request: no resourceId provided"; if (!e.publish("request.before", u)) { u.error(null, "abort"); return } return e.request.resources[u.resourceId](u, a), a }, e.request.types = {}, e.request.resources = {}, e.request.define = function (t, n, r) { if (typeof n == "string") { if (!(n in e.request.types)) throw "amplify.request.define: unknown type: " + n; r.resourceId = t, e.request.resources[t] = e.request.types[n](r) } else e.request.resources[t] = n } }(amplify), function (e, t, n) { "use strict"; var r = ["status", "statusText", "responseText", "responseXML", "readyState"], i = /\{([^\}]+)\}/g; e.request.types.ajax = function (i) { return i = t.extend({ type: "GET" }, i), function (s, o) { var u, a, f = i.url, l = o.abort, c = t.extend(!0, {}, i, { data: s.data }), h = !1, p = { readyState: 0, setRequestHeader: function (e, t) { return u.setRequestHeader(e, t) }, getAllResponseHeaders: function () { return u.getAllResponseHeaders() }, getResponseHeader: function (e) { return u.getResponseHeader(e) }, overrideMimeType: function (e) { return u.overrideMimeType(e) }, abort: function () { h = !0; try { u.abort() } catch (e) { } a(null, "abort") }, success: function (e, t) { s.success(e, t) }, error: function (e, t) { s.error(e, t) } }; a = function (e, i) { t.each(r, function (e, t) { try { p[t] = u[t] } catch (n) { } }), /OK$/.test(p.statusText) && (p.statusText = "success"), e === n && (e = null), h && (i = "abort"), /timeout|error|abort/.test(i) ? p.error(e, i) : p.success(e, i), a = t.noop }, e.publish("request.ajax.preprocess", i, s, c, p), t.extend(c, { isJSONP: function () { return /jsonp/gi.test(this.dataType) }, cacheURL: function () { if (!this.isJSONP()) return this.url; var e = "callback"; this.hasOwnProperty("jsonp") && (this.jsonp !== !1 ? e = this.jsonp : this.hasOwnProperty("jsonpCallback") && (e = this.jsonpCallback)); var t = new RegExp("&?" + e + "=[^&]*&?", "gi"); return this.url.replace(t, "") }, success: function (e, t) { a(e, t) }, error: function (e, t) { a(null, t) }, beforeSend: function (t, n) { u = t, c = n; var r = i.beforeSend ? i.beforeSend.call(this, p, c) : !0; return r && e.publish("request.before.ajax", i, s, c, p) } }), c.cache && c.isJSONP() && t.extend(c, { cache: !0 }), t.ajax(c), o.abort = function () { p.abort(), l.call(this) } } }, e.subscribe("request.ajax.preprocess", function (e, n, r) { var s = [], o = r.data; if (typeof o == "string") return; o = t.extend(!0, {}, e.data, o), r.url = r.url.replace(i, function (e, t) { if (t in o) return s.push(t), o[t] }), t.each(s, function (e, t) { delete o[t] }), r.data = o }), e.subscribe("request.ajax.preprocess", function (e, n, r) { var i = r.data, s = e.dataMap; if (!s || typeof i == "string") return; t.isFunction(s) ? r.data = s(i) : (t.each(e.dataMap, function (e, t) { e in i && (i[t] = i[e], delete i[e]) }), r.data = i) }); var s = e.request.cache = { _key: function (e, t, n) { function s() { return n.charCodeAt(i++) << 24 | n.charCodeAt(i++) << 16 | n.charCodeAt(i++) << 8 | n.charCodeAt(i++) << 0 } n = t + n; var r = n.length, i = 0, o = s(); while (i < r) o ^= s(); return "request-" + e + "-" + o }, _default: function () { var e = {}; return function (t, n, r, i) { var o = s._key(n.resourceId, r.cacheURL(), r.data), u = t.cache; if (o in e) return i.success(e[o]), !1; var a = i.success; i.success = function (t) { e[o] = t, typeof u == "number" && setTimeout(function () { delete e[o] }, u), a.apply(this, arguments) } } }() }; e.store && (t.each(e.store.types, function (t) { s[t] = function (n, r, i, o) { var u = s._key(r.resourceId, i.cacheURL(), i.data), a = e.store[t](u); if (a) return i.success(a), !1; var f = o.success; o.success = function (r) { e.store[t](u, r, { expires: n.cache.expires }), f.apply(this, arguments) } } }), s.persist = s[e.store.type]), e.subscribe("request.before.ajax", function (e) { var t = e.cache; if (t) return t = t.type || t, s[t in s ? t : "_default"].apply(this, arguments) }), e.request.decoders = { jsend: function (e, t, n, r, i) { e.status === "success" ? r(e.data) : e.status === "fail" ? i(e.data, "fail") : e.status === "error" ? (delete e.status, i(e, "error")) : i(null, "error") } }, e.subscribe("request.before.ajax", function (n, r, i, s) { function f(e, t) { o(e, t) } function l(e, t) { u(e, t) } var o = s.success, u = s.error, a = t.isFunction(n.decoder) ? n.decoder : n.decoder in e.request.decoders ? e.request.decoders[n.decoder] : e.request.decoders._default; if (!a) return; s.success = function (e, t) { a(e, t, s, f, l) }, s.error = function (e, t) { a(e, t, s, f, l) } }) }(amplify, jQuery);
$(document).ready(function () {

    $('.btn-toggle').click(function (event) {
        if ((event.target.tagName === "LABEL" || event.target.tagName === "SPAN") && !($(event.target).hasClass('active') || $(event.target).parent().hasClass('active'))) {
            $(this).find('.btn').toggleClass('active');

            if ($(this).find('.btn-primary').size() > 0) {
                $(this).find('.btn').toggleClass('btn-primary');
            }
            if ($(this).find('.btn-danger').size() > 0) {
                $(this).find('.btn').toggleClass('btn-danger');
            }
            if ($(this).find('.btn-success').size() > 0) {
                $(this).find('.btn').toggleClass('btn-success');
            }
            if ($(this).find('.btn-info').size() > 0) {
                $(this).find('.btn').toggleClass('btn-info');
            }

            $(this).find('.btn').toggleClass('btn-default');
        }
    });
});;
QuerystringParms = location.search.replace(/^\?/,"")
QuerystringParms = QuerystringParms.split('&');
Querystring = new Array()
var QuerystringParm = null;
for (var x = 0;x<QuerystringParms.length;x++)
	{QuerystringParm = QuerystringParms[x].split('=')
	if (QuerystringParm.length == 2)
		{Querystring[unescape(QuerystringParm[0]).toLowerCase()] = unescape(QuerystringParm[1])
		}
	}

/*  Christophe's hacked JS 25/04/2007 */
function GotoRegion(strRegion, strURL, region) {
	// hardcoded for Wales for now 
	region = 22;
	//
	var sUrl;
	sUrl = strURL;
	advSearchUrl = 'PublicListingList.aspx';
	officeSearchUrl = 'OfficeAgentSearch.aspx';
	//
	if (region != 'undefined' && region == 22) 
	{
		if (document.getElementById("SearchType2").checked) 
			{
			sUrl = sUrl + "?SearchType=O"
			//alert('Office Search for region '+region);
			// go to sub map
			location.href=sUrl;
			}
			else
			{			
			//alert('Property Search for region '+region);
			advSearchUrl = advSearchUrl + "?SearchType=P&regionid="+strRegion;
			// go to properties advanced search & pass in the region id
			location.href=advSearchUrl;
			}
	} 
	else 
	{
		if (document.getElementById("SearchType2").checked) 
			{
			sUrl = sUrl + "?SearchType=O"
			//alert('Office Search for region '+region);
			// go to office agent search & pass in the region id
			officeSearchUrl = officeSearchUrl+"?SearchType=O&regionid="+strRegion;
			location.href=officeSearchUrl;
			}
			else
			{			 
			//alert('Property Search for region '+region);
			// go to sub map
			sUrl = sUrl + "?SearchType=P"
			location.href=sUrl;
			}
	}

	//return false;
}



function DrillDown(SearchType, CityID) {
	//SearchType: P for property, O for Office

	//Lang = two character langauage code used throughout 
	//OfficeID:  the office ID of the selected office, an ID of 0 (zero) indicates 'Coming Soon'
	//IsMultiOffice:  0 (zero) for no, one office per city; 1 (one) there is more than one office, show list
	//var SearchType;
	//SearchType = GetSearchType();
	var page;
	//don't use the City ID to find Offices in the same city
	switch (CityID) {
	    case 0:
	        page = "/ComingSoon.aspx?SearchType=" + SearchType;
	        break;
	    case 6533115:
	        page = "/maps/bratislava.aspx?PathVar=2&province=6533115&searchType=" + SearchType;
	        break;
	    case 'opensearch':
	        switch (SearchType) {
	            case "P":
	                page = "/PublicListingList.aspx";
	                break
	            default:
	                page = "/OfficeAgentSearch.aspx";
	                break;
	        }
	        break;
	    default:
	        switch (SearchType) {
	            case "P":
	                page = "/PublicListingList.aspx?CityID=" + CityID + "&SearchType=" + SearchType;
	                break
	            case "RP":
	                page = "/PublicListingList.aspx?CityID=" + CityID + "&SearchType=" + SearchType + "&TransactionType=For Rent/Lease";		
	                break
	            case "PL":
	                page = "/PublicListingList.aspx?CityID=" + CityID + "&SearchType=" + SearchType;		
	                break;
	            default:
	                page = "/OfficeList.aspx?CityID=" + CityID 
	                break;
	        }
	        break;
	}
	
	location.href=page;
}
		
function GetSearchType()
{
	
	//determines which radio button is selected and returns P or O (property or office)
	//to the DrillDown function

	var searchType = typeof(Querystring["searchtype"]) != 'undefined'?Querystring["searchtype"]:"";

	if (/pl/i.test(searchType))
	{
		return 'PL';
	} 
	else if (/p/i.test(searchType))
	{
		return 'P' 
	}
	else if(/o/i.test(searchType))
	{    
	return 'O';
	}
	else if (document.getElementById("SearchType1") != null)
	{
		if(document.getElementById("SearchType1").checked) 
		{
			return 'P' 
		}
	}
	else if(document.getElementById("SearchType2") != null)
	{ 
		if(document.getElementById("SearchType2").checked)
		{
			return 'O';
		}
	}
	else {
		return 'P';	
	}
}

function LocalZoneDrillDown(SearchType, LocalZoneID)
{
	//SearchType: P for property, O for Office
	var page;	
	
	//don't use the City ID to find Offices in the same city
	if (SearchType == "P") 
	{
	    page = "/PublicListingList.aspx?SearchType=" + SearchType + "&LocalZoneID=" + LocalZoneID;
	} 
	else 
	{
		page = "/OfficeList.aspx?SearchType=" + SearchType + "&LocalZoneID=" + LocalZoneID;
	}
	location.href = page;
}

function GotoMapPage(strURL)
			{
	var sUrl
	sUrl = strURL;
	if (document.getElementById("SearchType2").checked) 
		sUrl = sUrl + "?SearchType=O"
	/*else if ((document.forms["frmSearchType"].SearchType3 != null) && (document.forms["frmSearchType"].SearchType3.checked)) // CR#13781 Currently used for Ireland Only
	{ 
		if (document.forms["frmSearchType"].SearchType3.checked)
			sUrl = sUrl + "&SearchType=RP&TransactionType=For Rent/Lease"
	}*/
	else
		sUrl = sUrl + "?SearchType=P"
	
	location.href=sUrl;
}

function GotoMapPageBelgium(strURL)
{
	var sUrl
	sUrl = strURL;

	searchTypeVal = GetSearchType();

	if (searchTypeVal == 'O') 
		sUrl = sUrl + "?SearchType=O"
	/*else if ((document.forms["frmSearchType"].SearchType3 != null) && (document.forms["frmSearchType"].SearchType3.checked)) // CR#13781 Currently used for Ireland Only
	{ 
		if (document.forms["frmSearchType"].SearchType3.checked)
			sUrl = sUrl + "&SearchType=RP&TransactionType=For Rent/Lease"
	}*/
	else
		sUrl = sUrl + "?SearchType=P"
	
	location.href=sUrl;
}


function GotoProvince(strProvince) //function not  used  all all. 
{				
	var bOffice = false;
	if (document.getElementById("SearchType2").checked) {
		
		bOffice = true;
		document.forms[0].action = '/officeagentsearch.aspx?ProvinceID='+strProvince;
	}
	else {
		
	    document.forms[0].action = '/PublicListingList.aspx?ProvinceID=' + strProvince;
	}


	document.forms[0].submit();


}


function GotoSwedenProvince(strProvince, strRegion)
{
	var mapPage = "";
	var SearchTypeVal = "SearchType=" + (document.getElementById("SearchType2").checked?"O":"P")
	if (document.getElementById("SearchType2").checked) {
		//alert(strProvince);
		switch(strProvince)
		{
			/*case "3094":
				mapPage = "/maps/blekinge.aspx?" + SearchTypeVal
				break;*/
			case "3095":
				mapPage = "/maps/dalarna.aspx?" + SearchTypeVal
				break;
			case "3096":
				mapPage = "/maps/gavleborg.aspx?" + SearchTypeVal
				break;
		/*	case "3097":
				mapPage = "/maps/gotland.aspx?" + SearchTypeVal
				break;*/
			/*case "3098":
				mapPage = "/maps/halland.aspx?" + SearchTypeVal
				break;*/
			case "3099":
				mapPage = "/maps/jamtland.aspx?" + SearchTypeVal
				break;
			/*case "3100":
				mapPage = "/maps/konkoping.aspx?" + SearchTypeVal
				break;*/
		/*	case "3101":
				mapPage = "/maps/kalmar.aspx?" + SearchTypeVal
				break;*/
		/*	case "3102":
				mapPage = "/maps/kronoberg.aspx?" + SearchTypeVal
				break;*/
	/*		case "3103":
				mapPage = "/maps/norrbotten.aspx?" + SearchTypeVal
				break;*/
			case "3104":
				mapPage = "/maps/orebro.aspx?" + SearchTypeVal
				break;
			case "3105":
				mapPage = "/maps/ostergotland.aspx?" + SearchTypeVal
				break;
			case "3106":
				mapPage = "/maps/skane.aspx?" + SearchTypeVal
				break;
		/*	case "3107":
				mapPage = "/maps/sodermanland.aspx?" + SearchTypeVal
				break;*/
			case "3108":
				mapPage = "/maps/stockolm.aspx?" + SearchTypeVal
				break;
			case "3109":
				mapPage = "/maps/uppsala.aspx?" + SearchTypeVal
				break;
		/*	case "3110":
				mapPage = "/maps/varmland.aspx?" + SearchTypeVal
				break;*/
		/*	case "3111":
				mapPage = "/maps/vasterbotten.aspx?" + SearchTypeVal
				break;*/
			case "3112":
				mapPage = "/maps/vasternorrland.aspx?" + SearchTypeVal
				break;
			case "3113":
				mapPage = "/maps/vastmanland.aspx?" + SearchTypeVal;
				break;
		/*	case "3114":
				mapPage = "/maps/vastragotaland.aspx?" + SearchTypeVal
				break;*/
			default:
				mapPage = 'ComingSoon.aspx?SearchType=O';
				break;
		}
		location.href = mapPage;
	}
	else
	{
	    location.href = 'PublicListingList.aspx?ProvinceID=' + strProvince;
	}
}

function ProvinceDrillDown(SearchType, ProvinceID)
{
	//SearchType: P for property, O for Office
	var page;	
	
	//don't use the City ID to find Offices in the same city
	if (SearchType == "P") 
	{
	    page = "/PublicListingList.aspx?ProvinceID=" + ProvinceID + "&SearchType=" + SearchType;
	} 
	else 
	{
		page = "/OfficeList.aspx?ProvinceID=" + ProvinceID + "&SearchType=" + SearchType;
	}
	location.href = page;
}

;
/// <reference path="jquery-1.7.js"/>
/// <reference path="global.js"/>
/// <reference path="geoServices.js"/>
/// <reference path="GoogleMapsCustomInfoBox.js"/>

var maps = (function() {

    var out = {};
    var isMobileDevice = /midp|j2me|avant|docomo| novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up.b|audio|SIE-|SEC-|samsung|HTC|mot-|mitsu|sagem|sony|alcatel|lg|eric|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch,rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|dddi|moto|iphone|opera mini/i.test(navigator.userAgent);


    var GoogleVer3 = (new function() {

        this.map = null; // reference to Google's map object
        this.marker = null; // reference to Google's marker object
        this.lat = 0;
        this.lng = 0;

        var noLatLngImagePath = {};
        noLatLngImagePath['userSet'] = '';
        noLatLngImagePath['default'] = '/Sites/MobileWeb/images/NoGoogleMapMobile.png';
        var onNoLatLng = null;
        var onMarkerHasStreetView = null;
        var streetViewRadius = 50;
        this.translations = null;
        var directionsRenderer = null;
        var infoWindowContent = '';
        var infoWindowClass = null;
        var infoWindowOnMarkerClick = false;
        var zoom = 10;
        var addressToSetZoomOn = ""; // for example: pass cityname here and zoom will be automatically set on this city's geo-boundaries
        var disabled = false;
        var approxMap = false;


        this.init = function(mapDivID, lat, lng, options) {
            var mapDiv = typeof (mapDivID) == 'object' ? mapDivID : document.getElementById(mapDivID);
            if (options == undefined)
                options = {};

            GoogleVer3.lat = lat; // must attach to an explicit instance (GoogleVer3 is that instance) because this.lat = lat doesn't work
            GoogleVer3.lng = lng;

            noLatLngImagePath['userSet'] = options.noLatLngImagePath;
            onNoLatLng = options.onNoLatLng;

            onMarkerHasStreetView = options.onMarkerHasStreetView;
            if (options.streetViewRadius && !isNaN(options.streetViewRadius))
                streetViewRadius = options.streetViewRadius;

            if (options.translations)
                GoogleVer3.translations = options.translations;
            if (options.directionsRenderer)
                directionsRenderer = options.directionsRenderer;

            if (options.infoWindowContent)
                infoWindowContent = options.infoWindowContent;
            else if (options.infoWindowClass)
                infoWindowClass = options.infoWindowClass;

            if (typeof (options.infoWindowOnMarkerClick) == 'boolean')
                infoWindowOnMarkerClick = options.infoWindowOnMarkerClick;

            if (options.zoom && !isNaN(options.zoom) && ("" + options.zoom).indexOf('.') == -1)
                zoom = options.zoom;
            else if (options.addressToSetZoomOn)
                addressToSetZoomOn = options.addressToSetZoomOn;

            if (typeof (options.disabled) == 'boolean')
                disabled = options.disabled;

            if (typeof (options.approxMap) == 'boolean')
                approxMap = options.approxMap;

            // if no latitude and/or no longitude then: display overlay-image & execute passed-in callback function (if any)
            if ((!lat || isNaN(lat) || (lat == -9999)) || (!lng || isNaN(lng) || (lng == -9999))) {
                $(mapDiv).html("<img src='" + (noLatLngImagePath['userSet'] || noLatLngImagePath['default']) + "' border=0>");
                if (onNoLatLng) onNoLatLng();
                return;
            }


            // creating map
            var mapOptions = null;

            if (disabled) {
                mapOptions = {
                    zoom: zoom,
                    center: new google.maps.LatLng(lat, lng),
                    mapTypeId: google.maps.MapTypeId.ROADMAP,

                    disableDefaultUI: true,
                    draggable: false,
                    zoomControl: false,
                    scrollwheel: false,
                    disableDoubleClickZoom: true
                };
            }
            else {
                mapOptions = {
                    zoom: zoom,
                    center: new google.maps.LatLng(lat, lng),
                    mapTypeId: google.maps.MapTypeId.ROADMAP,

                    scaleControl: true,
                    scaleControlOptions: {
                        position: google.maps.ControlPosition.BOTTOM_LEFT
                    }
                };
            }
            var map = new google.maps.Map(mapDiv, mapOptions);
            GoogleVer3.map = map;

            // creating marker
            if (!approxMap) {
                var markerOptions = {
                    position: new google.maps.LatLng(lat, lng),
                    map: map
                }
                if (options.marker) {
                    if (options.marker.icon)
                        markerOptions.icon = options.marker.icon;
                    if (options.marker.shadow)
                        markerOptions.shadow = options.marker.shadow;
                }
                var marker = new google.maps.Marker(markerOptions);
                GoogleVer3.marker = marker;
            }

            // creating circle for approximation map
            if (approxMap) {
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 1000,
                    fillColor: "#c4df9b",
                    fillOpacity: 0.4,
                    strokeWeight: 0.4,
                    center: new google.maps.LatLng(lat,lng) 
                });
            }

            // (optionally) checking if street-view available for passed-in latlong
            if (onMarkerHasStreetView) {
                google.maps.event.addDomListener(map, "projection_changed", function() {
                    var streetViewService = new google.maps.StreetViewService();
                    streetViewService.getPanoramaByLocation(new google.maps.LatLng(lat, lng), streetViewRadius, function(data, status) {
                        if (status === google.maps.StreetViewStatus.OK) {
                            onMarkerHasStreetView(data);
                        }
                        else {
                            onMarkerHasStreetView(null);
                        }
                    });
                });
            }


            // (optionally) creating directionsRenderer 
            // (it at least plots directions on the map and optionally outputs worded-directions in the "panel" if passed)
            if (directionsRenderer) {
                directionsRenderer.setMap(map);
            }

            // (optionally) creating infoWindow from string (ie. by passing infoWindowContent of type: string)
            if (infoWindowContent && typeof (infoWindowContent) == 'string') {
                var infoWindow = new google.maps.InfoWindow({
                    content: infoWindowContent
                });

                if (infoWindowOnMarkerClick) {
                    google.maps.event.addListener(marker, 'click', function() {
                        infoWindow.open(map, marker);
                    });
                }
                else {
                    infoWindow.open(map, marker);
                }

            } // else (optionally) creating infoWindow from class (ie. by passing infoWindowClass)
            else if (infoWindowClass && typeof (infoWindowClass) == 'function') {
                var infoWindow = new infoWindowClass({ latlng: marker.getPosition(), map: map, translations: this.translations });
            }


            // (optionally) setting zoom level automatically based on passed-in address's bounds
            if (addressToSetZoomOn) {
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'address': addressToSetZoomOn }, function(results, status) {

                    if (status == google.maps.GeocoderStatus.OK) {
                        if (map.getBounds().intersects(results[0].geometry.viewport)) { // check if correct address passed (ie. intersects current bounds)
                            map.fitBounds(results[0].geometry.viewport);
                            map.setCenter(new google.maps.LatLng(lat, lng));
                        }
                    }
                });
            }

            if (out.GoogleVer3.onMapInitialized) {
                if (typeof (out.GoogleVer3.onMapInitialized) == 'object') {
                    if (out.GoogleVer3.onMapInitialized.onMapInitialized) {
                        out.GoogleVer3.onMapInitialized.onMapInitialized();
                    }
                }
                else if (typeof (out.GoogleVer3.onMapInitialized) == 'function') {
                    out.GoogleVer3.onMapInitialized();
                }
            }

            //Resize map after tiles are loaded
            google.maps.event.addListenerOnce(GoogleVer3.map, 'tilesloaded', function() {
                //Avoid gray area to be displayed - show  full map, rather than partial
                setTimeout(function() { google.maps.event.trigger(GoogleVer3.map, 'resize'); map.setCenter(new google.maps.LatLng(lat, lng)); }, 1000);
            });
        }


        this.Utils = (new function() {
            this.addStreetViewToContainer = function(containerDivID, lat, lng, visible) {
                visible = typeof (visible) == 'boolean' ? visible : true; // panorama visible by default
                var containerDiv = typeof (containerDivID) == 'object' ? containerDivID : document.getElementById(containerDivID);
                // create panorama
                var panorama = new google.maps.StreetViewPanorama(containerDiv, {
                    position: new google.maps.LatLng(lat, lng),
                    visible: visible,
                    disableDefaultUI: true
                });
                return panorama;
            }


            this.addStreetViewToContainer2 = function(containerDivID, panoID, visible) {
                visible = typeof (visible) == 'boolean' ? visible : true; // panorama visible by default
                var containerDiv = typeof (containerDivID) == 'object' ? containerDivID : document.getElementById(containerDivID);
                // create panorama
                var panorama = new google.maps.StreetViewPanorama(containerDiv, {
                    disableDefaultUI: true
                });
                panorama.setPano(panoID);
                panorama.setVisible(visible);
                return panorama;
            }


            this.checkIfStreetViewExists = function(lat, lng, radius, callbackFunc) {
                var streetViewService = new google.maps.StreetViewService();
                streetViewService.getPanoramaByLocation(new google.maps.LatLng(lat, lng), radius, function(data, status) {
                    if (status === google.maps.StreetViewStatus.OK) {
                        var panoID = data.location.pano;
                        callbackFunc(panoID);
                    }
                    else {
                        callbackFunc(null);
                    }
                });
            }
        })


        this.FullDirections = (new function() {

            var directionsRenderer = null;
            var latlng2 = null; // latlng1: starting latlong, latlng2: destination latlong
            this.translations = {
                "Your_address_with_ellipsis": "",
                "Go_with_exclamation": "",
                "Locate": "",
                "Please_enter_your_address": "",
                "Google_cannot_find_address": "",
                "Google_cannot_determine_directions": "",
                "Your_address_cannot_be_determined": ""
            }


            this.init = function(mapDivID, directionsDivID, lat, lng, customInfoWindowClass) {
                var mapDiv = typeof (mapDivID) == 'object' ? mapDivID : document.getElementById(mapDivID);
                var directionsDiv = typeof (directionsDivID) == 'object' ? directionsDivID : document.getElementById(directionsDivID);
                for (var key in this.translations) {
                    if (this.translations.hasOwnProperty(key) && !this.translations[key]) {
                        alert("Please set all translations before calling: maps.GoogleVer3.FullDirections.initialize.");
                        break;
                    }
                }

                directionsRenderer = new google.maps.DirectionsRenderer({
                    suppressMarkers: false,
                    panel: directionsDiv
                });

                latlng2 = new google.maps.LatLng(lat, lng);

                var options = {
                    translations: this.translations,
                    directionsRenderer: directionsRenderer
                };


                if (customInfoWindowClass) {
                    options.infoWindowClass = customInfoWindowClass;
                }
                else { // create default infoWindow html if no custom infoWindow class passed
                    // start creating html for infoWindowContent
                    var html = "<input id='maps-address1'      type='text'   value='" + this.translations["Your_address_with_ellipsis"] + "'><br/>" +
                               "<input id='maps-go-button'     type='button' value='" + this.translations["Go_with_exclamation"] + "'>" +
                               "<input id='maps-locate-button' type='button' value='" + this.translations["Locate"] + "'>";

                    // clean-up (just in case)
                    $('#maps-address1, #maps-go-button, #maps-locate-button').remove();

                    // we must attach events to document.body to make them work 
                    $(document.body)
                    .on('focus', '#maps-address1', function() { if (this.value == this.defaultValue) this.value = ''; })
                    .on('blur', '#maps-address1', function() { if (this.value == '') this.value = this.defaultValue; })
                    .on('keypress', '#maps-address1', function(event) { if (event.which == 13) { maps.GoogleVer3.getDirections(this); return false; } });

                    $(document.body)
                    .on('click', '#maps-go-button', function() {
                        var input = document.getElementById('maps-address1');
                        maps.GoogleVer3.FullDirections.getDirections(input);
                    });

                    $(document.body)
                    .on('click', '#maps-locate-button', function() {
                        var input = document.getElementById('maps-address1');
                        geoServices.GoogleVer3.getUpdatedAddressFromCurrentPosition(function(response) {
                            input.value = response.city;
                        });
                    });

                    options.infoWindowContent = html;
                }

                maps.GoogleVer3.initialize(mapDivID, lat, lng, options);
            }


            this.getDirections = function(address1Input) {
                var me = this;
                if (address1Input.value == "" || address1Input.value == address1Input.defaultValue) {
                    alert(this.translations["Please_enter_your_address"]);
                    return;
                }
                if (latlng2 == null) {
                    alert("You must call: maps.GoogleVer3.FullDirections.initialize before calling: maps.GoogleVer3.FullDirections.getDirections.");
                    return;
                }


                geoServices.GoogleVer3.getLatLongFromAddress(address1Input.value, function(response) {
                    if (response == null) {
                        alert(this.translations["Google_cannot_find_address"]);
                        return;
                    }

                    var latlng1 = new google.maps.LatLng(response.lat, response.lng);
                    geoServices.GoogleVer3.getDirections(latlng1, latlng2, function(response) {
                        if (response == null) {
                            alert(me.translations["Google_cannot_determine_directions"]);
                            return;
                        }

                        var div = directionsRenderer.panel;
                        var windowHeight = $(window).height();
                        var containerHeight = $('.container').height();
                        if (isMobileDevice) {
                            // remove footer
                            $('.footer').remove();
                            // make directions content overflow container
                            $(div).css('overflow-Y', 'visible');
                        }
                        else {
                            $(div).height(windowHeight - containerHeight - $('#directions').height() - 20);
                        }
                        directionsRenderer.setDirections(response);
                    });
                });
            }
        });
    });



    out = {
        GoogleVer3: {
            initialize: GoogleVer3.init,
            initializeOnDocumentReady: function(mapDivID, lat, lng, options) {
                $(document).ready(function() { GoogleVer3.init(mapDivID, lat, lng, options) });
            },
            initializeOnWindowReady: function(mapDivID, lat, lng, options) {
                $(window).on('load', function() { GoogleVer3.init(mapDivID, lat, lng, options) });
            },
            onMapInitialized: null,
            getMap: function() { return GoogleVer3.map },
            getMarker: function() { return GoogleVer3.marker },
            getLat: function() { return GoogleVer3.lat },
            getLng: function() { return GoogleVer3.lng },
            Utils: {
                addStreetViewToContainer: function(containerDivID, lat, lng, visible) {
                    return GoogleVer3.Utils.addStreetViewToContainer.call(GoogleVer3.Utils, containerDivID, lat, lng, visible)
                },
                addStreetViewToContainer2: function(containerDivID, panoID, visible) {
                    return GoogleVer3.Utils.addStreetViewToContainer2.call(GoogleVer3.Utils, containerDivID, panoID, visible)
                },
                checkIfStreetViewExists: function(lat, lng, radius, callbackFunc) {
                    return GoogleVer3.Utils.checkIfStreetViewExists.call(GoogleVer3.Utils, lat, lng, radius, callbackFunc)
                }
            },
            FullDirections: {
                initialize: function(mapDivID, directionsDivID, lat, lng, customInfoWindowClass) {
                    GoogleVer3.FullDirections.init.call(GoogleVer3.FullDirections, mapDivID, directionsDivID, lat, lng, customInfoWindowClass)
                },
                getDirections: function(address1Input) {
                    GoogleVer3.FullDirections.getDirections.call(GoogleVer3.FullDirections, address1Input)
                },
                setTranslations: function(obj) { $.extend(GoogleVer3.FullDirections.translations, obj); },
                getTranslations: function() { return GoogleVer3.FullDirections.translations }
            }
        }
    }
    return out;
})();;
/*	
 * jQuery mmenu v4.7.5
 * @requires jQuery 1.7.0 or later
 *
 * mmenu.frebsite.nl
 *	
 * Copyright (c) Fred Heusschen
 * www.frebsite.nl
 *
 * Licensed under the MIT license:
 * http://en.wikipedia.org/wiki/MIT_License
 */
!function(e){function n(){l=!0,d.$wndw=e(window),d.$html=e("html"),d.$body=e("body"),e.each([i,a,o],function(e,n){n.add=function(e){e=e.split(" ");for(var t in e)n[e[t]]=n.mm(e[t])}}),i.mm=function(e){return"mm-"+e},i.add("wrapper menu inline panel nopanel list nolist subtitle selected label spacer current highest hidden opened subopened subopen fullsubopen subclose"),i.umm=function(e){return"mm-"==e.slice(0,3)&&(e=e.slice(3)),e},a.mm=function(e){return"mm-"+e},a.add("parent"),o.mm=function(e){return e+".mm"},o.add("toggle open close setSelected transitionend webkitTransitionEnd mousedown mouseup touchstart touchmove touchend scroll resize click keydown keyup"),e[t]._c=i,e[t]._d=a,e[t]._e=o,e[t].glbl=d}var t="mmenu",s="4.7.5";if(!e[t]){var i={},a={},o={},l=!1,d={$wndw:null,$html:null,$body:null};e[t]=function(n,s,i){this.$menu=n,this.opts=s,this.conf=i,this.vars={},"function"==typeof this.___deprecated&&this.___deprecated(),this._initMenu(),this._initAnchors(),this._initEvents();var a=this.$menu.children(this.conf.panelNodetype);for(var o in e[t].addons)e[t].addons[o]._add.call(this),e[t].addons[o]._add=function(){},e[t].addons[o]._setup.call(this);return this._init(a),"function"==typeof this.___debug&&this.___debug(),this},e[t].version=s,e[t].addons={},e[t].uniqueId=0,e[t].defaults={classes:"",slidingSubmenus:!0,onClick:{setSelected:!0}},e[t].configuration={panelNodetype:"ul, ol, div",transitionDuration:400,openingInterval:25,classNames:{panel:"Panel",selected:"Selected",label:"Label",spacer:"Spacer"}},e[t].prototype={_init:function(n){n=n.not("."+i.nopanel),n=this._initPanels(n);for(var s in e[t].addons)e[t].addons[s]._init.call(this,n);this._update()},_initMenu:function(){this.opts.offCanvas&&this.conf.clone&&(this.$menu=this.$menu.clone(!0),this.$menu.add(this.$menu.find("*")).filter("[id]").each(function(){e(this).attr("id",i.mm(e(this).attr("id")))})),this.$menu.contents().each(function(){3==e(this)[0].nodeType&&e(this).remove()}),this.$menu.parent().addClass(i.wrapper);var n=[i.menu];n.push(i.mm(this.opts.slidingSubmenus?"horizontal":"vertical")),this.opts.classes&&n.push(this.opts.classes),this.$menu.addClass(n.join(" "))},_initPanels:function(n){var t=this;this.__findAddBack(n,"ul, ol").not("."+i.nolist).addClass(i.list);var s=this.__findAddBack(n,"."+i.list).find("> li");this.__refactorClass(s,this.conf.classNames.selected,"selected"),this.__refactorClass(s,this.conf.classNames.label,"label"),this.__refactorClass(s,this.conf.classNames.spacer,"spacer"),s.off(o.setSelected).on(o.setSelected,function(n,t){n.stopPropagation(),s.removeClass(i.selected),"boolean"!=typeof t&&(t=!0),t&&e(this).addClass(i.selected)}),this.__refactorClass(this.__findAddBack(n,"."+this.conf.classNames.panel),this.conf.classNames.panel,"panel"),n.add(this.__findAddBack(n,"."+i.list).children().children().filter(this.conf.panelNodetype).not("."+i.nopanel)).addClass(i.panel);var l=this.__findAddBack(n,"."+i.panel),d=e("."+i.panel,this.$menu);if(l.each(function(){var n=e(this),s=n.attr("id")||t.__getUniqueId();n.attr("id",s)}),l.each(function(){var n=e(this),s=n.is("ul, ol")?n:n.find("ul ,ol").first(),o=n.parent(),l=o.children("a, span"),d=o.closest("."+i.panel);if(o.parent().is("."+i.list)&&!n.data(a.parent)){n.data(a.parent,o);var r=e('<a class="'+i.subopen+'" href="#'+n.attr("id")+'" />').insertBefore(l);l.is("a")||r.addClass(i.fullsubopen),t.opts.slidingSubmenus&&s.prepend('<li class="'+i.subtitle+'"><a class="'+i.subclose+'" href="#'+d.attr("id")+'">'+l.text()+"</a></li>")}}),this.opts.slidingSubmenus){var r=this.__findAddBack(n,"."+i.list).find("> li."+i.selected);r.parents("li").removeClass(i.selected).end().add(r.parents("li")).each(function(){var n=e(this),t=n.find("> ."+i.panel);t.length&&(n.parents("."+i.panel).addClass(i.subopened),t.addClass(i.opened))}).closest("."+i.panel).addClass(i.opened).parents("."+i.panel).addClass(i.subopened)}else{var r=e("li."+i.selected,d);r.parents("li").removeClass(i.selected).end().add(r.parents("li")).addClass(i.opened)}var u=d.filter("."+i.opened);return u.length||(u=l.first()),u.addClass(i.opened).last().addClass(i.current),this.opts.slidingSubmenus&&l.not(u.last()).addClass(i.hidden).end().appendTo(this.$menu),l},_initAnchors:function(){var n=this;d.$body.on(o.click,"a",function(s){var a=e(this),l=!1,r=n.$menu.find(a).length;for(var u in e[t].addons)if(e[t].addons[u]._clickAnchor&&(l=e[t].addons[u]._clickAnchor.call(n,a,r)))break;if(!l&&r){var c=a.attr("href")||"";if("#"==c.slice(0,1))try{e(c,n.$menu).is("."+i.panel)&&(l=!0,e(c).trigger(n.opts.slidingSubmenus?o.open:o.toggle))}catch(p){}}if(l&&s.preventDefault(),!l&&r&&a.is("."+i.list+" > li > a")&&!a.is('[rel="external"]')&&!a.is('[target="_blank"]')){n.__valueOrFn(n.opts.onClick.setSelected,a)&&a.parent().trigger(o.setSelected);var h=n.__valueOrFn(n.opts.onClick.preventDefault,a,"#"==c.slice(0,1));h&&s.preventDefault(),n.__valueOrFn(n.opts.onClick.blockUI,a,!h)&&d.$html.addClass(i.blocking),n.__valueOrFn(n.opts.onClick.close,a,h)&&n.$menu.trigger(o.close)}})},_initEvents:function(){var n=this;this.$menu.on(o.toggle+" "+o.open+" "+o.close,"."+i.panel,function(e){e.stopPropagation()}),this.opts.slidingSubmenus?this.$menu.on(o.open,"."+i.panel,function(){return n._openSubmenuHorizontal(e(this))}):this.$menu.on(o.toggle,"."+i.panel,function(){var n=e(this);n.trigger(n.parent().hasClass(i.opened)?o.close:o.open)}).on(o.open,"."+i.panel,function(){e(this).parent().addClass(i.opened)}).on(o.close,"."+i.panel,function(){e(this).parent().removeClass(i.opened)})},_openSubmenuHorizontal:function(n){if(n.hasClass(i.current))return!1;var t=e("."+i.panel,this.$menu),s=t.filter("."+i.current);return t.removeClass(i.highest).removeClass(i.current).not(n).not(s).addClass(i.hidden),n.hasClass(i.opened)?s.addClass(i.highest).removeClass(i.opened).removeClass(i.subopened):(n.addClass(i.highest),s.addClass(i.subopened)),n.removeClass(i.hidden).addClass(i.current),setTimeout(function(){n.removeClass(i.subopened).addClass(i.opened)},this.conf.openingInterval),"open"},_update:function(e){if(this.updates||(this.updates=[]),"function"==typeof e)this.updates.push(e);else for(var n=0,t=this.updates.length;t>n;n++)this.updates[n].call(this,e)},__valueOrFn:function(e,n,t){return"function"==typeof e?e.call(n[0]):"undefined"==typeof e&&"undefined"!=typeof t?t:e},__refactorClass:function(e,n,t){return e.filter("."+n).removeClass(n).addClass(i[t])},__findAddBack:function(e,n){return e.find(n).add(e.filter(n))},__transitionend:function(e,n,t){var s=!1,i=function(){s||n.call(e[0]),s=!0};e.one(o.transitionend,i),e.one(o.webkitTransitionEnd,i),setTimeout(i,1.1*t)},__getUniqueId:function(){return i.mm(e[t].uniqueId++)}},e.fn[t]=function(s,i){return l||n(),s=e.extend(!0,{},e[t].defaults,s),i=e.extend(!0,{},e[t].configuration,i),this.each(function(){var n=e(this);n.data(t)||n.data(t,new e[t](n,s,i))})},e[t].support={touch:"ontouchstart"in window||navigator.msMaxTouchPoints}}}(jQuery);
/*	
 * jQuery mmenu offCanvas addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){var t="mmenu",o="offCanvas";e[t].addons[o]={_init:function(){},_setup:function(){if(this.opts[o]){var t=this,s=this.opts[o],p=this.conf[o];"string"!=typeof p.pageSelector&&(p.pageSelector="> "+p.pageNodetype),a.$allMenus=(a.$allMenus||e()).add(this.$menu),this.vars.opened=!1;var r=[n.offcanvas];"left"!=s.position&&r.push(n.mm(s.position)),"back"!=s.zposition&&r.push(n.mm(s.zposition)),this.$menu.addClass(r.join(" ")).parent().removeClass(n.wrapper),this.setPage(a.$page),this[o+"_initBlocker"](),this[o+"_initWindow"](),this.$menu.on(i.open+" "+i.opening+" "+i.opened+" "+i.close+" "+i.closing+" "+i.closed+" "+i.setPage,function(e){e.stopPropagation()}).on(i.open+" "+i.close+" "+i.setPage,function(e){t[e.type]()}),this.$menu[p.menuInjectMethod+"To"](p.menuWrapperSelector)}},_add:function(){n=e[t]._c,s=e[t]._d,i=e[t]._e,n.add("offcanvas slideout modal background opening blocker page"),s.add("style"),i.add("opening opened closing closed setPage"),a=e[t].glbl},_clickAnchor:function(e){if(!this.opts[o])return!1;var t=this.$menu.attr("id");if(t&&t.length&&(this.conf.clone&&(t=n.umm(t)),e.is('[href="#'+t+'"]')))return this.open(),!0;if(a.$page){var t=a.$page.attr("id");return t&&t.length&&e.is('[href="#'+t+'"]')?(this.close(),!0):!1}}},e[t].defaults[o]={position:"left",zposition:"back",modal:!1,moveBackground:!0},e[t].configuration[o]={pageNodetype:"div",pageSelector:null,menuWrapperSelector:"body",menuInjectMethod:"prepend"},e[t].prototype.open=function(){if(this.vars.opened)return!1;var e=this;return this._openSetup(),setTimeout(function(){e._openFinish()},this.conf.openingInterval),"open"},e[t].prototype._openSetup=function(){var e=this;a.$allMenus.not(this.$menu).trigger(i.close),a.$page.data(s.style,a.$page.attr("style")||""),a.$wndw.trigger(i.resize,[!0]);var t=[n.opened];this.opts[o].modal&&t.push(n.modal),this.opts[o].moveBackground&&t.push(n.background),"left"!=this.opts[o].position&&t.push(n.mm(this.opts[o].position)),"back"!=this.opts[o].zposition&&t.push(n.mm(this.opts[o].zposition)),this.opts.classes&&t.push(this.opts.classes),a.$html.addClass(t.join(" ")),setTimeout(function(){e.vars.opened=!0},this.conf.openingInterval),this.$menu.addClass(n.current+" "+n.opened)},e[t].prototype._openFinish=function(){var e=this;this.__transitionend(a.$page,function(){e.$menu.trigger(i.opened)},this.conf.transitionDuration),a.$html.addClass(n.opening),this.$menu.trigger(i.opening)},e[t].prototype.close=function(){if(!this.vars.opened)return!1;var e=this;return this.__transitionend(a.$page,function(){e.$menu.removeClass(n.current).removeClass(n.opened),a.$html.removeClass(n.opened).removeClass(n.modal).removeClass(n.background).removeClass(n.mm(e.opts[o].position)).removeClass(n.mm(e.opts[o].zposition)),e.opts.classes&&a.$html.removeClass(e.opts.classes),a.$page.attr("style",a.$page.data(s.style)),e.vars.opened=!1,e.$menu.trigger(i.closed)},this.conf.transitionDuration),a.$html.removeClass(n.opening),this.$menu.trigger(i.closing),"close"},e[t].prototype.setPage=function(t){t||(t=e(this.conf[o].pageSelector,a.$body),t.length>1&&(t=t.wrapAll("<"+this.conf[o].pageNodetype+" />").parent())),t.addClass(n.page+" "+n.slideout),a.$page=t},e[t].prototype[o+"_initWindow"]=function(){a.$wndw.on(i.keydown,function(e){return a.$html.hasClass(n.opened)&&9==e.keyCode?(e.preventDefault(),!1):void 0});var s=0;a.$wndw.on(i.resize,function(e,t){if(t||a.$html.hasClass(n.opened)){var o=a.$wndw.height();(t||o!=s)&&(s=o,a.$page.css("minHeight",o))}}),e[t].prototype[o+"_initWindow"]=function(){}},e[t].prototype[o+"_initBlocker"]=function(){var s=e('<div id="'+n.blocker+'" class="'+n.slideout+'" />').appendTo(a.$body);s.on(i.touchstart,function(e){e.preventDefault(),e.stopPropagation(),s.trigger(i.mousedown)}).on(i.mousedown,function(e){e.preventDefault(),a.$html.hasClass(n.modal)||a.$allMenus.trigger(i.close)}),e[t].prototype[o+"_initBlocker"]=function(){}};var n,s,i,a}(jQuery);
/*	
 * jQuery mmenu buttonbars addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var n="mmenu",a="buttonbars";t[n].addons[a]={_init:function(n){this.opts[a],this.conf[a],this.__refactorClass(t("div",n),this.conf.classNames[a].buttonbar,"buttonbar"),t("."+i.buttonbar,n).each(function(){var n=t(this),a=n.children().not("input"),o=n.children().filter("input");n.addClass(i.buttonbar+"-"+a.length),o.each(function(){var n=t(this),i=a.filter('label[for="'+n.attr("id")+'"]');i.length&&n.insertBefore(i)})})},_setup:function(){},_add:function(){i=t[n]._c,o=t[n]._d,r=t[n]._e,i.add("buttonbar"),s=t[n].glbl}},t[n].defaults[a]={},t[n].configuration.classNames[a]={buttonbar:"Buttonbar"};var i,o,r,s}(jQuery);
/*	
 * jQuery mmenu counters addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var e="mmenu",n="counters";t[e].addons[n]={_init:function(e){var s=this,d=this.opts[n];this.conf[n],this.__refactorClass(t("em",e),this.conf.classNames[n].counter,"counter"),d.add&&e.each(function(){var e=t(this).data(o.parent);e&&(e.find("> em."+a.counter).length||e.prepend(t('<em class="'+a.counter+'" />')))}),d.update&&e.each(function(){var e=t(this),n=e.data(o.parent);if(n){var d=n.find("> em."+a.counter);d.length&&(e.is("."+a.list)||(e=e.find("> ."+a.list)),e.length&&!e.data(o.updatecounter)&&(e.data(o.updatecounter,!0),s._update(function(){var t=e.children().not("."+a.label).not("."+a.subtitle).not("."+a.hidden).not("."+a.search).not("."+a.noresultsmsg);d.html(t.length)})))}})},_setup:function(){var a=this.opts[n];"boolean"==typeof a&&(a={add:a,update:a}),"object"!=typeof a&&(a={}),a=t.extend(!0,{},t[e].defaults[n],a),this.opts[n]=a},_add:function(){a=t[e]._c,o=t[e]._d,s=t[e]._e,a.add("counter search noresultsmsg"),o.add("updatecounter"),d=t[e].glbl}},t[e].defaults[n]={add:!1,update:!1},t[e].configuration.classNames[n]={counter:"Counter"};var a,o,s,d}(jQuery);
/*	
 * jQuery mmenu dragOpen addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){function t(e,t,n){return t>e&&(e=t),e>n&&(e=n),e}var n="mmenu",o="dragOpen";e[n].addons[o]={_init:function(){},_setup:function(){if(this.opts.offCanvas){var s=this,p=this.opts[o],d=this.conf[o];if("boolean"==typeof p&&(p={open:p}),"object"!=typeof p&&(p={}),p=e.extend(!0,{},e[n].defaults[o],p),p.open){if(Hammer.VERSION<2)return;var f,c,h,m,u={},g=0,l=!1,v=!1,_=0,w=0;switch(this.opts.offCanvas.position){case"left":case"right":u.events="panleft panright",u.typeLower="x",u.typeUpper="X",v="width";break;case"top":case"bottom":u.events="panup pandown",u.typeLower="y",u.typeUpper="Y",v="height"}switch(this.opts.offCanvas.position){case"left":case"top":u.negative=!1;break;case"right":case"bottom":u.negative=!0}switch(this.opts.offCanvas.position){case"left":u.open_dir="right",u.close_dir="left";break;case"right":u.open_dir="left",u.close_dir="right";break;case"top":u.open_dir="down",u.close_dir="up";break;case"bottom":u.open_dir="up",u.close_dir="down"}var b=this.__valueOrFn(p.pageNode,this.$menu,r.$page);"string"==typeof b&&(b=e(b));var y=r.$page;switch(this.opts.offCanvas.zposition){case"front":y=this.$menu;break;case"next":y=y.add(this.$menu)}var $=new Hammer(b[0],p.vendors.hammer);$.on("panstart",function(e){switch(m=e.center[u.typeLower],s.opts.offCanvas.position){case"right":case"bottom":m>=r.$wndw[v]()-p.maxStartPos&&(g=1);break;default:m<=p.maxStartPos&&(g=1)}l=u.open_dir}).on(u.events+" panend",function(e){g>0&&e.preventDefault()}).on(u.events,function(e){if(f=e["delta"+u.typeUpper],u.negative&&(f=-f),f!=_&&(l=f>=_?u.open_dir:u.close_dir),_=f,_>p.threshold&&1==g){if(r.$html.hasClass(a.opened))return;g=2,s._openSetup(),s.$menu.trigger(i.opening),r.$html.addClass(a.dragging),w=t(r.$wndw[v]()*d[v].perc,d[v].min,d[v].max)}2==g&&(c=t(_,10,w)-("front"==s.opts.offCanvas.zposition?w:0),u.negative&&(c=-c),h="translate"+u.typeUpper+"("+c+"px )",y.css({"-webkit-transform":"-webkit-"+h,transform:h}))}).on("panend",function(){2==g&&(r.$html.removeClass(a.dragging),y.css("transform",""),s[l==u.open_dir?"_openFinish":"close"]()),g=0})}}},_add:function(){return"function"!=typeof Hammer?(e[n].addons[o]._init=function(){},e[n].addons[o]._setup=function(){},void 0):(a=e[n]._c,s=e[n]._d,i=e[n]._e,a.add("dragging"),r=e[n].glbl,void 0)}},e[n].defaults[o]={open:!1,maxStartPos:100,threshold:50,vendors:{hammer:{}}},e[n].configuration[o]={width:{perc:.8,min:140,max:440},height:{perc:.8,min:140,max:880}};var a,s,i,r}(jQuery);
/*	
 * jQuery mmenu fixedElements addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(o){var t="mmenu",d="fixedElements";o[t].addons[d]={_init:function(){if(this.opts.offCanvas){var o=this.conf.classNames[d].fixedTop,t=this.conf.classNames[d].fixedBottom,e=this.__refactorClass(a.$page.find("."+o),o,"fixed-top"),s=this.__refactorClass(a.$page.find("."+t),t,"fixed-bottom");e.add(s).appendTo(a.$body).addClass(i.slideout)}},_setup:function(){},_add:function(){i=o[t]._c,e=o[t]._d,s=o[t]._e,i.add("fixed-top fixed-bottom"),a=o[t].glbl}},o[t].defaults[d]={},o[t].configuration.classNames[d]={fixedTop:"FixedTop",fixedBottom:"FixedBottom"};var i,e,s,a}(jQuery);
/*	
 * jQuery mmenu footer addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var o="mmenu",e="footer";t[o].addons[e]={_init:function(a){var d=this,i=this.opts[e],r=t("div."+n.footer,this.$menu);r.length&&(i.update&&a.each(function(){var o=t(this),a=t("."+d.conf.classNames[e].panelFooter,o),u=a.html();u||(u=i.title);var l=function(){r[u?"show":"hide"](),r.html(u)};o.on(s.open,l),o.hasClass(n.current)&&l()}),t[o].addons.buttonbars&&t[o].addons.buttonbars._init.call(this,r))},_setup:function(){var a=this.opts[e];if("boolean"==typeof a&&(a={add:a,update:a}),"object"!=typeof a&&(a={}),a=t.extend(!0,{},t[o].defaults[e],a),this.opts[e]=a,a.add){var s=a.content?a.content:a.title;t('<div class="'+n.footer+'" />').appendTo(this.$menu).append(s),this.$menu.addClass(n.hasfooter)}},_add:function(){n=t[o]._c,a=t[o]._d,s=t[o]._e,n.add("footer hasfooter"),d=t[o].glbl}},t[o].defaults[e]={add:!1,content:!1,title:"",update:!1},t[o].configuration.classNames[e]={panelFooter:"Footer"};var n,a,s,d}(jQuery);
/*	
 * jQuery mmenu header addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){var t="mmenu",a="header";e[t].addons[a]={_init:function(s){var i=this,o=this.opts[a],l=(this.conf[a],e("."+n.header,this.$menu));if(l.length){if(o.update){var h=l.find("."+n.title),c=l.find("."+n.prev),f=l.find("."+n.next),p=l.find("."+n.close),u=!1;r.$page&&(u="#"+r.$page.attr("id"),p.attr("href",u)),s.each(function(){var t=e(this),s=t.find("."+i.conf.classNames[a].panelHeader),r=t.find("."+i.conf.classNames[a].panelPrev),l=t.find("."+i.conf.classNames[a].panelNext),p=s.html(),u=r.attr("href"),v=l.attr("href"),m=r.html(),b=l.html();p||(p=t.find("."+n.subclose).html()),p||(p=o.title),u||(u=t.find("."+n.subclose).attr("href"));var x=function(){h[p?"show":"hide"](),h.html(p),c[u?"attr":"removeAttr"]("href",u),c[u||m?"show":"hide"](),c.html(m),f[v?"attr":"removeAttr"]("href",v),f[v||b?"show":"hide"](),f.html(b)};t.on(d.open,x),t.hasClass(n.current)&&x()})}e[t].addons.buttonbars&&e[t].addons.buttonbars._init.call(this,l)}},_setup:function(){var s=this.opts[a];if(this.conf[a],"boolean"==typeof s&&(s={add:s,update:s}),"object"!=typeof s&&(s={}),"undefined"==typeof s.content&&(s.content=["prev","title","next"]),s=e.extend(!0,{},e[t].defaults[a],s),this.opts[a]=s,s.add){if(s.content instanceof Array){for(var d=e("<div />"),r=0,i=s.content.length;i>r;r++)switch(s.content[r]){case"prev":case"next":case"close":d.append('<a class="'+n[s.content[r]]+'" href="#"></a>');break;case"title":d.append('<span class="'+n.title+'"></span>');break;default:d.append(s.content[r])}d=d.html()}else var d=s.content;e('<div class="'+n.header+'" />').prependTo(this.$menu).append(d),this.$menu.addClass(n.hasheader)}},_add:function(){n=e[t]._c,s=e[t]._d,d=e[t]._e,n.add("header hasheader prev next close title"),r=e[t].glbl}},e[t].defaults[a]={add:!1,title:"Menu",update:!1},e[t].configuration.classNames[a]={panelHeader:"Header",panelNext:"Next",panelPrev:"Prev"};var n,s,d,r}(jQuery);
/*	
 * jQuery mmenu labels addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(l){var e="mmenu",s="labels";l[e].addons[s]={_init:function(e){var n=this.opts[s];this.__refactorClass(l("li",this.$menu),this.conf.classNames[s].collapsed,"collapsed"),n.collapse&&l("."+a.label,e).each(function(){var e=l(this),s=e.nextUntil("."+a.label,"."+a.collapsed);s.length&&(e.children("."+a.subopen).length||(e.wrapInner("<span />"),e.prepend('<a href="#" class="'+a.subopen+" "+a.fullsubopen+'" />')))})},_setup:function(){var a=this.opts[s];"boolean"==typeof a&&(a={collapse:a}),"object"!=typeof a&&(a={}),a=l.extend(!0,{},l[e].defaults[s],a),this.opts[s]=a},_add:function(){a=l[e]._c,n=l[e]._d,o=l[e]._e,a.add("collapsed uncollapsed"),t=l[e].glbl},_clickAnchor:function(l,e){if(e){var s=l.parent();if(s.is("."+a.label)){var n=s.nextUntil("."+a.label,"."+a.collapsed);return s.toggleClass(a.opened),n[s.hasClass(a.opened)?"addClass":"removeClass"](a.uncollapsed),!0}}return!1}},l[e].defaults[s]={collapse:!1},l[e].configuration.classNames[s]={collapsed:"Collapsed"};var a,n,o,t}(jQuery);
/*	
 * jQuery mmenu searchfield addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){function s(e){switch(e){case 9:case 16:case 17:case 18:case 37:case 38:case 39:case 40:return!0}return!1}var n="mmenu",t="searchfield";e[n].addons[t]={_init:function(n){var i=this,l=this.opts[t],d=this.conf[t];if(l.add){switch(l.addTo){case"menu":var c=this.$menu;break;case"panels":var c=n;break;default:var c=e(l.addTo,this.$menu).filter("."+a.panel)}c.length&&c.each(function(){var s=e(this),n=s.is("."+a.menu)?d.form?"form":"div":"li";if(!s.children(n+"."+a.search).length){if(s.is("."+a.menu))var t=i.$menu,r="prependTo";else var t=s.children().first(),r=t.is("."+a.subtitle)?"insertAfter":"insertBefore";var o=e("<"+n+' class="'+a.search+'" />');if("form"==n&&"object"==typeof d.form)for(var c in d.form)o.attr(c,d.form[c]);o.append('<input placeholder="'+l.placeholder+'" type="text" autocomplete="off" />'),o[r](t)}l.noResults&&(s.is("."+a.menu)&&(s=s.children("."+a.panel).first()),n=s.is("."+a.list)?"li":"div",s.children(n+"."+a.noresultsmsg).length||e("<"+n+' class="'+a.noresultsmsg+'" />').html(l.noResults).appendTo(s))})}if(this.$menu.children("."+a.search).length&&this.$menu.addClass(a.hassearch),l.search){var h=e("."+a.search,this.$menu);h.length&&h.each(function(){var n=e(this);if("menu"==l.addTo)var t=e("."+a.panel,i.$menu),d=i.$menu;else var t=n.closest("."+a.panel),d=t;var c=n.children("input"),h=i.__findAddBack(t,"."+a.list).children("li"),u=h.filter("."+a.label),f=h.not("."+a.subtitle).not("."+a.label).not("."+a.search).not("."+a.noresultsmsg),p="> a";l.showLinksOnly||(p+=", > span"),c.off(o.keyup+" "+o.change).on(o.keyup,function(e){s(e.keyCode)||n.trigger(o.search)}).on(o.change,function(){n.trigger(o.search)}),n.off(o.reset+" "+o.search).on(o.reset+" "+o.search,function(e){e.stopPropagation()}).on(o.reset,function(){n.trigger(o.search,[""])}).on(o.search,function(s,n){"string"==typeof n?c.val(n):n=c.val(),n=n.toLowerCase(),t.scrollTop(0),f.add(u).addClass(a.hidden),f.each(function(){var s=e(this);e(p,s).text().toLowerCase().indexOf(n)>-1&&s.add(s.prevAll("."+a.label).first()).removeClass(a.hidden)}),e(t.get().reverse()).each(function(s){var n=e(this),t=n.data(r.parent);if(t){var d=n.add(n.find("> ."+a.list)).find("> li").not("."+a.subtitle).not("."+a.search).not("."+a.noresultsmsg).not("."+a.label).not("."+a.hidden);d.length?t.removeClass(a.hidden).removeClass(a.nosubresults).prevAll("."+a.label).first().removeClass(a.hidden):"menu"==l.addTo&&(n.hasClass(a.opened)&&setTimeout(function(){t.trigger(o.open)},1.5*(s+1)*i.conf.openingInterval),t.addClass(a.nosubresults))}}),d[f.not("."+a.hidden).length?"removeClass":"addClass"](a.noresults),i._update()})})}},_setup:function(){var s=this.opts[t];this.conf[t],"boolean"==typeof s&&(s={add:s,search:s}),"object"!=typeof s&&(s={}),s=e.extend(!0,{},e[n].defaults[t],s),"boolean"!=typeof s.showLinksOnly&&(s.showLinksOnly="menu"==s.addTo),this.opts[t]=s},_add:function(){a=e[n]._c,r=e[n]._d,o=e[n]._e,a.add("search hassearch noresultsmsg noresults nosubresults"),o.add("search reset change"),i=e[n].glbl}},e[n].defaults[t]={add:!1,addTo:"menu",search:!1,placeholder:"Search",noResults:"No results found."},e[n].configuration[t]={form:!1};var a,r,o,i}(jQuery);
/*	
 * jQuery mmenu toggles addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){var t="mmenu",s="toggles";e[t].addons[s]={_init:function(t){var a=this;this.opts[s],this.conf[s],this.__refactorClass(e("input",t),this.conf.classNames[s].toggle,"toggle"),this.__refactorClass(e("input",t),this.conf.classNames[s].check,"check"),e("input."+c.toggle+", input."+c.check,t).each(function(){var t=e(this),s=t.closest("li"),l=t.hasClass(c.toggle)?"toggle":"check",n=t.attr("id")||a.__getUniqueId();s.children('label[for="'+n+'"]').length||(t.attr("id",n),s.prepend(t),e('<label for="'+n+'" class="'+c[l]+'"></label>').insertBefore(s.children("a, span").last()))})},_setup:function(){},_add:function(){c=e[t]._c,a=e[t]._d,l=e[t]._e,c.add("toggle check"),n=e[t].glbl}},e[t].defaults[s]={},e[t].configuration.classNames[s]={toggle:"Toggle",check:"Check"};var c,a,l,n}(jQuery);;
