/*!
 * http://www.shamasis.net/projects/ga/
 * Refer jquery.ga.debug.js
 * Revision: 13
 */
(function($){$.ga={};$.ga.load=function(uid,callback){jQuery.ajax({type:'GET',url:(document.location.protocol=="https:"?"https://ssl":"http://www")+'.google-analytics.com/ga.js',cache:true,success:function(){if(typeof _gat==undefined){throw"_gat has not been defined";}t=_gat._getTracker(uid);bind();if($.isFunction(callback)){callback(t)}t._trackPageview()},dataType:'script',data:null})};var t;var bind=function(){if(noT()){throw"pageTracker has not been defined";}for(var $1 in t){if($1.charAt(0)!='_')continue;$.ga[$1.substr(1)]=t[$1]}};var noT=function(){return t==undefined}})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * jQuery Corners 0.3
 * Copyright (c) 2008 David Turnbull, Steven Wittens
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
jQuery.fn.corners=function(C){var N="rounded_by_jQuery_corners";var V=B(C);var F=false;try{F=(document.body.style.WebkitBorderRadius!==undefined);var Y=navigator.userAgent.indexOf("Chrome");if(Y>=0){F=false}}catch(E){}var W=false;try{W=(document.body.style.MozBorderRadius!==undefined);var Y=navigator.userAgent.indexOf("Firefox");if(Y>=0&&parseInt(navigator.userAgent.substring(Y+8))<3){W=false}}catch(E){}return this.each(function(b,h){$e=jQuery(h);if($e.hasClass(N)){return }$e.addClass(N);var a=/{(.*)}/.exec(h.className);var c=a?B(a[1],V):V;var j=h.nodeName.toLowerCase();if(j=="input"){h=O(h)}if(F&&c.webkit){K(h,c)}else{if(W&&c.mozilla&&(c.sizex==c.sizey)){M(h,c)}else{var d=D(h.parentNode);var f=D(h);switch(j){case"a":case"input":Z(h,c,d,f);break;default:R(h,c,d,f);break}}}});function K(d,c){var a=""+c.sizex+"px "+c.sizey+"px";var b=jQuery(d);if(c.tl){b.css("WebkitBorderTopLeftRadius",a)}if(c.tr){b.css("WebkitBorderTopRightRadius",a)}if(c.bl){b.css("WebkitBorderBottomLeftRadius",a)}if(c.br){b.css("WebkitBorderBottomRightRadius",a)}}function M(d,c){var a=""+c.sizex+"px";var b=jQuery(d);if(c.tl){b.css("-moz-border-radius-topleft",a)}if(c.tr){b.css("-moz-border-radius-topright",a)}if(c.bl){b.css("-moz-border-radius-bottomleft",a)}if(c.br){b.css("-moz-border-radius-bottomright",a)}}function Z(k,n,l,a){var m=S("table");var i=S("tbody");m.appendChild(i);var j=S("tr");var d=S("td","top");j.appendChild(d);var h=S("tr");var c=T(k,n,S("td"));h.appendChild(c);var f=S("tr");var b=S("td","bottom");f.appendChild(b);if(n.tl||n.tr){i.appendChild(j);X(d,n,l,a,true)}i.appendChild(h);if(n.bl||n.br){i.appendChild(f);X(b,n,l,a,false)}k.appendChild(m);if(jQuery.browser.msie){m.onclick=Q}k.style.overflow="hidden"}function Q(){if(!this.parentNode.onclick){this.parentNode.click()}}function O(c){var b=document.createElement("a");b.id=c.id;b.className=c.className;if(c.onclick){b.href="javascript:";b.onclick=c.onclick}else{jQuery(c).parent("form").each(function(){b.href=this.action});b.onclick=I}var a=document.createTextNode(c.value);b.appendChild(a);c.parentNode.replaceChild(b,c);return b}function I(){jQuery(this).parent("form").each(function(){this.submit()});return false}function R(d,a,b,c){var f=T(d,a,document.createElement("div"));d.appendChild(f);if(a.tl||a.tr){X(d,a,b,c,true)}if(a.bl||a.br){X(d,a,b,c,false)}}function T(j,i,k){var b=jQuery(j);var l;while(l=j.firstChild){k.appendChild(l)}if(j.style.height){var f=parseInt(b.css("height"));k.style.height=f+"px";f+=parseInt(b.css("padding-top"))+parseInt(b.css("padding-bottom"));j.style.height=f+"px"}if(j.style.width){var a=parseInt(b.css("width"));k.style.width=a+"px";a+=parseInt(b.css("padding-left"))+parseInt(b.css("padding-right"));j.style.width=a+"px"}k.style.paddingLeft=b.css("padding-left");k.style.paddingRight=b.css("padding-right");if(i.tl||i.tr){k.style.paddingTop=U(j,i,b.css("padding-top"),true)}else{k.style.paddingTop=b.css("padding-top")}if(i.bl||i.br){k.style.paddingBottom=U(j,i,b.css("padding-bottom"),false)}else{k.style.paddingBottom=b.css("padding-bottom")}j.style.padding=0;return k}function U(f,a,d,c){if(d.indexOf("px")<0){try{console.error("%s padding not in pixels",(c?"top":"bottom"),f)}catch(b){}d=a.sizey+"px"}d=parseInt(d);if(d-a.sizey<0){try{console.error("%s padding is %ipx for %ipx corner:",(c?"top":"bottom"),d,a.sizey,f)}catch(b){}d=a.sizey}return d-a.sizey+"px"}function S(b,a){var c=document.createElement(b);c.style.border="none";c.style.borderCollapse="collapse";c.style.borderSpacing=0;c.style.padding=0;c.style.margin=0;if(a){c.style.verticalAlign=a}return c}function D(b){try{var d=jQuery.css(b,"background-color");if(d.match(/^(transparent|rgba\(0,\s*0,\s*0,\s*0\))$/i)&&b.parentNode){return D(b.parentNode)}if(d==null){return"#ffffff"}if(d.indexOf("rgb")>-1){d=A(d)}if(d.length==4){d=L(d)}return d}catch(a){return"#ffffff"}}function L(a){return"#"+a.substring(1,2)+a.substring(1,2)+a.substring(2,3)+a.substring(2,3)+a.substring(3,4)+a.substring(3,4)}function A(h){var a=255;var d="";var b;var e=/([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;var f=e.exec(h);for(b=1;b<4;b++){d+=("0"+parseInt(f[b]).toString(16)).slice(-2)}return"#"+d}function B(b,d){var b=b||"";var c={sizex:5,sizey:5,tl:false,tr:false,bl:false,br:false,webkit:true,mozilla:true,transparent:false};if(d){c.sizex=d.sizex;c.sizey=d.sizey;c.webkit=d.webkit;c.transparent=d.transparent;c.mozilla=d.mozilla}var a=false;var e=false;jQuery.each(b.split(" "),function(f,j){j=j.toLowerCase();var h=parseInt(j);if(h>0&&j==h+"px"){c.sizey=h;if(!a){c.sizex=h}a=true}else{switch(j){case"no-native":c.webkit=c.mozilla=false;break;case"webkit":c.webkit=true;break;case"no-webkit":c.webkit=false;break;case"mozilla":c.mozilla=true;break;case"no-mozilla":c.mozilla=false;break;case"anti-alias":c.transparent=false;break;case"transparent":c.transparent=true;break;case"top":e=c.tl=c.tr=true;break;case"right":e=c.tr=c.br=true;break;case"bottom":e=c.bl=c.br=true;break;case"left":e=c.tl=c.bl=true;break;case"top-left":e=c.tl=true;break;case"top-right":e=c.tr=true;break;case"bottom-left":e=c.bl=true;break;case"bottom-right":e=c.br=true;break}}});if(!e){if(!d){c.tl=c.tr=c.bl=c.br=true}else{c.tl=d.tl;c.tr=d.tr;c.bl=d.bl;c.br=d.br}}return c}function P(f,d,h){var e=Array(parseInt("0x"+f.substring(1,3)),parseInt("0x"+f.substring(3,5)),parseInt("0x"+f.substring(5,7)));var c=Array(parseInt("0x"+d.substring(1,3)),parseInt("0x"+d.substring(3,5)),parseInt("0x"+d.substring(5,7)));r="0"+Math.round(e[0]+(c[0]-e[0])*h).toString(16);g="0"+Math.round(e[1]+(c[1]-e[1])*h).toString(16);d="0"+Math.round(e[2]+(c[2]-e[2])*h).toString(16);return"#"+r.substring(r.length-2)+g.substring(g.length-2)+d.substring(d.length-2)}function X(f,a,b,d,c){if(a.transparent){G(f,a,b,c)}else{J(f,a,b,d,c)}}function J(k,z,p,a,n){var h,f;var l=document.createElement("div");l.style.fontSize="1px";l.style.backgroundColor=p;var b=0;for(h=1;h<=z.sizey;h++){var u,t,q;arc=Math.sqrt(1-Math.pow(1-h/z.sizey,2))*z.sizex;var c=z.sizex-Math.ceil(arc);var w=Math.floor(b);var v=z.sizex-c-w;var o=document.createElement("div");var m=l;o.style.margin="0px "+c+"px";o.style.height="1px";o.style.overflow="hidden";for(f=1;f<=v;f++){if(f==1){if(f==v){u=((arc+b)*0.5)-w}else{t=Math.sqrt(1-Math.pow(1-(c+1)/z.sizex,2))*z.sizey;u=(t-(z.sizey-h))*(arc-w-v+1)*0.5}}else{if(f==v){t=Math.sqrt(1-Math.pow((z.sizex-c-f+1)/z.sizex,2))*z.sizey;u=1-(1-(t-(z.sizey-h)))*(1-(b-w))*0.5}else{q=Math.sqrt(1-Math.pow((z.sizex-c-f)/z.sizex,2))*z.sizey;t=Math.sqrt(1-Math.pow((z.sizex-c-f+1)/z.sizex,2))*z.sizey;u=((t+q)*0.5)-(z.sizey-h)}}H(z,o,m,n,P(p,a,u));m=o;var o=m.cloneNode(false);o.style.margin="0px 1px"}H(z,o,m,n,a);b=arc}if(n){k.insertBefore(l,k.firstChild)}else{k.appendChild(l)}}function H(c,a,e,d,b){if(d&&!c.tl){a.style.marginLeft=0}if(d&&!c.tr){a.style.marginRight=0}if(!d&&!c.bl){a.style.marginLeft=0}if(!d&&!c.br){a.style.marginRight=0}a.style.backgroundColor=b;if(d){e.appendChild(a)}else{e.insertBefore(a,e.firstChild)}}function G(c,o,l,h){var f=document.createElement("div");f.style.fontSize="1px";var a=document.createElement("div");a.style.overflow="hidden";a.style.height="1px";a.style.borderColor=l;a.style.borderStyle="none solid";var m=o.sizex-1;var j=o.sizey-1;if(!j){j=1}for(var b=0;b<o.sizey;b++){var n=m-Math.floor(Math.sqrt(1-Math.pow(1-b/j,2))*m);if(b==2&&o.sizex==6&&o.sizey==6){n=2}var k=a.cloneNode(false);k.style.borderWidth="0 "+n+"px";if(h){k.style.borderWidth="0 "+(o.tr?n:0)+"px 0 "+(o.tl?n:0)+"px"}else{k.style.borderWidth="0 "+(o.br?n:0)+"px 0 "+(o.bl?n:0)+"px"}h?f.appendChild(k):f.insertBefore(k,f.firstChild)}if(h){c.insertBefore(f,c.firstChild)}else{c.appendChild(f)}}};


/* jTemplates 0.7.8 (http://jtemplates.tpython.com) Copyright (c) 2009 Tomasz Gloc */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('a(37.b&&!37.b.38){(9(b){6 m=9(s,A,f){5.1M=[];5.1u={};5.2p=E;5.1N={};5.1c={};5.f=b.1m({1Z:1f,3a:1O,2q:1f,2r:1f,3b:1O,3c:1O},f);5.1v=(5.f.1v!==F)?(5.f.1v):(13.20);5.Y=(5.f.Y!==F)?(5.f.Y):(13.3d);5.3e(s,A);a(s){5.1w(5.1c[\'21\'],A,5.f)}5.1c=E};m.y.2s=\'0.7.8\';m.R=1O;m.y.3e=9(s,A){6 2t=/\\{#14 *(\\w*?)( .*)*\\}/g;6 22,1x,M;6 1y=E;6 2u=[];2v((22=2t.3N(s))!=E){1y=2t.1y;1x=22[1];M=s.2w(\'{#/14 \'+1x+\'}\',1y);a(M==-1){C j Z(\'15: m "\'+1x+\'" 2x 23 3O.\');}5.1c[1x]=s.2y(1y,M);2u[1x]=13.2z(22[2])}a(1y===E){5.1c[\'21\']=s;c}N(6 i 24 5.1c){a(i!=\'21\'){5.1N[i]=j m()}}N(6 i 24 5.1c){a(i!=\'21\'){5.1N[i].1w(5.1c[i],b.1m({},A||{},5.1N||{}),b.1m({},5.f,2u[i]));5.1c[i]=E}}};m.y.1w=9(s,A,f){a(s==F){5.1M.B(j 1g(\'\',1,5));c}s=s.U(/[\\n\\r]/g,\'\');s=s.U(/\\{\\*.*?\\*\\}/g,\'\');5.2p=b.1m({},5.1N||{},A||{});5.f=j 2A(f);6 p=5.1M;6 1P=s.1h(/\\{#.*?\\}/g);6 16=0,M=0;6 e;6 1i=0;6 25=0;N(6 i=0,l=(1P)?(1P.V):(0);i<l;++i){6 17=1P[i];a(1i){M=s.2w(\'{#/1z}\');a(M==-1){C j Z("15: 3P 1Q 3f 1z.");}a(M>16){p.B(j 1g(s.2y(16,M),1,5))}16=M+11;1i=0;i=b.3Q(\'{#/1z}\',1P);1R}M=s.2w(17,16);a(M>16){p.B(j 1g(s.2y(16,M),1i,5))}6 3R=17.1h(/\\{#([\\w\\/]+).*?\\}/);6 26=I.$1;2B(26){q\'3S\':++25;p.27();q\'a\':e=j 1A(17,p);p.B(e);p=e;D;q\'J\':p.27();D;q\'/a\':2v(25){p=p.28();--25}q\'/N\':q\'/29\':p=p.28();D;q\'29\':e=j 1n(17,p,5);p.B(e);p=e;D;q\'N\':e=2a(17,p,5);p.B(e);p=e;D;q\'1R\':q\'D\':p.B(j 18(26));D;q\'2C\':p.B(j 2D(17,5.2p));D;q\'h\':p.B(j 2E(17));D;q\'2F\':p.B(j 2G(17));D;q\'3T\':p.B(j 1g(\'{\',1,5));D;q\'3U\':p.B(j 1g(\'}\',1,5));D;q\'1z\':1i=1;D;q\'/1z\':a(m.R){C j Z("15: 3V 2H 3f 1z.");}D;2I:a(m.R){C j Z(\'15: 3W 3X: \'+26+\'.\');}}16=M+17.V}a(s.V>16){p.B(j 1g(s.3Y(16),1i,5))}};m.y.K=9(d,h,z,H){++H;6 $T=d,2b,2c;a(5.f.3b){$T=5.1v(d,{2d:(5.f.3a&&H==1),1S:5.f.1Z},5.Y)}a(!5.f.3c){2b=5.1u;2c=h}J{2b=5.1v(5.1u,{2d:(5.f.2q),1S:1f},5.Y);2c=5.1v(h,{2d:(5.f.2q&&H==1),1S:1f},5.Y)}6 $P=b.1m({},2b,2c);6 $Q=(z!=F)?(z):({});$Q.2s=5.2s;6 19=\'\';N(6 i=0,l=5.1M.V;i<l;++i){19+=5.1M[i].K($T,$P,$Q,H)}--H;c 19};m.y.2J=9(1T,1o){5.1u[1T]=1o};13=9(){};13.3d=9(3g){c 3g.U(/&/g,\'&3Z;\').U(/>/g,\'&3h;\').U(/</g,\'&3i;\').U(/"/g,\'&40;\').U(/\'/g,\'&#39;\')};13.20=9(d,1B,Y){a(d==E){c d}2B(d.2K){q 2A:6 o={};N(6 i 24 d){o[i]=13.20(d[i],1B,Y)}a(!1B.1S){a(d.41("2L"))o.2L=d.2L}c o;q 42:6 o=[];N(6 i=0,l=d.V;i<l;++i){o[i]=13.20(d[i],1B,Y)}c o;q 2M:c(1B.2d)?(Y(d)):(d);q 43:a(1B.1S){a(m.R)C j Z("15: 44 45 23 46.");J c F}2I:c d}};13.2z=9(2e){a(2e===E||2e===F){c{}}6 o=2e.47(/[= ]/);a(o[0]===\'\'){o.48()}6 2N={};N(6 i=0,l=o.V;i<l;i+=2){2N[o[i]]=o[i+1]}c 2N};6 1g=9(2O,1i,14){5.2f=2O;5.3j=1i;5.1d=14};1g.y.K=9(d,h,z,H){6 2g=5.2f;a(!5.3j){6 2P=5.1d;6 $T=d;6 $P=h;6 $Q=z;2g=2g.U(/\\{(.*?)\\}/g,9(49,3k){1C{6 1D=10(3k);a(1E 1D==\'9\'){a(2P.f.1Z||!2P.f.2r){c\'\'}J{1D=1D($T,$P,$Q)}}c(1D===F)?(""):(2M(1D))}1F(e){a(m.R){a(e 1G 18)e.1j="4a";C e;}c""}})}c 2g};6 1A=9(L,1H){5.2h=1H;L.1h(/\\{#(?:J)*a (.*?)\\}/);5.3l=I.$1;5.1p=[];5.1q=[];5.1I=5.1p};1A.y.B=9(e){5.1I.B(e)};1A.y.28=9(){c 5.2h};1A.y.27=9(){5.1I=5.1q};1A.y.K=9(d,h,z,H){6 $T=d;6 $P=h;6 $Q=z;6 19=\'\';1C{6 2Q=(10(5.3l))?(5.1p):(5.1q);N(6 i=0,l=2Q.V;i<l;++i){19+=2Q[i].K(d,h,z,H)}}1F(e){a(m.R||(e 1G 18))C e;}c 19};2a=9(L,1H,14){a(L.1h(/\\{#N (\\w+?) *= *(\\S+?) +4b +(\\S+?) *(?:12=(\\S+?))*\\}/)){L=\'{#29 2a.3m 3n \'+I.$1+\' 2H=\'+(I.$2||0)+\' 1Q=\'+(I.$3||-1)+\' 12=\'+(I.$4||1)+\' u=$T}\';c j 1n(L,1H,14)}J{C j Z(\'15: 4c 4d "3o": \'+L);}};2a.3m=9(i){c i};6 1n=9(L,1H,14){5.2h=1H;5.1d=14;L.1h(/\\{#29 (.+?) 3n (\\w+?)( .+)*\\}/);5.3p=I.$1;5.x=I.$2;5.W=I.$3||E;5.W=13.2z(5.W);5.1p=[];5.1q=[];5.1I=5.1p};1n.y.B=9(e){5.1I.B(e)};1n.y.28=9(){c 5.2h};1n.y.27=9(){5.1I=5.1q};1n.y.K=9(d,h,z,H){1C{6 $T=d;6 $P=h;6 $Q=z;6 1r=10(5.3p);6 1U=[];6 1J=1E 1r;a(1J==\'3q\'){6 2R=[];b.1e(1r,9(k,v){1U.B(k);2R.B(v)});1r=2R}6 u=(5.W.u!==F)?(10(5.W.u)):(($T!=E)?($T):({}));6 s=1V(10(5.W.2H)||0),e;6 12=1V(10(5.W.12)||1);a(1J!=\'9\'){e=1r.V}J{a(5.W.1Q===F||5.W.1Q===E){e=1V.4e}J{e=1V(10(5.W.1Q))+((12>0)?(1):(-1))}}6 19=\'\';6 i,l;a(5.W.1W){6 2S=s+1V(10(5.W.1W));e=(2S>e)?(e):(2S)}a((e>s&&12>0)||(e<s&&12<0)){6 1K=0;6 3r=(1J!=\'9\')?(4f.4g((e-s)/12)):F;6 1s,1k;N(;((12>0)?(s<e):(s>e));s+=12,++1K){1s=1U[s];a(1J!=\'9\'){1k=1r[s]}J{1k=1r(s);a(1k===F||1k===E){D}}a((1E 1k==\'9\')&&(5.1d.f.1Z||!5.1d.f.2r)){1R}a((1J==\'3q\')&&(1s 24 2A)){1R}6 3s=u[5.x];u[5.x]=1k;u[5.x+\'$3t\']=s;u[5.x+\'$1K\']=1K;u[5.x+\'$3u\']=(1K==0);u[5.x+\'$3v\']=(s+12>=e);u[5.x+\'$3w\']=3r;u[5.x+\'$1U\']=(1s!==F&&1s.2K==2M)?(5.1d.Y(1s)):(1s);u[5.x+\'$1E\']=1E 1k;N(i=0,l=5.1p.V;i<l;++i){1C{19+=5.1p[i].K(u,h,z,H)}1F(2T){a(2T 1G 18){2B(2T.1j){q\'1R\':i=l;D;q\'D\':i=l;s=e;D;2I:C e;}}J{C e;}}}1l u[5.x+\'$3t\'];1l u[5.x+\'$1K\'];1l u[5.x+\'$3u\'];1l u[5.x+\'$3v\'];1l u[5.x+\'$3w\'];1l u[5.x+\'$1U\'];1l u[5.x+\'$1E\'];1l u[5.x];u[5.x]=3s}}J{N(i=0,l=5.1q.V;i<l;++i){19+=5.1q[i].K($T,h,z,H)}}c 19}1F(e){a(m.R||(e 1G 18))C e;c""}};6 18=9(1j){5.1j=1j};18.y=Z;18.y.K=9(d){C 5;};6 2D=9(L,A){L.1h(/\\{#2C (.*?)(?: 4h=(.*?))?\\}/);5.1d=A[I.$1];a(5.1d==F){a(m.R)C j Z(\'15: 4i 3o 2C: \'+I.$1);}5.3x=I.$2};2D.y.K=9(d,h,z,H){6 $T=d;6 $P=h;1C{c 5.1d.K(10(5.3x),h,z,H)}1F(e){a(m.R||(e 1G 18))C e;}c\'\'};6 2E=9(L){L.1h(/\\{#h 1T=(\\w*?) 1o=(.*?)\\}/);5.x=I.$1;5.2f=I.$2};2E.y.K=9(d,h,z,H){6 $T=d;6 $P=h;6 $Q=z;1C{h[5.x]=10(5.2f)}1F(e){a(m.R||(e 1G 18))C e;h[5.x]=F}c\'\'};6 2G=9(L){L.1h(/\\{#2F 4j=(.*?)\\}/);5.2U=10(I.$1);5.2V=5.2U.V;a(5.2V<=0){C j Z(\'15: 2F 4k 4l 4m\');}5.2W=0;5.2X=-1};2G.y.K=9(d,h,z,H){6 2Y=b.O(z,\'1X\');a(2Y!=5.2X){5.2X=2Y;5.2W=0}6 i=5.2W++%5.2V;c 5.2U[i]};b.1a.1w=9(s,A,f){a(s.2K===m){c b(5).1e(9(){b.O(5,\'2i\',s);b.O(5,\'1X\',0)})}J{c b(5).1e(9(){b.O(5,\'2i\',j m(s,A,f));b.O(5,\'1X\',0)})}};b.1a.4n=9(1L,A,f){6 s=b.2Z({1t:1L,1Y:1f}).3y;c b(5).1w(s,A,f)};b.1a.4o=9(30,A,f){6 s=b(\'#\'+30).2O();a(s==E){s=b(\'#\'+30).3z();s=s.U(/&3i;/g,"<").U(/&3h;/g,">")}s=b.4p(s);s=s.U(/^<\\!\\[4q\\[([\\s\\S]*)\\]\\]>$/3A,\'$1\');s=s.U(/^<\\!--([\\s\\S]*)-->$/3A,\'$1\');c b(5).1w(s,A,f)};b.1a.4r=9(){6 1W=0;b(5).1e(9(){a(b.2j(5)){++1W}});c 1W};b.1a.4s=9(){b(5).3B();c b(5).1e(9(){b.3C(5,\'2i\')})};b.1a.2J=9(1T,1o){c b(5).1e(9(){6 t=b.2j(5);a(t===F){a(m.R)C j Z(\'15: m 2x 23 3D.\');J c}t.2J(1T,1o)})};b.1a.31=9(d,h){c b(5).1e(9(){6 t=b.2j(5);a(t===F){a(m.R)C j Z(\'15: m 2x 23 3D.\');J c}b.O(5,\'1X\',b.O(5,\'1X\')+1);b(5).3z(t.K(d,h,5,0))})};b.1a.4t=9(1L,h,G){6 X=5;G=b.1m({1j:\'4u\',1Y:1O,32:1f},G);b.2Z({1t:1L,1j:G.1j,O:G.O,3E:G.3E,1Y:G.1Y,32:G.32,3F:G.3F,4v:\'4w\',4x:9(d){6 r=b(X).31(d,h);a(G.2k){G.2k(r)}},4y:G.4z,4A:G.4B});c 5};6 2l=9(1t,h,2m,2n,1b,G){5.3G=1t;5.1u=h;5.3H=2m;5.3I=2n;5.1b=1b;5.3J=E;5.33=G||{};6 X=5;b(1b).1e(9(){b.O(5,\'34\',X)});5.35()};2l.y.35=9(){5.3K();a(5.1b.V==0){c}6 X=5;b.4C(5.3G,5.3I,9(d){6 r=b(X.1b).31(d,X.1u);a(X.33.2k){X.33.2k(r)}});5.3J=4D(9(){X.35()},5.3H)};2l.y.3K=9(){5.1b=b.3L(5.1b,9(o){a(b.4E.4F){6 n=o.36;2v(n&&n!=4G){n=n.36}c n!=E}J{c o.36!=E}})};b.1a.4H=9(1t,h,2m,2n,G){c j 2l(1t,h,2m,2n,5,G)};b.1a.3B=9(){c b(5).1e(9(){6 2o=b.O(5,\'34\');a(2o==E){c}6 X=5;2o.1b=b.3L(2o.1b,9(o){c o!=X});b.3C(5,\'34\')})};b.1m({38:9(s,A,f){c j m(s,A,f)},4I:9(1L,A,f){6 s=b.2Z({1t:1L,1Y:1f}).3y;c j m(s,A,f)},2j:9(z){c b.O(z,\'2i\')},4J:9(14,O,3M){c 14.K(O,3M,F,0)},4K:9(1o){m.R=1o}})})(b)}',62,295,'|||||this|var|||function|if|jQuery|return|||settings||param||new|||Template|||node|case||||extData|||_name|prototype|element|includes|push|throw|break|null|undefined|options|deep|RegExp|else|get|oper|se|for|data|||DEBUG_MODE|||replace|length|_option|that|f_escapeString|Error|eval||step|TemplateUtils|template|jTemplates|ss|this_op|JTException|ret|fn|objs|_templates_code|_template|each|false|TextNode|match|literalMode|type|cval|delete|extend|opFOREACH|value|_onTrue|_onFalse|fcount|ckey|url|_param|f_cloneData|setTemplate|tname|lastIndex|literal|opIF|filter|try|__tmp|typeof|catch|instanceof|par|_currentState|mode|iteration|url_|_tree|_templates|true|op|end|continue|noFunc|name|key|Number|count|jTemplateSID|async|disallow_functions|cloneData|MAIN|iter|not|in|elseif_level|op_|switchToElse|getParent|foreach|opFORFactory|_param1|_param2|escapeData|optionText|_value|__t|_parent|jTemplate|getTemplate|on_success|Updater|interval|args|updater|_includes|filter_params|runnable_functions|version|reg|_template_settings|while|indexOf|is|substring|optionToObject|Object|switch|include|Include|UserParam|cycle|Cycle|begin|default|setParam|constructor|toString|String|obj|val|__template|tab|arr|tmp|ex|_values|_length|_index|_lastSessionID|sid|ajax|elementName|processTemplate|cache|_options|jTemplateUpdater|run|parentNode|window|createTemplate||filter_data|clone_data|clone_params|escapeHTML|splitTemplates|of|txt|gt|lt|_literalMode|__1|_cond|funcIterator|as|find|_arg|object|_total|prevValue|index|first|last|total|_root|responseText|html|im|processTemplateStop|removeData|defined|dataFilter|timeout|_url|_interval|_args|timer|detectDeletedNodes|grep|parameter|exec|closed|No|inArray|ppp|elseif|ldelim|rdelim|Missing|unknown|tag|substr|amp|quot|hasOwnProperty|Array|Function|Functions|are|allowed|split|shift|__0|subtemplate|to|Operator|failed|MAX_VALUE|Math|ceil|root|Cannot|values|has|no|elements|setTemplateURL|setTemplateElement|trim|CDATA|hasTemplate|removeTemplate|processTemplateURL|GET|dataType|json|success|error|on_error|complete|on_complete|getJSON|setTimeout|browser|msie|document|processTemplateStart|createTemplateURL|processTemplateToText|jTemplatesDebugMode'.split('|'),0,{}))
/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#",
		prev_text:"Prev",
		next_text:"Next",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}
		
		/**
		 * Calculate start and end point of pagination links depending on 
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}
		
		/**
		 * This is the event handling function for the pagination links. 
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ return pageSelected(page_id,evt); }
			}
			// Helper function for generating a single link (or a span tag if it's the current page)
			var appendItem = function(page_id, appendopts){
				page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
				appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
				if(page_id == current_page){
					var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/,page_id));
						
						
				}
				if(appendopts.classes){lnk.addClass(appendopts.classes);}
				panel.append(lnk);
			}
			// Generate "Previous"-Link
			if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
				appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
			}
			// Generate starting points
			if (interval[0] > 0 && opts.num_edge_entries > 0)
			{
				var end = Math.min(opts.num_edge_entries, interval[0]);
				for(var i=0; i<end; i++) {
					appendItem(i);
				}
				if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
			}
			// Generate interval links
			for(var i=interval[0]; i<interval[1]; i++) {
				appendItem(i);
			}
			// Generate ending points
			if (interval[1] < np && opts.num_edge_entries > 0)
			{
				if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
				var begin = Math.max(np-opts.num_edge_entries, interval[1]);
				for(var i=begin; i<np; i++) {
					appendItem(i);
				}
				
			}
			// Generate "Next"-Link
			if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
				appendItem(current_page+1,{text:opts.next_text, classes:"next"});
			}
		}
		
		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);
		// Attach control functions to the DOM element 
		this.selectPage = function(page_id){ pageSelected(page_id);}
		this.prevPage = function(){ 
			if (current_page > 0) {
				pageSelected(current_page - 1);
				return true;
			}
			else {
				return false;
			}
		}
		this.nextPage = function(){ 
			if(current_page < numPages()-1) {
				pageSelected(current_page+1);
				return true;
			}
			else {
				return false;
			}
		}
		// When all initialisation is done, draw the links
		drawLinks();
        // call callback function
        opts.callback(current_page, this);
	});
}



﻿/******** START GLOBAL VARIABLES *******/
//Need to make setup funtions etc use callbacks to ensure they finish
//Loggin also needs to be inproved so it is less it is auto matically called w/ action and so you don't have to remember to call it.. i.e. log() for search should be called within the search function or similar fashion... Need a listener to sense when anything w/ a LogItem class is called such that jquery attaces the event handlers to it.
//Need to better check form inputs
//change all cart delete to cart remove in funcions css etc.. aslo old logs
//Make parentcategory id in here, menu.ascx and on the search.ascx.cs be blank for null instead of -1
//User jquery.metadataplugin and jqquery ajaxform to more quickly grab json data to pose to forms
var User = { ID: "", Email: "", FirstName: "", LastName: "" };
var Filters = { AccountID: "", Active: "", AdvertisementID: "", AdvertiserID: "", CategoryChildren: "", CampaignID: "", CategoryID: 0, CategoryParentID: -1, EndDate: "", Featured: "", PageNumber: 1, PageSize: 10, PageTotal: 1, PublisherID: "", Radius: "", StartDate: "", Term: "", ViewType: "List", Zip: "" };
var LogItem = { AdvertisementID: "", Browser: "", BrowserVersion: "", Caller: "", Date: "", Description: "", DescriptionShort: "", IPAddress: "", LogTypeID: "", Referer: "", SearchAccountID: "", SearchAdvertisementID: "", SearchCampaignID: "", SearchCategoryID: "", SearchCount: "", SearchFeatured: "", SearchPageNumber: "", SearchPageSize: "", SearchPageTotal: "", SearchPublisherID: "", SearchRadius: "", SearchTerm: "", SearchViewType: "", SearchZip: "", SessionID: "", URL: "", UserID: "", DomainID: "" };
var LogTypes = { Visit: 1, Search: 2, Zoom: 3, Map: 4, Clip: 5, Print: 6, Click: 7, Other: 8, Payment: 9, Impression: 10, Register: 11, Login: 12, Logout: 13, UserEdit: 14 };
var SearchResults;
var SearchResultsCount = -1;
var SearchZipCode;
var SearchInProgress = 0;
var Cart = [];
var msie_x = 200;
var msie_y = 150;
var InitializationDone = 0;
var NationalBrandVendor = 0 ;
var GoogleAddressCheckInProgress = 0;
var FirstPage = 0;
var BannerLeft;
var BannerRight;
var Coupons = [];
var FreshPagination = 0;
var CookieOptions = { path: '/', expires: 100 };
var QSzip = 0;
var QSrad = 25;

/******** END GLOBAL VARIABLES *******/
/******** START INITIALIZATION *******/
$(document).ready(function() {
    QueryStringSetup();
    Log(LogTypes.Visit, "Initialize", "", "Visit", "Visit");
    Initialize();
    Background();
    return false;
});

function Initialize() {
    $('#DivBlock').fadeOut();
    /* These are items that are not loaded right away if prompt is called. */
    TopSetup();
    HeaderSetup();
    MenuSetup();
    NewNavSetup();
    PrintSetup();
    CartSetup();
    ContentSetup();
    LocationLauncherSetup();
    SearchSetup();
    MapSetup();
    //PaymentSetup();
    LocationSetup();
    // UserSetup();
    Log(LogTypes.Search, "Initialize", "", "Search: Initialize", "Search: Initialize");
    AnimateSetup();
    AdsSetup();
    Banner("Side", "Left");
    Banner("Side", "Right");
    LogSetup();
    InitializationDone = 1;
    Search();
    return false;
}

function Background() {
    /* Loads in background first even if prompt is displayed */
    LoadOnDemand("#DivUCHeader");
    LoadOnDemand("#DivUCContentTop");
    return false;
}
/******** END INITIALIZATION *******/
/******** SET UP MSIE CENTER *******/
function set_ie_center(dialog_selector) {

    // Bail If We're Already Set
    if (msie_x != 200) {
        return true;
    }

    // Branch And Set If We're IE        
    if (jQuery.browser.msie == true) {
        var e = window, a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }

        // Set The Window H/W
        var w = ($(dialog_selector).dialog('option', 'width') / 2);
        var h = ($(dialog_selector).dialog('option', 'height') / 2);

        // Now Set X/Y, Accounting For H/W
        var x = (e[a + 'Width'] / 2) - w;
        var y = (e[a + 'Height'] / 2) - h;

        // Save 'Em
        msie_x = x;
        msie_y = y;
    }
    return false;
}
/******** END SET UP MSIE CENTER *******/
/******** START LOGGING *******/
function LogSetup() {
    //All loggin setup should be in setup of the indivicdual modules unless it is a general log item not part of a module.
    // Setup logging for all other types of items links etc.  This should be called last to make sure that it catch all ondemand items and recalled if things change such that it won't be listening to new items
    $(".LogItem").click(function() { Log(LogTypes[$(this).attr('logtype')], $(this).attr('caller'), "", $(this).attr('description'), $(this).attr('descriptionshort')); });
    $('.UCListZoom').live("click", function() { Log(LogTypes.Zoom, ".UCListZoomTEST", SearchResults[$(this).attr('searchindex')].AdvertisementID, "Zoom", "Zoom"); });
    $('.UCListPic').live("click", function() { Log(LogTypes.Zoom, ".UCListPicTEST", SearchResults[$(this).attr('searchindex')].AdvertisementID, "Zoom", "Zoom"); });
    $('#UCZoomButtonMap').live("click", function() { Log(LogTypes.Map, "#UCZoomBottomTEST", SearchResults[$('#UCZoomData').attr('searchindex')].AdvertisementID, "Map: ZoomExpand", "Map: ZoomExpand"); });
    //might have to put these search logging items all in the actual search area..or leave them as on change
    $('.UCSearchSelectCategory').live("click", function() { /*Log(LogTypes.Search, ".UCSearchSelectCategory", "", "Search: Category", "Search: Category"); */ });
    return false;
}
function Log(logtypeid, caller, advertisementid, description, descriptionshort) {
    var logitem = LogItem;
    logitem.Browser = BrowserGet();
    logitem.BrowserVersion = $.browser.version;
    logitem.Caller = escape(caller);
    logitem.AdvertisementID = advertisementid;
    logitem.Date = Date();
    logitem.Description = description;
    logitem.DescriptionShort = descriptionshort;
    logitem.IPAddress = $(".IPAddress").text();
    logitem.LogTypeID = logtypeid;
    logitem.Referer = $(".Referer").text();
    logitem.SearchAccountID = Filters.AccountID;
    logitem.SearchAdvertisementID = Filters.AdvertisementID;
    logitem.SearchCampaignID = Filters.CampaignID;
    logitem.SearchCategoryID = Filters.CategoryID;
    logitem.SearchFeatured = Filters.Featured;
    logitem.SearchPageNumber = Filters.PageNumber;
    logitem.SearchPageSize = Filters.PageSize;
    logitem.SearchPageTotal = Filters.PageTotal;
    logitem.SearchPublisherID = Filters.PublisherID;
    logitem.SearchRadius = Filters.Radius;
    logitem.SearchTerm = Filters.Term;
    logitem.SearchViewType = Filters.ViewType;
    logitem.SearchZip = Filters.Zip;
    logitem.SessionID = $(".SessionID").text();
    logitem.URL = location.href;
    logitem.UserID = User.ID;
    logitem.DomainID = $(".DomainID").text();

    // Set Log URL And Make The Web Service Call
    var logurl = "Services/Coupons.svc/Log?advertisementid=" + logitem.AdvertisementID + "&browser=" + AjaxString(logitem.Browser) + "&browserversion=" + AjaxString(logitem.BrowserVersion) + "&caller=" + AjaxString(logitem.Caller) + "&date=" + AjaxString(logitem.Date) + "&description=" + AjaxString(AjaxClean(logitem.Description)) + "&descriptionshort=" + AjaxString(AjaxClean(logitem.DescriptionShort)) + "&ipaddress=" + AjaxString(logitem.IPAddress) + "&logtypeid=" + logitem.LogTypeID + "&referer=" + AjaxString(AjaxClean(logitem.Referer)) + "&searchaccountid=" + logitem.SearchAccountID + "&searchcampaignid=" + logitem.SearchCampaignID + "&searchcategoryid=" + logitem.SearchCategoryID + "&searchcount=" + logitem.SearchCount + "&searchfeatured=" + logitem.SearchFeatured + "&searchpagenumber=" + logitem.SearchPageNumber + "&searchpagesize=" + logitem.SearchPageSize + "&searchpagetotal=" + logitem.SearchPageTotal + "&searchpublisherid=" + logitem.SearchPublisherID + "&searchradius=" + logitem.SearchRadius + "&searchterm=" + AjaxString(AjaxClean(logitem.SearchTerm)) + "&searchviewtype=" + AjaxString(logitem.SearchViewType) + "&searchzip=" + AjaxString(logitem.SearchZip) + "&sessionid=" + AjaxString(logitem.SessionID) + "&url=" + AjaxString(AjaxClean(logitem.URL)) + "&userid=" + AjaxString(logitem.UserID) + "&domainid=" + AjaxString(logitem.DomainID);
    $.ajax({ type: "GET", url: logurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { LogResults(msg.d); } });
    return false;
}
function LogResults(results) {
    return false;
}
function LogPrintPreview() { Log(LogTypes.Print, "#UCCartBottom", "", "Print: Preview", "Print: Preview"); }
function LogPrint() {
    for (var i = 0; i < Cart.length; i++) {
        Log(LogTypes.Print, "#UCPrintButton", Cart[i].AdvertisementID, "Print", "Print");
    }
    return false;
}
/******** END LOGGING *******/

function LocationSetup() {

    // Use Zip From URL First
    if (checkZipCode(QSzip) == true) {
        Filters.Zip = QSzip;
        Filters.Radius = QSrad;
        $("#UCSearchZipcode").val(QSzip);
        $("#UCSearchSelectRadius").val(QSrad);
        QSzip = 0;
        QSrad = 25;
        return true;
    }

    // Check Cookie
    if (checkZipCode($.cookie("Location_Zip")) == true) {
        Filters.Zip = $.cookie("Location_Zip");
        Filters.Radius = 50;
        $("#UCSearchZipcode").val($.cookie("Location_Zip"));
        $("#UCSearchSelectRadius").val(Filters.Radius);
        return true;
    }

    //  Otherwise Prompt
    else {
        PromptSetup();
    }

    // And Return
    return false;
}

/******** START PROMPT *******/
function PromptSetup() {
    $('#DivUCPrompt').removeClass("Hidden");
    $("#UCPrompt").dialog({
        autoOpen: true,
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "UCPrompt",
        minWidth: 400,
        minHeight: 330,
        width: 400,
        height: 330,
        overlay: { opacity: .5, background: "#000000"}
    });

    // Save Off Our Center Coords For IE
    set_ie_center("#UCPrompt");

    // And Continue
    $('#UCPromptInputZipcode').keyup(function(e) { if (e.keyCode == 13) { PromptSubmit(); } });
    $("#UCPromptSubmit").click(PromptSubmit);
    $("#UCPromptInputZipcode").focus();
    return false;
}
function PromptSubmit() {
    ValidateLocale($("#UCPromptInputZipcode").val());
    return false;
}
function PromptComplete() {
    Filters.Zip = SearchZipCode;
    Filters.Radius = 50;
    // $("#UCPrompt").dialog("close");
    $("#UCPrompt").dialog("destroy");
    if (InitializationDone == 0) {
        Initialize();
    }
    else {
        if (SearchZipCode != null) {
            Filters.Zip = SearchZipCode;
        }
        Filters.PageNumber = 1;
        if (SearchZipCode != null) {
            $("#UCSearchZipcode").val(SearchZipCode);
        }
        else {
            $("#UCSearchZipcode").val(Filters.Zip);
        }
        $("#UCSearchSelectRadius").val(Filters.Radius);
        $("#UCSearchSelectRadius").removeAttr('disabled');
        $("#UCPromptInputZipcode").val("");
        Search();
        Log(LogTypes.Search, "#UCSearchZipcode", "", "Search: Zipcode", "Search: Zipcode");
        Banner("Side", "Left");
        Banner("Side", "Right");
    }
    return false;
}

/******** END PROMPT *******/
/******** START VALIDATE PROMPT *******/
function ValidateLocale(value) {

    // Null Out Search Zip
    SearchZipCode = null;

    // Check Zip
    if (checkZipCode(value) == true) {
        TrackEvent('New Location', 'Zip Code', value);
        PromptComplete();
        return false;
    }

    // Check City, State Entry
    else {
        TrackEvent('New Location', 'City, State', value);
        checkGoogleLatLng(value);
        return false;
    }
}
/******** END VALIDATE PROMPT *******/
/******** START CHECK ZIP CODE *******/
function checkZipCode(value) {
    var re = /^\d{5}([\-]\d{4})?$/;
    if (re.test(value) == true) {
        SearchZipCode = value;
        $.cookie("Location_Zip", SearchZipCode, CookieOptions);
        return true;
    }
    return false;
}
/******** END CHECK ZIP CODE *******/
/******** START GOOGLE ADDRESS CHECK *******/
function checkGoogleLatLng(address) {
    if (GoogleAddressCheckInProgress != 1) {
        GoogleAddressCheckInProgress = 1;
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(address, function(point) {
            if (!point) {
                GoogleAddressCheckInProgress = 0;
                jAlert("Sorry, we were unable to map that location!", "Coupon Network Location Mapper", PromptSetup());
                return false;
            }
            else {
                geocoder.getLocations(point, storeOffZip);
                return false;
            }
        });
    }
    return false;
}
/******** END GOOGLE ADDRESS CHECK *******/
/******** START STORE OFF ZIP CODE *******/
function storeOffZip(addr) {

    GoogleAddressCheckInProgress = 0;
    
    // Start Our Loop
    for (x = 0; x < 3; x++) {

        // SubAdministrativeArea
        if (addr.Placemark[x].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null) {
            if (addr.Placemark[x].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber != null) {
                SearchZipCode = addr.Placemark[x].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
            }
        }

        // No SubAdministrativeArea
        if (addr.Placemark[x].AddressDetails.Country.AdministrativeArea.Locality != null) {
            if (addr.Placemark[x].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber != null) {
                SearchZipCode = addr.Placemark[x].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
            }
        }

        $.cookie("Location_Zip", SearchZipCode, CookieOptions);

        // Wrap It Up
        if (SearchZipCode != null) {
            PromptComplete();
            x=3;
        }
    }
    return false;
}
/******** END STORE OFF ZIP CODE *******/
/******** START QUERYSTRING *******/
function QueryStringSetup() {
    var query = $.query(location.search);
    for (var k in query) {
        if (k.toString().toLowerCase() == "zip" || k.toString().toLowerCase() == "zipcode") { Filters.Zip = query[k].toString(); QSzip = Filters.Zip; }
        if (k.toString().toLowerCase() == "pagesize") { Filters.PageSize = parseInt(query[k]); }
        if (k.toString().toLowerCase() == "pagenumber") { Filters.PageNumber = parseInt(query[k]); }
        if (k.toString().toLowerCase() == "advertisementid") { Filters.AdvertisementID = parseInt(query[k]); }
        if (k.toString().toLowerCase() == "categoryid") { Filters.CategoryID = parseInt(query[k]); }
        if (k.toString().toLowerCase() == "categoryparentid") { Filters.CategoryParentID = parseInt(query[k]); }
        if (k.toString().toLowerCase() == "startdate") { Filters.StartDate = query[k].toString(); }
        if (k.toString().toLowerCase() == "enddate") { Filters.EndDate = query[k].toString(); }
        if (k.toString().toLowerCase() == "featured") { Filters.Featured = query[k].toString(); }
        if (k.toString().toLowerCase() == "active") { Filters.Active = query[k].toString(); }
        if (k.toString().toLowerCase() == "radius") { Filters.Radius = parseFloat(query[k]); QSrad = Filters.Radius; }
        if (k.toString().toLowerCase() == "viewtype") { Filters.ViewType = query[k].toString(); }
    }
    return false;
}
/******** END QUERYSTRING *******/
/******** START TOP *******/
function TopSetup() {
    $('#DivUCTop').removeClass("Hidden");
    return false;
}
/******** END TOP *******/
/******** START HEADER *******/
function HeaderSetup() {
    $('#DivUCHeader').removeClass("Hidden");
    // $('#UCHeaderNews').cycle({ timeout: 5000, speed: 500, next: '#UCHeaderNext', prev: '#UCHeaderPrevious', before: null, after: null, height: 'auto', sync: 1, fit: 0, pause: 0, delay: 0, slideExpr: null });
    return false;
}
/******** END HEADER *******/



/******** START MENU *******/
function MenuSetup() {
    $('#DivUCMenu').removeClass("Hidden");
    return false;
}
/******** END MENU *******/






/******** START SEARCH *******/
function SearchSetup() {

    /* Show Items */
    $('#DivUCSearch').removeClass("Hidden");
    $('#DivUCSearchBottom').removeClass("Hidden");
    $('#DivUCList').removeClass("Hidden");
    $('#DivLoading').removeClass("Hidden");
    $('#UCSearchViewList').hide();
    $('#UCSearchViewListBottom').hide();
    $('.UCSearchSelectCategory').addClass("Hidden");
    $('#UCSearchSelectCategory-0').removeClass("Hidden");

    /* Set Form Values */
    if (SearchZipCode != null) {
        $("#UCSearchZipcode").val(SearchZipCode);
    }
    else {
        $("#UCSearchZipcode").val(Filters.Zip);
    }
    $("#UCSearchSelectRadius").val(Filters.Radius);
    $("#UCSearchSelectRadius").removeAttr('disabled');


    /* Set Event Handlers */
    $('.UCSearchSelectCategory').change(function() {
        if (SearchInProgress != 1) {
            SearchInProgress = 1;
            Filters.PageNumber = 1;
            CategoryUpdate($(this).find(":selected").attr('categoryid'), $(this).find(":selected").attr('categoryparentid'));
            //Log(LogTypes.Search, ".UCSearchSelectCategory", "", "Search: Category", "Search: Category");
        }
    });

    // Zip Code Gets Changed w/ A Carriage Return
    $('#UCSearchZipcode').keyup(function(e) {
        if (e.keyCode == 13) {
            if (SearchInProgress != 1) {
                SearchInProgress = 1;
                ValidateLocale($('#UCSearchZipcode').val());
                if (SearchZipCode != null) {
                    Filters.Zip = SearchZipCode;
                }
                Filters.PageNumber = 1;
                Filters.Radius = $('#UCSearchSelectRadius').val();
                $("#UCSearchSelectRadius").val(Filters.Radius);
                $("#UCSearchSelectRadius").removeAttr('disabled');
                Search();
                Log(LogTypes.Search, "#UCSearchZipcode", "", "Search: Zipcode", "Search: Zipcode");
                Banner("Side", "Left");
                Banner("Side", "Right");
            }
        }
    });

    // Zip Code Gets Changed
    $('#UCSearchZipcode').change(function() {
    if (SearchInProgress != 1) {
        SearchInProgress = 1;
            ValidateLocale($('#UCSearchZipcode').val());
            if (SearchZipCode != null) {
                Filters.Zip = SearchZipCode;
            }
            Filters.PageNumber = 1;
            Filters.Radius = $('#UCSearchSelectRadius').val();
            $("#UCSearchSelectRadius").val(Filters.Radius);
            $("#UCSearchSelectRadius").removeAttr('disabled');
            Search();
            Log(LogTypes.Search, "#UCSearchZipcode", "", "Search: Zipcode", "Search: Zipcode");
            Banner("Side", "Left");
            Banner("Side", "Right");
        }
    });

    // Radius Changes
    $('#UCSearchSelectRadius').change(function() {
        if (SearchInProgress != 1) {
            SearchInProgress = 1;
            Filters.PageNumber = 1;
            Filters.Zip = $('#UCSearchZipcode').val();
            Filters.Radius = $('#UCSearchSelectRadius').val();
            Search();
            Log(LogTypes.Search, "#UCSearchSelectRadius", "", "Search: Radius", "Search: Radius");
        }
    });

    // Button Change
    $('#UCSearchButtonDistance').click(function() {
        if (SearchInProgress != 1) {
            SearchInProgress = 1;
            Filters.PageNumber = 1;
            Filters.Zip = $('#UCSearchZipcode').val();
            Filters.Radius = $('#UCSearchSelectRadius').val();
            Search();
            Log(LogTypes.Search, "#UCSearchButtonDistance", "", "Search: Distance", "Search: Distance");
            Banner("Side", "Left");
            Banner("Side", "Right");
        } 
    });

    // Search Term Change
    $('#UCSearchTerm').change(function() {
        if (SearchInProgress != 1) {
            SearchInProgress = 1;
            Filters.PageNumber = 1;
            Filters.Term = $('#UCSearchTerm').val();
            Search();
            Log(LogTypes.Search, "#UCSearchTerm", "", "Search: Term", "Search: Term");
        }
    });

    // Search Term Button
    $('#UCSearchButtonTerm').click(function() {
    if (SearchInProgress != 1) {
            SearchInProgress = 1;
            Filters.PageNumber = 1;
            Filters.Term = $('#UCSearchTerm').val();
            Search();
            Log(LogTypes.Search, "#UCSearchButtonTerm", "", "Search: Term", "Search: Term");
        }
    });

    $('#UCSearchViewMap').click(function() { ViewSwitch("Map"); });
    $('#UCSearchViewList').click(function() { ViewSwitch("List"); });
    $('#UCSearchViewMapBottom').click(function() { ViewSwitch("Map"); });
    $('#UCSearchViewListBottom').click(function() { ViewSwitch("List"); });

    // Reset SearchZipCode & SearchInProgress
    SearchInProgress = 0;
    return false;
}
function ViewSwitch(ViewType) {
    Filters.ViewType = ViewType;
    if (ViewType == "Map") {
        $('#UCList').hide();
        $('#UCMap').show();
        $('#UCSearchViewList').show();
        $('#UCSearchViewMap').hide();
        $('#UCSearchViewListBottom').show();
        $('#UCSearchViewMapBottom').hide();
    } else {
        $('#UCList').show();
        $('#UCMap').hide();
        $('#UCSearchViewList').hide();
        $('#UCSearchViewMap').show();
        $('#UCSearchViewListBottom').hide();
        $('#UCSearchViewMapBottom').show();
    }
    ViewUpdate();
    return false;
}

function ViewUpdate() {
    HideAllNonCoupons();
    if ($('#CouponBody').hasClass("Hidden")) {
        $('#CouponBody').removeClass("Hidden");
    }
    $('#CouponBody').css({ display: "block" });
    if (Filters.ViewType == "Map") {
        ViewMap();
    } else {
        ViewList();
    }
    Coupons = [];
    $.each(SearchResults, function(i, val) {
        Coupons.push(SearchResults[i].AdvertisementID);
    });
    return false;
}
function ViewList() {
    if ($('#UCList').hasTemplate() == 0) {
        $('#UCList').setTemplateElement("ListTemplate");
    }
    $('#UCList').processTemplate(SearchResults);
    $('.UCListClip').click(function() {
        CartAdd($(this).attr('advertisementid'), $(this).attr('accountname'), $(this).attr('offer'), $(this).attr('enddate'));
        Log(LogTypes.Clip, '.UCListClip', $(this).attr('advertisementid'), "Clip: Add", "Clip: Add");
    });
    ZoomSetup();
    return false;
}
function ViewMap() {
    Map();
    return false;
}

function Search() {
    //alert("Search caller is " + arguments.callee.caller.toString());
    var searchurl = "Services/Coupons.svc/Search?categoryid=" + Filters.CategoryID + "&pagenumber=" + Filters.PageNumber + "&pagesize=" + Filters.PageSize + "&zip=" + AjaxString(Filters.Zip) + "&radius=" + Filters.Radius + "&term=" + AjaxString(Filters.Term);
    ViewTransitionStart();
    $.ajax({ type: "GET", url: searchurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", complete: function() { ViewTransitionEnd(); }, success: function(msg) { SearchUpdate(msg.d); } });
    return false;
}

function SearchUpdate(data) {
    SearchResults = data;
    ViewUpdate();
    CountUpdate();
    return false;
}

function CountUpdate() {
    var SearchResultsCountTemp = 0;
    $.each(SearchResults, function(i, item) {
        SearchResultsCountTemp = this.SearchCount;
        return false;
    });
    TrackPageView("/Search?categoryid=" + Filters.CategoryID + "&pagenumber=" + Filters.PageNumber + "&pagesize=" + Filters.PageSize + "&zip=" + Filters.Zip + "&radius=" + Filters.Radius + "&term=" + AjaxString(Filters.Term) + "&view=" + Filters.ViewType);

    // Initialize Fresh Pagination As Needed
    if (SearchResultsCount != SearchResultsCountTemp) {
        SearchResultsCount = SearchResultsCountTemp;    
        initPagination();
        $("#Debug").html($("#Debug").html() + SearchResultsCount);
        Filters.PageTotal = Math.ceil(SearchResultsCount / Filters.PageSize);
    }

    PagerInfoUpdate(Filters.PageNumber, Filters.PageTotal, SearchResultsCount);
    SearchInProgress = 0;
    return false;
}

function CategoryUpdate(categoryid, categoryparentid) {
    Filters.CategoryID = categoryid;
    Filters.CategoryParentID = categoryparentid;
    $('.UCSearchSelectCategory').addClass("Hidden");
    if (categoryparentid > 0) {
        $('#UCSearchSelectCategory-' + categoryparentid).removeClass("Hidden");
    } else {
        $('#UCSearchSelectCategory-' + categoryid).removeClass("Hidden");
        $('#UCSearchSelectCategory-' + categoryid).attr('selectedIndex', 0);
    }

    Search(); //Logging called where CategoryUpdate is called

    Banner("Side", "Right");
    return false;
}
/******** END SEARCH *******/
/******** START BANNER *******/
function Banner(name, placement) {
    var siteid = $(".SiteID").text();
    var bannerurl = "Services/Coupons.svc/Banner?name=" + AjaxString(name) + "&placement=" + AjaxString(placement) + "&siteid=" + AjaxString(siteid) + "&zipcode=" + AjaxString(Filters.Zip) + "&categoryid=" + Filters.CategoryID;
    $.ajax({ type: "GET", url: bannerurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", complete: function() { return false; }, success: function(msg) { UpdateBanner(placement, msg.d); } });
    return false;
}
/******** END BANNER *******/
/******** END BANNER UPDATE *******/
function UpdateBanner(placement, banner) {

    // Set Local Values
    var id = $(banner).attr('ID');
    var url = $(banner).attr('WebsiteURL');
    var display = $(banner).attr('WebsiteDisplay');

    // Scope
    var template = null;

    // Set Our Image
    var img = "Assets/Images/Banners/" + id + ".jpg";
    if ($(banner).attr('Image') != null) {
        img = "Assets/Images/Banners/" + $(banner).attr('Image');
    }

    // Banners Right
    if (placement == "Right") {

        // Set Template
        template = $('#BannerRight').hasTemplate();
        if (template == 0) {
            $('#BannerRight').setTemplateElement("BannerRightTemplate");
        }
        
        // Now Build It
        $('#BannerRight').setParam("WebsiteURL", url);
        $('#BannerRight').setParam("WebsiteDisplay", display);
        $('#BannerRight').setParam("ImageSource", img);
        $('#BannerRight').setParam("BannerID", id);
        $('#BannerRight').processTemplate();

        // Save It
        BannerRight = id;
    }

    // Banners Left
    if (placement == "Left") {

        // Set Template
        template = $('#BannerLeft').hasTemplate();
        if (template == 0) {
            $('#BannerLeft').setTemplateElement("BannerLeftTemplate");
        }
        
        // Now Build It
        $('#BannerLeft').setParam("WebsiteURL", url);
        $('#BannerLeft').setParam("WebsiteDisplay", display);
        $('#BannerLeft').setParam("ImageSource", img);
        $('#BannerLeft').setParam("BannerID", id);
        $('#BannerLeft').processTemplate();

        // Save It
        BannerLeft = id;
    }
    return false;
}
/******** END BANNER UPDATE *******/
/******** START PAGINATION *******/
function pageit(ui) {
    Filters.PageNumber = ui + 1;
    if (FreshPagination != 1) {
        Search();
        Log(LogTypes.Search, "#UCSearchSlider", "", "Search: Slider", "Search: Slider");
    }
    else {
        FreshPagination = 0;
    }
    var paging = $("#Pagination").clone(true);
    $("#Pagination2").empty().html(paging);
    return false;
};
function initPagination() {
    FreshPagination = 1;
    $("#Pagination").pagination(SearchResultsCount, {
        num_edge_entries: 1,
        num_display_entries: 4,
        callback: pageit,
        items_per_page:10,
        next_show_always:false,
        prev_show_always:false        
    });
    return false;
}
function PagerInfoUpdate(pagenumber, pagetotal, numberitems) {
    $('#UCSearchInfo').html("Coupons Selected: " + numberitems);
    $('#UCSearchInfoBottom').html("Coupons Selected: " + numberitems);
}
/******** END PAGINATION *******/
function LocationLauncherSetup() {
    $('#DivUCLocationLauncher').removeClass("Hidden");
    $("#UCLocationLauncherImage").click(function() { PromptSetup(); });
}


/******** START CART *******/
function CartSetup() {
    $('#DivUCCart').removeClass("Hidden");
}
function CartAdd(advertisementid, accountname, offer, enddate) {
    Cart.push({
        AdvertisementID: advertisementid,
        AccountName: accountname,
        Offer: offer,
        EndDate: FormatDate(enddate)
    });
    TrackEvent('Coupons', 'Clip', advertisementid);
    CartUpdate();
    $.gritter.add({
        title: 'That Coupon Has Been Added To Your Cart!',
        text: 'Please use the <a href="#" onclick="javascript:PrintPreview();">print button</a> on your cart when you are done clipping coupons.',
        image: '/App_Themes/Common/Images/Gritter/growl_logo.gif',
        sticky: false,
        time: 7500
    });
    return false;
}
function CartRemove(index) {
    Cart.remove(parseInt(index), parseInt(index));
    CartUpdate();
    return false;
}
function CartUpdate() {
    if ($('#Cart').hasTemplate() == 0) {
        $('#Cart').setTemplateElement("CartTemplate");
    }
    $('#Cart').processTemplate(Cart);
    $('.UCCartDelete').click(function() {
        var advertisementid = Cart[$(this).attr('cartindex')].AdvertisementID;
        CartRemove($(this).attr('cartindex'));
        Log(LogTypes.Clip, '.UCCartDelete', advertisementid, "Clip: Remove", "Clip: Remove");
    });
    if (Cart.length == 0) {
        $('#DivCartEmpty').show();
    } else {
        $('#DivCartEmpty').hide();
    }
    $(".UCCartDetails").dialog({ autoOpen: false, modal: false, resizable: false, draggable: false, width: 272, height: 135, overlay: { opacity: 0.5, background: "black"} });
    $(".UCCartAccountName").hover(function() {
        var cartindex = $(this).attr('cartindex');
        $('.UCCartDetails[cartindex = ' + cartindex + ']').dialog("open");
    }, function() {
        var cartindex = $(this).attr('cartindex');
        $('.UCCartDetails[cartindex = ' + cartindex + ']').dialog("close");
    });
    return false;
}
/******** END CART *******/
/******** START PRINT *******/
function PrintSetup() {
    $('#DivUCPrint').removeClass("Hidden");
    $("#UCCartBottom").click(function() {
            PrintPreview();
            LogPrintPreview();
    });
    $("#UCPrintButton").click(function() {
        Print();
        LogPrint();
    });
    $("#UCPrintTopRight").click(function() {
        $("#UCPrint").dialog("close");
    });

    $("#UCPrint").dialog({ autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "UCPrintDialog",
        minWidth: 680,
        minHeight: 550,
        width: 680,
        height: 550,
        position: 'center',
        stack: 'true',
        zindex: 1500,
        overlay: { opacity: 0.5, background: "black" }
    });

    if (jQuery.browser.msie == true) {
        $("#UCPrint").dialog('option', 'position', [msie_x, msie_y]);
    }

}
function PrintPreview(AdID, EndDate) {
    if ($('#Print').hasTemplate() == 0) {
        $('#Print').setTemplateElement("PrintTemplate");
    }
    if (AdID != null) {
        $('#Print').processTemplate([{ AdvertisementID: AdID, EndDate: FormatDate(EndDate)}]);
        TrackEvent('Coupons', 'Print', AdID);
    }
    else {
        $('#Print').processTemplate(Cart);
        for (var i = 0; i < Cart.length; i++) {
            TrackEvent('Coupons', 'Print', Cart[i].AdvertisementID);
        }  
    }
    $('#Print').hide();
    $("#UCPrint").dialog("open");
    try {
        var oIframe = document.getElementById('IframePrint');
        var oContent = document.getElementById('Print').innerHTML;
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.write("<html><head><title>Florida Coupon Network</title>");
        oDoc.write("</head><body style='background-color:#ffffff;width:640px;' onload='this.focus();'>");
        oDoc.write(oContent + "</body></html>");
        oDoc.close();
    } catch (e) {}  
}
function Print() {
    PrintItem('Print');
}
function PrintItem(el) {
    try {
        var oIframe = document.getElementById('IframePrint');
        var oContent = document.getElementById(el).innerHTML;
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.write("<html><head><title>Florida Coupon Network</title>");
        jQuery.each(jQuery.browser, function(i) {
            //if (i == "msie" && jQuery.browser.version.substr(0, 1) == "7")
            if ($.browser.msie) {
                oDoc.write("</head><body style='background-color:#ffffff;width:640px;' onload='this.focus(); this.document.execCommand(\"print\", false, null);'>");
            } else {
                oDoc.write("</head><body style='background-color:#ffffff;width:640px;' onload='this.focus(); this.print();'>");
            }
        });
        oDoc.write(oContent + "</body></html>");
        oDoc.close();
    } catch (e) {
        self.execCommand('print', false, null)
    }
}
/******** END PRINT *******/
/******** START CONTENT *******/
function ContentSetup() {
    $('#DivUCContact').removeClass("Hidden");
    // $('#DivUCContentTop').removeClass("Hidden");
    //ContactSetup();
}
/******** END CONTENT *******/
/******** START CONTACT *******/
function ContactSetup() {
    $('#BodyOther').empty().html($('#MainContactDiv').html());
    UpdateContentBlock($('#BodyOther').html());
    $('#UCContactButtonSubmit').click(ContactSubmit);
    $('#UCContactButtonReset').click(ContactReset);
    $('#UCContactResults').hide();
}
function ContactSubmit() {
    var results = Email($('#UCContactInputName').attr("value"), $('#UCContactInputEmail').attr("value"), $('#UCContactInputPhone').attr("value"), $('#UCContactTextAreaComments').attr("value"));
    if (results == "success") {
        $('#UCContactForm').slideUp("normal");
        $('#UCContactResults').slideDown("normal");
    } else {
        alert(results);
    }
}
function ContactReset() {
    $('#UCContactInputName').attr("value", "");
    $('#UCContactInputEmail').attr("value", "");
    $('#UCContactInputPhone').attr("value", "");
    $('#UCContactTextAreaComments').attr("value", "");
    $('#UCContactResults').slideUp("normal");
    $('#UCContactForm').slideDown("normal");
}
/******** END CONTACT *******/
/******** START EMAIL *******/
function Email(name, email, phone, comments) {
    comments = AjaxClean(comments);
    name = AjaxClean(name);
    email = AjaxClean(email);
    phone = AjaxClean(phone);
    var searchurl = "Services/Coupons.svc/Email?name=" + AjaxString(name) + "&email=" + AjaxString(email) + "&phone=" + AjaxString(phone) + "&comments=" + AjaxString(comments);
    $.ajax({ async: false, type: "GET", url: searchurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { results = msg.d.Email; } });
    return results;
}
/******** END EMAIL *******/
/******** START TRACKING *******/
function TrackPageView(URL) {

    // Deal With Page Views
    if ($(".AnalyticsKey").text() != "UA-6997504-0") {
        if (FirstPage == 1) {
            $.ga.trackPageview(URL);
        }
        else {
            FirstPage = 1;
        }
    }

    // Deal With Impressions
    TrackImpressions();

    // And Return
    return false;
}
function TrackEvent(category, action, label) {
    if ($(".AnalyticsKey").text() != "UA-6997504-0") {
        $.ga.trackEvent(category, action, String(label));
    }
    return false;
}
function TrackImpressions() {

    // Set Up Banners
    if (BannerLeft == null) {
        BannerLeft = 0;
    }
    if (BannerRight == null) {
        BannerRight = 0;
    }
    var banners = BannerLeft + "," + BannerRight;

    // Set Up Coupons
    var coupons = Coupons.join(",");
    if (coupons.length == 0) {
        coupons = "0";
    }

    // Track It
    var impressionurl = "Services/Coupons.svc/Impressions?bannerids=" + AjaxString(banners) + "&couponids=" + AjaxString(coupons);
    $.ajax({ type: "GET", url: impressionurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", complete: function() { return false; }, success: function(msg) { return false; } });
    return false;
}
function TrackBannerClick(BannerID) {
    if (BannerID > 0) {
        var clickurl = "Services/Coupons.svc/BannerClicks?bannerid=" + BannerID;
        $.ajax({ type: "GET", url: clickurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", complete: function() { return false; }, success: function(msg) { return false; } });
    }
    return false;
}
/******** END TRACKING *******/
/******** START MAP *******/
function MapSetup() {
    $('#DivUCMap').removeClass("Hidden");
    $('#UCMap').hide();
}
function Map() {
    if (GBrowserIsCompatible()) {
        var couponIcon = new GIcon();
        couponIcon.image = "/Assets/Images/Map_Icon.png";
        couponIcon.shadow = "/Assets/Images/Map_Icon_Shadow.png";
        couponIcon.iconSize = new GSize(37, 36);
        couponIcon.shadowSize = new GSize(60, 38);
        couponIcon.iconAnchor = new GPoint(18, 18);
        couponIcon.infoWindowAnchor = new GPoint(18, 0);
        var map = new GMap2(document.getElementById("UCMapContent"), {
            size: new GSize(570, 450)
        });
        var address;
        var points = [];
        var markers = [];
        var infowindows = [];
        var i = new Number(0);
        $.each(SearchResults, function(i, val) {
            address = SearchResults[i].Address1 + " " + SearchResults[i].Address2 + ", " + SearchResults[i].City + ", " + SearchResults[i].State + ", " + SearchResults[i].Zipcode;
            var geocoder = new GClientGeocoder();
            infowindows.push("<div style='float:left;padding-right:8px;width:85px;height:85px;'><img src='/Assets/Images/Coupons/Thumbnails/" + SearchResults[i].AdvertisementID + ".jpg'></div><div style='float:left;padding-right:5px;'><span style='font-weight:bold; font-size:12px;color:#0a8db0;'>" + SearchResults[i].AccountName + "</span><br>" + SearchResults[i].Address1 + " " + SearchResults[i].Address2 + "<br>" + SearchResults[i].City + ", " + SearchResults[i].State + ", " + SearchResults[i].Zipcode + "</div><div style='clear:both'></div>");
            geocoder.getLatLng(address, function(point) {
                if (!point) {
                } else {
                    points.push(point);
                    if (points.length == 1) {
                        map.setCenter(point, 13);
                    }
                    var marker = new GMarker(point, { icon: couponIcon });
                    map.addOverlay(marker);
                    GEvent.addListener(marker, "click", function() {
                        i = Number(i);
                        marker.openInfoWindowHtml(infowindows[i]);
                    });
                    markers.push(marker);
                }
                if (points.length == Filters.PageSize) { MapFit(map, points) }
            });
        });
        map.enableScrollWheelZoom();
    }
    /* Removes logo and trademark for debugging, add back on live site */
}
function MapFit(mapfit, points) {
    var bounds = new GLatLngBounds();
    $.each(points, function(i, val) {
        bounds.extend(val);
    });
    mapfit.setZoom(mapfit.getBoundsZoomLevel(bounds));
    mapfit.setCenter(bounds.getCenter());
}
/******** END MAP *******/
/******** START ADS *******/
function AdsSetup() {
    $('#DivUCAdsLeft').removeClass("Hidden");
    $('#DivUCAdsRight').removeClass("Hidden");
}
/******** END ADS *******/
/******** START ANIMATE *******/
function AnimateSetup() {
    $("img[src*='Content_Top.png']").animate({
        opacity: 1
    }, 15000, "linear", function() {
        $("#DivUCContentTop").slideUp("slow");
    });
    //animate form inputs
    //annimate title graphics
    //Anumate buttons
}
/******** END ANIMATE *******/
/******** START MISCELLANEOUS *******/
function LoadOnDemand(context) {
    $(context).each(function() {
        $(context).html($(context).html().replace("<!--ONDEMAND", "").replace("ONDEMAND-->", ""));
    });
}
function showObject(obj) {
    var text = JSON.stringify(obj, null, '\t'); 
    alert (text);
}
function FormatDate(date) {
    var myDate = eval('new' + date.replace(/\//g, ' '));
    if (myDate.getFullYear() != null) {
        return (myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear();
    }
    return false;
}
jQuery.query = function(s) {
    var r = {};
    if (s) {
        var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
        q = q.replace(/\&$/, ''); // remove the trailing &
        jQuery.each(q.split('&'), function() {
            var splitted = this.split('=');
            var key = splitted[0];
            var val = splitted[1];
            // convert numbers
            if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
            // convert booleans
            if (val == 'true') val = true;
            if (val == 'false') val = false;
            // ignore empty values
            if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
        });
    }
    return r;
};
Array.prototype.remove = function(from, to) {
    this.splice(from, !to || 1 + to - from + (!(to < 0 ^ from >= 0) && (to < 0 || -1) * this.length));
    return this.length;
};
Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}
function BrowserGet() { if ($.browser.mozilla) { return "mozilla"; } else if ($.browser.msie) { return "msie"; } else if ($.browser.opera) { return "opera"; } else if ($.browser.safari) { return "safari"; } else { return ""; } }
function AjaxString(str) { return str == "" ? str : ("'" + str + "'"); }
function AjaxClean(str) {
    if (str != null) {
        return str = escape(str.toString()).replace("%27", "%60");
    }
    return null;
}
jQuery.fn.extend({
    slideUpForce: function(speed, callback) {
        ///	<summary>
        ///		Reveal all matched elements by adjusting their height, even if parent item is hidden.
        ///	</summary>
        ///	<param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
        ///		the number of milliseconds to run the animation</param>
        ///	<param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element.  It should map function callback() such that this is the DOM element being animated.</param>
        ///	<returns type="jQuery" />
        return this.slideUp(speed, function() {
            $(this).css("display", "none");
            if ($.isFunction(callback)) { callback.call(); }
        });
    }, slideDownForce: function(speed, callback) {
        ///	<summary>
        ///		Hide all matched elements by adjusting their height, even if parent item is hidden.
        ///	</summary>
        ///	<param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or
        ///		the number of milliseconds to run the animation</param>
        ///	<param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element.  It should map function callback() such that this is the DOM element being animated.</param>
        ///	<returns type="jQuery" />
        return this.slideDown(speed, function() {
            $(this).css("display", "block");
            if ($.isFunction(callback)) { callback.call(); }
        });
    }
});

// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;OK&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Cancel&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);
/*
 * Gritter for jQuery
 * http://www.boedesign.com/
 *
 * Copyright (c) 2009 Jordan Boesch
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: June 26, 2009
 * Version: 1.0
 */

jQuery(document).ready(function($){
 	
 	/********************************************
	 * First, we'll define our object
	 */
 	
	Gritter = {
	    
	    // PUBLIC - touch all you want
		fade_speed: 2000, // how fast the notices fade out
	    timer_stay: 6000, // how long you want the message to hang on screen for
	    
	    // PRIVATE - no touchy the private parts
		_custom_timer: 0,
	    _item_count: 0,
		_tpl_close: '<div class="gritter-close"></div>',
		_tpl_item: '<div id="gritter-item-[[number]]" class="gritter-item-wrapper" style="display:none"><div class="gritter-top"></div><div class="gritter-item">[[image]]<div class="[[class_name]]"><span class="gritter-title">[[username]]</span><p>[[text]]</p></div><div style="clear:both"></div></div><div class="gritter-bottom"></div></div>',
	    _tpl_wrap: '<div id="gritter-notice-wrapper"></div>',
	    
	    // Add a notification to the screen
	    add: function(user, text, image, sticky, time_alive){
	        
	        // This is also called from init, we just added it here because
	        // some people might just call the "add" method
	        this.verifyWrapper();
	        
	        var tmp = this._tpl_item;
	        this._item_count++;
			
			// reset
			this._custom_timer = 0;
			
			// a custom fade time set
			if(time_alive){
				this._custom_timer = time_alive;
			}
			
			var image_str = (image != '') ? '<img src="' + image + '" class="gritter-image" />' : '';
			var class_name = (image != '') ? 'gritter-with-image' : 'gritter-without-image';
			
	        tmp = this.str_replace(
	            ['[[username]]', '[[text]]', '[[image]]', '[[number]]', '[[class_name]]'],
	            [user, text, image_str, this._item_count, class_name], tmp
	        );
	        
	        $('#gritter-notice-wrapper').append(tmp);
	        var item = $('#gritter-item-' + this._item_count);
	        var number = this._item_count;
	        item.fadeIn();
	        
			if(!sticky){
				this.setFadeTimer(item, number);
			}
			
			$(item).hover(function(){
				if(!sticky){ 
					Gritter.restoreItemIfFading(this, number);
				}
				Gritter.hoveringItem(this);
			},
			function(){
				if(!sticky){
					Gritter.setFadeTimer(this, number);
				}
				Gritter.unhoveringItem(this);
			});
			
			return number;
	    
	    },
		
		// If we don't have any more gritter notifications, get rid of the wrapper
	    countRemoveWrapper: function(){
	        
	        if($('.gritter-item-wrapper').length == 0){
	            $('#gritter-notice-wrapper').remove();
	        }
	    
	    },
		
		// Fade the item and slide it up nicely... once its completely faded, remove it
	    fade: function(e){
	
	        $(e).animate({
	            opacity:0
	        }, Gritter.fade_speed, function(){
	            $(e).animate({ height: 0 }, 300, function(){
	                $(e).remove();
	                Gritter.countRemoveWrapper();
	            })
	        })
	        
	    },
		
		 // Change the border styles and add the (X) close button when you hover
	    hoveringItem: function(e){
	    	
	    	$(e).addClass('hover');
	    	
			if($(e).find('img').length){
				$(e).find('img').before(this._tpl_close);
			}
			else {
				$(e).find('span').before(this._tpl_close);
			}
			$(e).find('.gritter-close').click(function() {
			    Gritter.remove(this);
			});
			$(e).find('.gritter-item').click(function() {
			    Gritter.remove(this);
			});
	        
	    },
	    
	    // Remove a notification, this is called from the inline "onclick" event
	    remove: function(e){
	        
	        $(e).parents('.gritter-item-wrapper').fadeOut('medium', function(){ $(this).remove();  });
	        this.countRemoveWrapper();
	        
	    },
		
		// Remove a specific notification based on an id (int)
		removeSpecific: function(id, params){
			
			var e = $('#gritter-item-' + id);
			
			if(typeof(params) === 'object'){
				if(params.fade){
					var speed = this.fade_speed;
					if(params.speed){
						speed = params.speed;
					}
					e.fadeOut(speed);
				}
			}
			else {
				e.remove();
			}
			
			this.countRemoveWrapper();
			
		},
		
		 // If the item is fading out and we hover over it, restore it!
	    restoreItemIfFading: function(e, number){
			
			window.clearTimeout(Gritter['_int_id_' + number]);
	        $(e).stop().css({ opacity: 1 });
	        
	    },
	    
	    // Set the notification to fade out after a certain amount of time
	    setFadeTimer: function(item, number){
			
			var timer_str = (this._custom_timer) ? this._custom_timer : this.timer_stay;
	        Gritter['_int_id_' + number] = window.setTimeout(function(){ Gritter.fade(item); }, timer_str);
	
	    },
		
		// Bring everything to a halt!    
		stop: function(){
	
			$('#gritter-notice-wrapper').fadeOut(function(){
				$(this).remove();
			});
	
		},
		
		// A handy PHP function ported to js!
	    str_replace: function(search, replace, subject, count) {
	    
	        var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
	            f = [].concat(search),
	            r = [].concat(replace),
	            s = subject,
	            ra = r instanceof Array, sa = s instanceof Array;
	        s = [].concat(s);
	        if (count) {
	            this.window[count] = 0;
	            }
	 
	        for (i=0, sl=s.length; i < sl; i++) {
	            if (s[i] === '') {
	                continue;
	            }
	            for (j=0, fl=f.length; j < fl; j++) {
	                temp = s[i]+'';
	                repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
	                s[i] = (temp).split(f[j]).join(repl);
	                if (count && s[i] !== temp) {
	                    this.window[count] += (temp.length-s[i].length)/f[j].length;}
	            }
	        }
	        return sa ? s : s[0];
	        
	    },
	    
	    // Remove the border styles and (X) close button when you mouse out
	    unhoveringItem: function(e){
	        
	        $(e).removeClass('hover');
	        $(e).find('.gritter-close').remove();
	        
	    },
		
		// Make sure we have something to wrap our notices with
		verifyWrapper: function(){
	      
			if($('#gritter-notice-wrapper').length == 0){
				$('body').append(this._tpl_wrap);
			}
	 
		}
	    
	}
	
	/********************************************
	 * Now lets turn it into some jQuery Magic!
	 */
	
	// Set it up as an object
	$.gritter = {};
	
	// Add a gritter notification
	$.gritter.add = function(params){

		try {
			if(!params.title || !params.text){
				throw "Missing_Fields"; 
			}
		} catch(e) {
			if(e == "Missing_Fields"){
				alert('Gritter Error: You need to fill out the first 2 params: "title" and "text"');
			}
		}
		
		var id = Gritter.add(
			params.title,
			params.text,
			params.image || '',
			params.sticky || false,
			params.time || ''
		);
		
		return id;

	}
	
	// Remove a specific notification
	$.gritter.remove = function(id, params){
		Gritter.removeSpecific(id, params || '');
	}
	
	// Remove all gritter notifications
	$.gritter.removeAll = function(){
		Gritter.stop();
	}
	
});


function NewContentBlock() {
    // ViewTransitionStart();
    return false;
}

function UpdateContentBlock(NewContent) {

    HideObject($('#CouponBody'));

    $('#CenterContentBlock').empty().html(NewContent);
    if ($('#CenterContentBlock').hasClass("Hidden") == true) {
        $('#CenterContentBlock').removeClass("Hidden");
    }
    // ViewTransitionEnd();
}

function DisplayContent(What) {
    if (What == "RedPlum") {
        var String = RedPlum();
        $('#BodyOther').empty().html(String);
        UpdateContentBlock($('#BodyOther').html());
    }
    else if (What == "SmartSource") {
        var String = SmartSource();
        $('#BodyOther').empty().html(String);
        UpdateContentBlock($('#BodyOther').html());
    }
    return false;
}

function ViewTransitionStart() {
    $("#UCSearchSelectRadius").attr('disabled', "disabled");
    $("#DivLoading").fadeIn("fast");
    return false;
}
function ViewTransitionEnd() {
    $("#UCSearchSelectRadius").removeAttr('disabled');
    $("#DivLoading").fadeOut("slow");
    return false;
}

function HideAllNonCoupons() {
    HideObject($('#CenterContentBlock'));
    HideObject($('#BodyOther'));
    HideObject($('#CouponClipper'));
    return false;
}

function HideObject(Element) {
    if (Element.hasClass("Hidden") == false) {
        Element.addClass("Hidden");
    }
    if (Element.attr("id") == "CouponBody") {
        Element.css({ display: "none" });
    }
    return false;
}

function PhoneSubmit() {
    var Phone = stripNonNumerics($("#UCPhonePromptInputNumber").val());
    var CID = $("#UCPhonePromptInputCarrier").val();
    var SearchIndex = $('#UCZoomData').attr("searchindex");
    var AdID = SearchResults[SearchIndex].AdvertisementID;
    if (CID > 0 && isValidPhoneNumber(Phone) == true) {
        SendSMS(Phone, AdID, CID);
    }
    else {
        jAlert("Phone numbers must be at least 10 digits and you need to select a carrier.", "Send Coupon To Your Phone");    
    }
    return false;
}

function SendSMS(Phone, AdID, CID) {
    TrackEvent('Coupons', 'SMS', AdID);
    var Url = "Services/Coupons.svc/TextMessage?phone=" + AjaxString(Phone) + "&advertisementid=" + AdID + "&carrierid=" + CID;
    $.ajax({ type: "GET", url: Url, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { SMSSuccess(); } });
    return false;
}

function SMSSuccess() {
    $.gritter.add({
        title: 'Coupon Sent!',
        text: 'Those coupon details have been sent to your phone. You should see them arrive shortly.',
        image: '/App_Themes/Common/Images/Gritter/growl_logo.gif',
        sticky: false,
        time: 7500
    });
    $('#UCPhonePromptInputNumber').val('');
    $('#UCPhonePromptInputCarrier').find('option:first').attr('selected', 'selected').parent('select');
    return false;
}

function stripNonNumerics(Phone) {
    Phone = Phone.replace(/[^0-9]/g, '');
    return Phone;
}

function isValidPhoneNumber(ph) {
     if (ph == null) {
        return false;
    }
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
}

function EmailSubmit() {
    var NameF = $("#UCEmailPromptInYourName").val();
    NameF = AjaxClean(NameF);
    var EmailF = $("#UCEmailPromptInYourEmail").val();
    if (NameF == null || NameF.length == 0) { NameF = EmailF ; }
    var NameT = $("#UCEmailPromptInTheirName").val();
    NameT = AjaxClean(NameT);
    var EmailT = $("#UCEmailPromptInTheirEmail").val();
    if (NameT == null || NameT.length == 0) { NameT = EmailT ; }
    var Body = $("#UCEmailPromptInMessage").val();
    Body = AjaxClean(Body);

    var SearchIndex = $('#UCZoomData').attr("searchindex");
    var AdID = SearchResults[SearchIndex].AdvertisementID;

    if (isValidEmail(EmailF) == true && isValidEmail(EmailT) == true) {
        EmailFriend(NameF, EmailF, NameT, EmailT, Body, AdID);
    }
    else {
        jAlert("Please fill out all five fields and make sure the provided email addresses are valid.", "Email Coupon To A Friend");    
    }
    return false;
}

function EmailFriend(NameF, EmailF, NameT, EmailT, Body, AdID) {
    TrackEvent('Coupons', 'Email', AdID);
    var Url = "Services/Coupons.svc/EmailCoupon?namef=" + AjaxString(NameF) + "&emailf=" + AjaxString(EmailF) + "&namet=" + AjaxString(NameT) + "&emailt=" + AjaxString(EmailT) + "&body=" + AjaxString(Body) + "&advertisementid=" + AdID;
    $.ajax({ type: "GET", url: Url, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { EmailSuccess(); } });
    return false;
}

function EmailSuccess() {
    $.gritter.add({
        title: 'Coupon Sent!',
        text: 'Those coupon details have been emailed to your friend.',
        image: '/App_Themes/Common/Images/Gritter/growl_logo.gif',
        sticky: false,
        time: 7500
    });
    $('#UCEmailPromptInYourName').val('');
    $('#UCEmailPromptInYourEmail').val('');
    $('#UCEmailPromptInTheirName').val('');
    $('#UCEmailPromptInTheirEmail').val('');
    $('#UCEmailPromptInMessage').val('');
    return false;
}

function isValidEmail(email) {
    if (email == null) {
        return false;
    }
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return true;
    return (filter.test(email.value));
}

var PrevNavID = 99;
var CurrentNavID = 99;
var Zoomed = 0;

function ZoomSetup() {

    // Make Stuff Visible
    $('#DivUCZoom').removeClass("Hidden");

    // Set Up The Dialog
    $("#UCZoom").dialog({ autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "UCZoomDialog",
        width: 'auto',
        height: 'auto',
        position: 'center',
        stack: 'true',
        zindex: 3900,
        overlay: { opacity: 0.5, background: "black" }
    });

    // Set Up The Zoom Start Events
    $('.UCListZoom').click(function() { Zoom($(this).attr('searchindex')); });
    $('.UCListPic').click(function() { Zoom($(this).attr('searchindex')); });

    // Branch To Set Up Zoom Tab Events If They Haven't Already Been Set
    if (Zoomed == 0) {
        ZoomSetupEvents();
    }

    return false;
}

function ZoomSetupEvents() {

    // The Simple Zoom Events
    $('#UCZoomOptionPrint').click(function() {
        var searchindex = $('#UCZoomData').attr("searchindex")
        PrintPreview(SearchResults[searchindex].AdvertisementID, SearchResults[searchindex].EndDate);
        return false;
    });
    $('#UCZoomOptionCart').click(function() {
        var searchindex = $('#UCZoomData').attr("searchindex");
        CartAdd(SearchResults[searchindex].AdvertisementID, SearchResults[searchindex].AccountName, SearchResults[searchindex].Offer, SearchResults[searchindex].EndDate);
        Log(LogTypes.Clip, '.UCListClip', SearchResults[searchindex].AdvertisementID, "Clip: Add", "Clip: Add");
        return false;
    });
    $('#UCZoomCloseButton').click(function() {
        $('#UCZoom').dialog("close");
    });

    // Events For The Zoom Pages
    $('#UCZoomOptionCoupon').click(function() {
        CurrentNavID = 0;
        Zoom($('#UCZoomData').attr("searchindex"), "ZoomCoupon");
        return false;
    });
    $('#UCZoomOptionMap').click(function() {
        CurrentNavID = 1;
        Zoom($('#UCZoomData').attr("searchindex"), "ZoomMap");
        return false;
    });
    $('#UCZoomOptionPhone').click(function() {
        CurrentNavID = 5;
        Zoom($('#UCZoomData').attr("searchindex"), "ZoomPhone");
        $('#UCPhonePromptSubmit').click(PhoneSubmit);
        $('#UCPhonePromptInputNumber').focus();
        return false;
    });
    $('#UCZoomOptionEmail').click(function() {
        CurrentNavID = 6;
        Zoom($('#UCZoomData').attr("searchindex"), "ZoomEmail");
        $('#UCEmailPromptSubmit').click(EmailSubmit);
        $('#UCEmailPromptInYourName').focus();
        return false;
    });

    // Flag Setup As Done
    Zoomed = 1;
}

function Zoom(searchindex, template) {

    // Track
    TrackEvent('Coupons', 'Zoom', SearchResults[searchindex].AdvertisementID);

    // Do Some Setup
    $('#UCZoomData').attr("searchindex", searchindex);
    $('#UCZoom').dialog("open");
    $('.ui-dialog.UCZoomDialog').css({ width: "365px", height: "475px" });
    $('#UCZoom').css({ width: "365px", height: "475px" });

    // Default The Tempate
    if (template == null) {
        template = "ZoomCoupon";
        CurrentNavID = 0;
    }

    // Set Our Template
    $('#UCZoomContentBody').setTemplateElement(template);
    $('#UCZoomContentBody').processTemplate(SearchResults[searchindex]);

    // The Coupon Zoom Page
    if (template == "ZoomCoupon") {
        $('#UCZoomPic').html("<img src='/Assets/Images/Coupons/" + SearchResults[searchindex].AdvertisementID + ".jpg' />");
    }

    // The Map Page
    if (template == "ZoomMap") {
        ZoomMap($('#UCZoomData').attr("searchindex"));
    }

    // These Items Are Shown On Every Zoom Page
    $('#UCZoomOffer').html(SearchResults[searchindex].Offer);
    var exp = FormatDate(SearchResults[searchindex].EndDate);
    if (exp != null) {
        $('#UCZoomExpiration').html("Expires: " + exp);
    }

    // Sort Our Web Address And Account Name
    if (SearchResults[searchindex].ShowWebsite == true) {
        // $('#UCZoomWebsite').html("<a href='" + SearchResults[searchindex].WebsiteURL + "' target='_blank'>" + SearchResults[searchindex].WebsiteDisplay + "</a>");
        $('#UCZoomAccount').html("<a href='" + SearchResults[searchindex].WebsiteURL + "' target='_blank'>" + SearchResults[searchindex].AccountName + "</a>");
    }
    else {
        $('#UCZoomAccount').html(SearchResults[searchindex].AccountName);
    }

    // Turn Off The Map HREF If We Don't Have An Address To Map
    if (SearchResults[searchindex].ShowAddress == false) {
        $("#ZoomNav > li:eq(1)").hide();
        $("#ZoomNav > li:eq(2)").show();
        $('#UCZoomOptionMapOff').removeAttr("href");
        $('#UCZoomOptionMapOff').unbind('click');
        $('#UCZoomOptionMapOff').css({ cursor: "default", color: "White" });
    }
    else {
        $("#ZoomNav > li:eq(2)").hide();
        $("#ZoomNav > li:eq(1)").show();
    }    

    // Set Our Tabs
    SetZoomTabs();

    return false;
}

function SetZoomTabs() {
    $("#ZoomNav > li:eq(" + PrevNavID + ")").attr("id", "");
    $("#ZoomNav > li:eq(" + CurrentNavID + ")").attr("id", "current");
    PrevNavID = CurrentNavID;
    return false;
}

function ZoomMap(searchindex) {

    // Track It
    TrackEvent('Coupons', 'Map', SearchResults[searchindex].AdvertisementID);

    // Map It If We Can
    if (GBrowserIsCompatible()) {
        var zoomaddress = SearchResults[searchindex].Address1 + " " + SearchResults[searchindex].Address2 + ", " + SearchResults[searchindex].City + ", " + SearchResults[searchindex].State + ", " + SearchResults[searchindex].Zipcode;
        var zoominfowindow = "<span style='font-weight:bold; font-size:12px;color:#0a8db0;'>" + SearchResults[searchindex].AccountName + "</span><br>" + SearchResults[searchindex].Address1 + " " + SearchResults[searchindex].Address2 + "<br>" + SearchResults[searchindex].City + ", " + SearchResults[searchindex].State + ", " + SearchResults[searchindex].Zipcode;
        var zoommap = new GMap2(document.getElementById("UCZoomMap"));
        var zoomgeocoder = new GClientGeocoder();
        zoomgeocoder.getLatLng(zoomaddress, function(zoompoint) {
            if (!zoompoint) {
            } else {
                zoommap.setCenter(zoompoint, 14);
                var zoomcouponIcon = new GIcon();
                zoomcouponIcon.image = "/Assets/Images/Map_Icon.png";
                zoomcouponIcon.shadow = "/Assets/Images/Map_Icon_Shadow.png";
                zoomcouponIcon.iconSize = new GSize(37, 36);
                zoomcouponIcon.shadowSize = new GSize(60, 38);
                zoomcouponIcon.iconAnchor = new GPoint(18, 18);
                zoomcouponIcon.infoWindowAnchor = new GPoint(18, 0);
                var zoommarker = new GMarker(zoompoint, { icon: zoomcouponIcon });
                zoommap.addOverlay(zoommarker);
                zoommarker.openInfoWindowHtml(zoominfowindow);
                zoommap.setCenter(zoompoint, 14);
            }
        });
        zoommap.enableScrollWheelZoom();
    }
    else {
        alert("Sorry!  Your browser isn't compatible with Google Maps.  Please consider upgrading.");
    }
    return false;
}

// Set Handlers, Defaults And Classes
function NewNavSetup() {
    HideAllNonCoupons();
    $('#NewNavMain li').click( MainNavChange );
    SelectMainNav(0);
    SelectSubNav(0);
    $('#NewNav').removeClass("Hidden");
    return false;
}

// Changes To Main Navigation
function MainNavChange() {
    HideAllNonCoupons();
    NewContentBlock();
    var ID = $("#NewNavMain li").index(this);
    SelectMainNav(ID);

    // Default To All For Local
    if (ID == 0) {
        SelectSubNav(0);
        Filters.PageNumber = 1;
        CategoryUpdate(0, -1);
    }

    // Default To Splash Page For National
    if (ID == 1) {
        if ($('#BodyOther').hasTemplate() > 0) {
            $('#BodyOther').removeTemplate();
        }
        $('#BodyOther').setTemplateElement("NationalSplash");
        $('#BodyOther').empty().processTemplate();
        $('#BodyOther').css({ display: "block" });
        UpdateContentBlock($('#BodyOther').html());
    }

    return false;
}

// Changes To Sub Navigation
function SubNavChange(ID) {
    HideAllNonCoupons();
    NewContentBlock();
    if (ID >= 0) {
    }
    else {
        ID = $("#NewNavBottom li").index(this);
    }
    SelectSubNav(ID);

    // Set Various Values
    var catid = $("#NewNavBottom li:eq(" + ID + ") > a").attr('categoryid');
    var parentid = $("#NewNavBottom li:eq(" + ID + ") > a").attr('categoryparentid');
    var vendorid = $("#NewNavBottom li:eq(" + ID + ") > a").attr('NationalBrandVendor');

    // Branch To Handle Category Changes
    if (catid >= 0 && catid != 7) {
        Filters.PageNumber = 1;
        CategoryUpdate(catid, parentid);
        Log(LogTypes.Search, ".MenuItem", "", "Search: Category", "Search: Category");
    }

    // Branch To Handle Vendors And Splash Pages
    else {
        if (catid == 7) {
            if ($('#BodyOther').hasTemplate() > 0) {
                $('#BodyOther').removeTemplate();
            }
            $('#BodyOther').setTemplateElement("GrocerySplash");
            $('#BodyOther').empty().processTemplate();
            UpdateContentBlock($('#BodyOther').html());
        }
        else if (vendorid == 1) {
            var String = RedPlum();
            $('#BodyOther').empty().html(String);
            UpdateContentBlock($('#BodyOther').html());
        }
        else if (vendorid == 2) {
            var String = SmartSource();
            $('#BodyOther').empty().html(String);
            UpdateContentBlock($('#BodyOther').html());
        }
        else if (vendorid == 3) {
            HideAllNonCoupons();
            $('#CouponClipper').removeClass("Hidden");
            ViewTransitionEnd();
        }
    }

    return false;
}

// Selects The New Tab, Adds Black, Deselects The Old Tab
function SelectMainNav(ID) {

    // Deal With The Tabs
    UnselectMainNav();
    $("#NewNavMain li:eq(" + ID + ")").attr("id", "SelectedMain");

    // Fix Our Span Color
    $("#NewNavMain li:eq(" + ID + ") > a > span").removeClass("green").addClass("white");

    // Build The Sub Navigation
    BuildSubNav(ID);

    // And We're Done
    return false;
}

// Removes SelectedMain, White, Adds Back Green
function UnselectMainNav() {
    if ($("#NewNavMain > li[id='SelectedMain'] > a > span").length != 0) {
        $("#NewNavMain > li[id='SelectedMain'] > a > span").removeClass("white").addClass("green");
        $("#NewNavMain > li[id='SelectedMain']").attr("id", "None");
    }
    return false;
}

// Selects The New Tab, Adds Black, Deselects The Old Tab
function SelectSubNav(ID) {

    // Deal With The Tabs
    UnselectSubNav();
    $("#NewNavBottom li:eq(" + ID + ")").attr("id", "SelectedSub");

    // Fix Our Span Color
    $("#NewNavBottom li:eq(" + ID + ") > a").addClass("black");

    // And We're Done
    return false;
}

// Removes SelectedSub, Black
function UnselectSubNav() {
    if ($("#NewNavBottom > li[id='SelectedSub'] > a").length != 0) {
        $("#NewNavBottom > li[id='SelectedSub'] > a").removeClass("black");
        $("#NewNavBottom > li[id='SelectedSub']").attr("id", "None");
    }
    return false;
}

// Set Our Template & Load In Our Subnavigation
function BuildSubNav(ID) {
    var template = "Sub" + ID;
    if ($('#NewNavBottom').hasTemplate() > 0) {
        $('#NewNavBottom').removeTemplate();
    }
    $("#NewNavBottom").setTemplateElement(template);
    $("#NewNavBottom").processTemplate();
    $('#NewNavBottom li').click( SubNavChange );
    return false;
}


// Red Plum
function RedPlum() {
    TrackEvent('National Brand Coupons', 'Red Plum');
    var String = '<iframe id="host_iframe" name="host_iframe" src="http://coupons.redplum.com/RedPlumWidget/Offers_Narrow_Local_National.aspx?HostName=' + $(".RedPlum").text() + '&DefaultZipCode=' + Filters.Zip + '" scrolling="YES" frameborder="0" width="590" height="1760"></iframe>';
    return String;
}

// Smart Source
function SmartSource() {
    TrackEvent('National Brand Coupons', 'Smart Source');
    var String = '<iframe src="http://coupons.smartsource.com/WEB/index.aspx?Link=' + $(".SmartSource").text() + '" width="590px" height="2900" scrolling="auto" frameborder="0" style="border: 0px"></iframe>';
    return String;
}

/** 
 * @depends jquery.ga.js
 * @depends jquery.cookie.js
 * @depends jquery.corners.min.js
 * @depends jquery-jtemplates.js
 * @depends jquery.pagination.js
 * @depends Coupon.js
 * @depends jquery.alerts.js
 * @depends jquery.gritter.js
 * @depends Display.js
 * @depends SendToPhone.js
 * @depends SendToFriend.js
 * @depends Zoom.js
 * @depends Navigation.js
 * @depends Affiliates.js
 */  

