/*!
 * 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'>"+commify(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+commify(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: "", Referrer: "" };
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, Phone: 15, Email: 16, BannerImpression: 17, BannerClick: 18, PrintPreview: 19, SendToVendor: 20, SendToBusiness: 21, CarouselZoom: 22, CarouselImpression: 23 };
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 Coupons = [];
var FreshPagination = 0;
var CookieOptions = { path: '/', expires: 100 };
var QSzip = 0;
var QSrad = 20;
var QSDone = 0;
var FadeOutDone = 0;
var FadeInDone = 0;
var PrintPreviewList = [];
var geocoder;

/******** 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();
    Banner("Side", "Left");
    Banner("Side", "Right");
    BannerStartUp();
    LogSetup();
    FadeInCCCBanner();
    InitializationDone = 1;

    // Deal With The Carousel
    FetchCarouselCoupons();
    SetCarouselHeader();

    // Check For Content
    if (checkContentCall() === true) {
        makeContentCall();
    }
    else if (checkCouponCall() === true) {
        makeCouponCall();
        Search();
    }
    else {
        Search();
    }

    // And Out
    return false;
}

function Background() {
    /* Loads in background first even if prompt is displayed */
    LoadOnDemand("#DivUCHeader");
    LoadOnDemand("#DivUCContentTop");
    $("#DivUCFooter").removeClass("Hidden");
    return false;
}

function FadeInCCCBanner() {
    if (FadeOutDone == 1) {
        return false;
    }
    var SS = $(".SiteState").text();
    if (SS != 'Dev1' && SS != 'FLCN' && SS != 'localhosst') {
        FadeOutDone = 1;
        return false;
    }
    fadeInProper();
    FadeOutDone = 1;
    return false;
}

function fadeInProper() {
    if (FadeInDone == 1) {
        return false;
    }
    $('#UCHeader').empty().html('<div id="ccc_button" style="cursor: pointer; left: 450px; top: 155px; width: 240px; height: 60px; z-index: 100; position: absolute;" onclick="openCCC();"></div>'
                              + '<div style="cursor: pointer; left: 810px; top: 209px; width: 85px; height: 15px; z-index: 100; position: absolute;" onclick="ContactSetup();"></div>');
    FadeInDone = 1;
    return false;
}

function openCCC() {
    window.open("http://www.customcouponcreator.com/?ref=" + Filters.Referrer);
    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;
    if (advertisementid.length > 0 && advertisementid.indexOf(',') > 0) {
        logurl = "Services/Coupons.svc/LogMultiple?advertisementid=" + AjaxString(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);
    }
    else {
        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);
    }

    // Make The Call
    $.ajax({ type: "GET", url: logurl, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { LogResults(msg.d); } });

    // And We're Out
    return false;
}
function LogResults(results) {
    return false;
}
function LogPrint() {
    for (var i = 0; i < PrintPreviewList.length; i++) {
        Log(LogTypes.Print, "#UCPrintButton", PrintPreviewList[i], "Print", "Print");
    }
    PrintPreviewList = [];
    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 = 20;
        return true;
    }

    // Check Cookie
    if (checkZipCode($.cookie("Location_Zip")) == true) {
        Filters.Zip = $.cookie("Location_Zip");
        Filters.Radius = 20;
        $("#UCSearchZipcode").val($.cookie("Location_Zip"));
        $("#UCSearchSelectRadius").val(Filters.Radius);
        return true;
    }

    //  Otherwise Prompt
    else {
        $.cookie("Location_Zip", 33950, CookieOptions);
        Filters.Zip = $.cookie("Location_Zip");
        Filters.Radius = 20;
        $("#UCSearchZipcode").val($.cookie("Location_Zip"));
        $("#UCSearchSelectRadius").val(Filters.Radius);
        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() {
    $("#UCPrompt").dialog("destroy");
    $('#UCPromptInputZipcode').unbind('keyup');
    ValidateLocale($("#UCPromptInputZipcode").val());
    return false;
}
function PromptComplete() {
    Filters.Zip = SearchZipCode;
    Filters.Radius = 20;
    // $("#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 (geocoder === undefined) {
        geocoder = new GClientGeocoder();
        //alert("Creating geocoder in checkLL");
    }
    if (GoogleAddressCheckInProgress != 1) {
        GoogleAddressCheckInProgress = 1;
        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;
            }
        }

        // Check And Save The Zip Code
        //checkZipCode(SearchZipCode);
        $.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") {
            if (QSDone === 0) {
                Filters.AdvertisementID = parseInt(query[k]);
                QSDone = 1;
            }
        }
        if (k.toString().toLowerCase() == "term") {
            if (QSDone === 0) {
                Filters.Term = query[k].toString();
                QSDone = 1;
            }
        }
        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(); }
        if (k.toString().toLowerCase() == "ref") { Filters.Referrer = 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");

            // Deal With The Carousel
            FetchCarouselCoupons();
        }
    });

    // 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 Gets Changed w/ A Carriage Return
    $('#UCSearchTerm').keyup(function(e) {
        if (e.keyCode == 13) {
            if (SearchInProgress != 1) {
                SearchInProgress = 1;
                Filters.PageNumber = 1;
                Filters.Term = $('#UCSearchTerm').val();
                $('#UCSearchTerm').blur();
                Search();
                Log(LogTypes.Search, "#UCSearchTerm", "", "Search: Term", "Search: Term");
            }
        }
    });
    
    // 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() {

    GenerateListView(SearchResults);

    $('.ThumbClip').click(function() {
        var SearchIndex = $(this).attr('searchindex');
        CartAdd(SearchResults[SearchIndex].AdvertisementID, SearchResults[SearchIndex].AccountName, SearchResults[SearchIndex].Offer, SearchResults[SearchIndex].EndDate, 'Thumb', 'Thumb: Clip');
    });
    $('.ThumbPrint').click(function() {
        var SearchIndex = $(this).attr('searchindex');
        PrintPreview(SearchResults[SearchIndex].AdvertisementID, SearchResults[SearchIndex].EndDate, 'Thumb','Thumb: PrintPreview');
    });

    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) + "&advertisementid=" + Filters.AdvertisementID;
    ViewTransitionStart();
    $.ajax({ type: "GET", url: searchurl, cache: false, 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();

    // Plug The Following For Navigation Reasons
    if (Filters.AdvertisementID > 0) {
        $("#UCSearchZipcode").val(SearchResults[0].Zipcode);
        $("#UCSearchSelectRadius").val(20);
        Filters.ViewType = 'list';
        Filters.AdvertisementID = 0;
        ZoomZoom("0", "External Link", "External Link");
    }
    if (Filters.Term.length > 0) {
        Filters.Term = "";
    }
    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");

    // Branch For RedPlum And SmartSource
    if (categoryid == 'RedPlum' || categoryid == 'SmartSource') {
        var str;
        if (categoryid == 'RedPlum') {
            str = RedPlum();
        }
        if (categoryid == 'SmartSource') {
            str = SmartSource();
        }
        $('#BodyOther').empty().html(str);
        UpdateContentBlock($('#BodyOther').html());
        return false;
    }

    // The Normal Category Change
    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 PAGINATION *******/
function pageit(ui) {
    Filters.PageNumber = ui + 1;
    if (FreshPagination != 1) {
        Search();
        Log(LogTypes.Search, "Pagination", "", "Search: Pagination", "Search: Pagination");
    }
    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: " + commify(numberitems));
    $('#UCSearchInfoBottom').html("Coupons Selected: " + commify(numberitems));
}
/******** END PAGINATION *******/
function LocationLauncherSetup() {
    $('#DivUCLocationLauncher').removeClass("Hidden");
    $("#UCLocationButton").click(function() { PromptSetup(); });
    $("#UCSubscribeButton").click(function() { SubscriptionStartup(); });
}

/******** START CART *******/
function CartSetup() {
    $('#DivUCCart').removeClass("Hidden");
}
function CartAdd(advertisementid, accountname, offer, enddate, LogWhere, LogDesc) {

    // Log It
    Log(LogTypes.Clip, LogWhere, advertisementid, LogDesc, LogDesc);

    Cart.push({
        AdvertisementID: advertisementid,
        AccountName: accountname,
        Offer: offer,
        EndDate: FormatDate(enddate)
    });
    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'));
    });
    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();
        return false;
    });
    $("#UCPrintButton").click(function() {
        LogPrint();
        Print();
        return false;
    });
    $("#UCPrintTopRight").click(function() {
        $("#UCPrint").dialog("close");
        return false;
    });

    $("#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]);
    }
    return false;
}
function PrintPreview(AdID, EndDate, LogWhere, LogDesc) {
    PrintPreviewList = [];
    if ($('#Print').hasTemplate() == 0) {
        $('#Print').setTemplateElement("PrintTemplate");
    }
    if (AdID != null) {
        $('#Print').processTemplate([{ AdvertisementID: AdID, EndDate: FormatDate(EndDate)}]);
        TrackEvent('Coupons', 'Print', AdID);
        PrintPreviewList.push(AdID);
        Log(LogTypes.PrintPreview, LogWhere, AdID, LogDesc, LogDesc);
    }
    else {
        $('#Print').processTemplate(Cart);
        for (var i = 0; i < Cart.length; i++) {
            TrackEvent('Coupons', 'Print', Cart[i].AdvertisementID);
            PrintPreviewList.push(Cart[i].AdvertisementID);
            Log(LogTypes.PrintPreview, LogWhere, Cart[i].AdvertisementID, LogDesc, LogDesc);
        }  
    }
    $('#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>" + $(".SiteName").text() + "</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>" + $(".SiteName").text() + "</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();
    $('#UCContactLeft').html($(".ContactUs").html());
}
/******** 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,0";
    }

    // Track 'Em
    Log(LogTypes.Impression, 'Impression Tracker', coupons, "Coupon Impression", "Coupon Impression");
    Log(LogTypes.BannerImpression, 'Impression Tracker', banners, "Banner Impression", "Banner Impression");

    // And We're Out
    return false;
}

/******** END TRACKING *******/
/******** START MAP *******/
function MapSetup() {
    $('#DivUCMap').removeClass("Hidden");
    $('#UCMap').hide();
}
function Map() {
    if (GBrowserIsCompatible()) {
        if (geocoder === undefined) {
            geocoder = new GClientGeocoder();
            //alert("Creating geocoder in Map...?");
        }
        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;
            infowindows.push("<div style='float:left;padding-right:8px;width:85px;height:85px;'><img src='/Assets/Images/Coupons/Thumbnails/" + DeepDirectory(SearchResults[i].AdvertisementID) + "/" + 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 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.getUTCFullYear() != null) {
        return (myDate.getUTCMonth() + 1) + "/" + myDate.getUTCDate() + "/" + myDate.getUTCFullYear();
    }
    return false;
}
function DeepDirectory(id) {
    id = ZeroPad(id, 3);
    id = id.substring( (id.toString().length - 3) );
    return id;
}
function ZeroPad(num, count) {
    var numZeropad = num + '';
    while (numZeropad.length < count) {
        numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}
function commify(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

// Does An Element Exist??
function exists(selector) {
    if ($(selector).length > 0) {
        return true;
    }
    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(); }
        });
    }
});


// Set CouponCall Hash Map
var CatMap = [];
CatMap['Auto'] = 1;
CatMap['General'] = 2;
CatMap['Beauty Health Personal Care'] = 3;
CatMap['Home Garden'] = 4;
CatMap['Dining'] = 6;
CatMap['Grocery'] = 7;
CatMap['Activities'] = 8;
CatMap['Shopping'] = 9;
CatMap['Travel Tourism'] = 10;

// Set Navigation Map
var NavMap = [];
NavMap['Auto'] = 1;
NavMap['General'] = 3;
NavMap['Beauty Health Personal Care'] = 5;
NavMap['Home Garden'] = 6;
NavMap['Dining'] = 2;
NavMap['Grocery'] = 4;
NavMap['Activities'] = 8;
NavMap['Shopping'] = 7;
NavMap['Travel Tourism'] = 9;

// Checks To See If This Is A Content Call
function checkContentCall() {
    var url = location.href;
    var re1 = '(#!)'; // Any Single Character 1
    var re2 = '(\\/)'; // Any Single Character 2
    var re3 = '(Content)'; // Word 1
    var re4 = '(\\/)'; // Any Single Character 3
    var p = new RegExp(re1 + re2 + re3 + re4, ["i"]);
    var m = p.exec(url);
    if (m !== null) {
        return true;
    }
    return false;
}

// Serves Up A Piece Of Static Content
function makeContentCall() {
    var url = location.href;
    var re1 = '(#!)'; // Any Single Character 1
    var re2 = '(\\/)'; // Any Single Character 2
    var re3 = '(Content)'; // Word 1
    var re4 = '(\\/)'; // Any Single Character 3
    var p = new RegExp(re1 + re2 + re3 + re4, ["i"]);
    var m = p.exec(url);
    var chunks = url.split("#!/Content/");
    var contentElement = chunks.pop();
    if (contentElement == 'Partners') {
        GetContent(38);
        return false;
    }
    if (contentElement == 'Privacy') {
        GetContent(39);
        return false;
    }
    if (contentElement == 'Terms') {
        GetContent(40);
        return false;
    }
    return false;
}

// Sample URL
// http://www.dev1couponnetwork.com/#!/Coupons/Punta%20Gorda/FL/33950/Dining

// Checks To See If This Is A Coupon Call
function checkCouponCall() {
    var url = location.href;
    var re1 = '(#!)';
    var re2 = '(\\/)';
    var re3 = '(Coupons)';
    var re4 = '(\\/)';
    var p = new RegExp(re1 + re2 + re3 +re4, ["i"]);
    var m = p.exec(url);
    if (m !== null) {
        return true;
    }
    Filters.PageSize = 10;
    return false;
}

// Fakes Out Our Inputs
function makeCouponCall() {

    // Parse Out Our Bits
    var url = location.href;
    var chunks = url.split("/");

    // Set Our Category
    var Category = chunks.pop();
    Filters.CategoryID = CatMap[Category];
    if (NavMap[Category] > 0) {
        SelectSubNav(NavMap[Category]);
    } else {
        SelectSubNav(0);
    }

    // Set Our Zip Code
    Filters.Zip = chunks.pop();
    $("#UCSearchZipcode").val(Filters.Zip);

    // Plug Additional Settings
    Filters.Radius = 5;
    $("#UCSearchSelectRadius").val(Filters.Radius);
    Filters.PageSize = 100;

    // And We're Out
    return false;
}

// 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 HideObject(Element) {
    if (Element.hasClass("Hidden") === false) {
        Element.addClass("Hidden");
    }
    if (Element.attr("id") == "CouponBody") {
        Element.css({ display: "none" });
    }
    return false;
}

function HideAllNonCoupons() {
    HideObject($('#CenterContentBlock'));
    HideObject($('#BodyOther'));
    return false;
}

function UpdateContentBlock(NewContent) {

    HideObject($('#CouponBody'));

    $('#CenterContentBlock').empty().html(NewContent);
    if ($('#CenterContentBlock').hasClass("Hidden") === true) {
        $('#CenterContentBlock').removeClass("Hidden");
    }
    // ViewTransitionEnd();
}

function DisplayContent(What) {
    var String = undef;
    if (What == "RedPlum") {
        String = RedPlum();
    }
    else if (What == "SmartSource") {
        String = SmartSource();
    }
    if (String != undef) {
        $('#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;
}

// Display Mostly-Flat Pages From The DB
function ShowContent(data) {
    $('#BodyOther').empty().html(data.Content);
    UpdateContentBlock($('#BodyOther').html());
    $("#DivLoading").fadeOut("fast");
    return false;
}

// Retrieve Mostly-Flat Pages From The DB
function GetContent(id) {
    $("#DivLoading").fadeIn("fast", function() {
        HideAllNonCoupons();
        $.getJSON("Services/Coupons.svc/Content?contentid=" + id, function(data) {
            ShowContent(data.d);
        });
    });
    return false;
}

// Screen Width/Height, Scroll Coordinates
window.viewport = {

    height: function() {
        return $(window).height();
    },

    width: function() {
        return $(window).width();
    },

    scrollTop: function() {
        return $(window).scrollTop();
    },

    scrollLeft: function() {
        return $(window).scrollLeft();
    }
};

function truncate(text, length, ellipsis) {

    // Set length and ellipsis to defaults if not defined
    if (typeof length == 'undefined') var length = 100;
    if (typeof ellipsis == 'undefined') var ellipsis = '...';

    // Return if the text is already lower than the cutoff
    if (text.length < length) return text;

    // Otherwise, check if the last character is a space.
    // If not, keep counting down from the last character
    // until we find a character that is a space
    for (var i = length - 1; text.charAt(i) != ' '; i--) {
        length--;
    }

    // The for() loop ends when it finds a space, and the length var
    // has been updated so it doesn't cut in the middle of a word.
    return text.substr(0, length) + ellipsis;
}



function GenerateListView(SearchResults) {

    // Scope
    var LV = '<table><tbody>';

    // Start Looping On Our Coupons
    var len = SearchResults.length;
    for (var i = 0; i < len; i++) {

        // Set Coupon
        var coupon = SearchResults[i];

        // Set Values
        var PubID = coupon.PublisherID;
        var AdID = coupon.AdvertisementID;
        var Offer = coupon.Offer;
        var PCID = coupon.ParentCategoryID;
        var CID = coupon.CategoryID;
        var AccountName = coupon.AccountName;
        var City = coupon.City;
        var State = coupon.State;
        var ShowWebsite = coupon.ShowWebsite;
        var ShowAddress = coupon.ShowAddress;

        // Is A Feed Publisher?
        var FeedPub = 0;
        if (PubID == 15 || PubID == 16 || PubID == 17 || PubID == 20 || PubID == 25) {
            FeedPub = 1;
        }

        // Start The Row, Set Left/Right Classes
        if (i % 2 === 0) {
            LV += '<tr><td class="ThumbTdLeft"><div class="ThumbBG">';
        } else {
            LV += '<td class="ThumbTdRight"><div class="ThumbBG">';
        }

        // Set Image Based On Pub
        if (PubID == 15 || PubID == 16 || PubID == 17) {
            LV += '<div class="CatImage"><img width="65" height="65" src="' + CategoryIcon(PCID, CID) + '"></img></div>';
        } else if (PubID == 20) {
            LV += '<div class="MMImage"><img src="Assets/Images/Coupons/Thumbnails/' + DeepDirectory(AdID) + '/' + AdID + '.jpg"></img></div>';
        } else if (PubID == 25) {
            LV += '<div class="FMSImage"><img src="App_Themes/Common/Images/fms.png"></img></div>';
        } else {
            LV += '<div class="ThumbImage" searchindex="' + i + '"><img src="Assets/Images/Coupons/Thumbnails/' + DeepDirectory(AdID) + '/' + AdID + '.jpg" style="border: solid 1 black;" ></img></div>';
        }

        // Image Details
        LV += '<div id="ThumbDetails">';
        if (FeedPub == 1) {
            LV += '<p class="offer" onclick="SendToVendor(' + i + ', \'Thumb\', \'Thumb: SendToVendor Offer\');">' + truncate(Offer, 70) + '</p>';
        } else {
            LV += '<p class="offer ThumbDetailsOffer" searchindex="' + i + '">' + truncate(Offer, 70) + '</p>';
        }

        // Account Name
        LV += '<p class="company_info">' + AccountName + '</p>';

        // Address
        if (ShowAddress === true) {
            LV += '<p class="city">' + City + ', ' + State + '</p>';
        }

        // Wrap Up Thumb Details
        LV += '</div>';

        // Start Thumb Options
        LV += '<div id="ThumbOptions"><p>';

        // Feed Thumb Options
        if (FeedPub === 1) {
            LV += '<a class="ThumbPartnerPrint" onclick="SendToVendor(' + i + ', \'Thumb\', \'Thumb: SendToVendor Print\');">&nbsp;Print&nbsp;</a>';
            if (ShowAddress === true) {
                LV += '<a class="ThumbMap" searchindex="' + i + '">&nbsp;Map&nbsp;</a>';
            }
        }

        // YCN Thumb Options
        else {
            LV += '<a class="ThumbPrint" searchindex="' + i + '">&nbsp;Print&nbsp;';
            LV += '<a class="ThumbClip" searchindex="' + i + '">&nbsp;Clip&nbsp;</a>';
            if (ShowAddress === true) {
                LV += '<a class="ThumbMap" searchindex="' + i + '">&nbsp;Map&nbsp;</a>';
            }
            LV += '<a class="ThumbPhone" searchindex="' + i + '">&nbsp;Text&nbsp;</a>';
            LV += '<a class="ThumbEmail" searchindex="' + i + '">&nbsp;Email&nbsp;</a>';
        }

        // End Thumb Options
        LV += '</p></div>';

        // More Details
        if (FeedPub === 1) {
            LV += '<div class="ThumbPartnerDetails" onclick="SendToVendor(' + i + ', \'Thumb\', \'Thumb: SendToVendor Zoom\');"></div>';
        } else {
            LV += '<div class="ThumbMoreDetails" searchindex="' + i + '"></div>';
        }

        // Finish Up The Coupon
        LV += '</div></td>';
        if (i % 2 === 0) { } else { LV += '</tr>'; }
    }

    if (length === 0) {
        LV += '<tr><td align="center"><span class="Color3" style="text-align:center; font-family: arial, helvetica; font-size: 24px; font-weight: bold; font-style: italic;">';
        LV += '<br />No Matching Coupons Found!<br /><br /></span>';
        LV += '<span class="Color3" style="text-align:center; font-family: arial, helvetica; font-size: 13px; font-weight: bold; ">';
        LV += 'Please try changing your search criteria.<br /><br /><br /></span></td></tr>';
    }

    // Finish It
    $('#UCList').empty().html(LV);

    // And Out
    return false;
}

function SendToVendor(SearchIndex, LogWhere, LogDesc) {

    // Grab Our Coupon Details
    var Results = SetResults(SearchIndex);
    var AdID = Results.AdvertisementID;
    var RemoteURL = Results.RemoteURL;

    // Track It
    Log(LogTypes.SendToVendor, LogWhere, AdID, LogDesc, LogDesc);
    TrackEvent('Coupons', LogDesc, AdID);

    // And Send Them
    window.open(RemoteURL);

    // And We're Out
    return false;
}

function SendToBusiness(SearchIndex, LogWhere, LogDesc) {

    // Grab Our Coupon Details
    var Results = SetResults(SearchIndex);
    var AdID = Results.AdvertisementID;
    var WebsiteURL = Results.WebsiteURL;

    // Track It
    Log(LogTypes.SendToBusiness, LogWhere, AdID, LogDesc, LogDesc);
    TrackEvent('Coupons', LogDesc, AdID);

    // And Send Them
    window.open(WebsiteURL);

    // And We're Out
    return false;
}

function BannerClick(AdID, WebsiteURL, LogWhere, LogDesc) {

    // Track It
    Log(LogTypes.BannerClick, LogWhere, AdID, LogDesc, LogDesc);
    TrackEvent('Banners', LogDesc, AdID);

    // Bail If NA
    if (WebsiteURL == "NA") {
        return false;
    }

    // And Send Them
    window.open(WebsiteURL);

    // And We're Out
    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 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('');
//    $('#UCPhonePromptCarrier').find('.Carriers').val();
    $('#UCPhonePromptCarrier').find('option:first').attr('selected', 'selected').parent('select');
    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 PhoneSubmit() {
    var Phone = stripNonNumerics($("#UCPhonePromptInputNumber").val());
    var CID = $('#UCPhonePromptCarrier').find('.Carriers').val();
    var SearchIndex = $('#UCZoomData').attr("searchindex");
    var Results = SetResults(SearchIndex);
    var AdID = Results.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 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 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 + "&domain=" + AjaxString(document.domain);
    $.ajax({ type: "GET", url: Url, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { EmailSuccess(); } });
    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 (filter.test(email));
}

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 Results = SetResults(SearchIndex);
    var AdID = Results.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;
}

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')); });

    // Set Up The Various Action Start Events
    $('.ThumbDetailsOffer').click(function() { ZoomZoom($(this).attr('SearchIndex'), "Thumb", "Thumb: Zoom Offer"); });
    $('.ThumbMoreDetails').click(function() { ZoomZoom($(this).attr('SearchIndex'), "Thumb", "Thumb: Zoom Details"); });
    $('.ThumbImage').click(function() { ZoomZoom($(this).attr('SearchIndex'), "Thumb", "Thumb: Zoom Image"); });
    $('.ThumbMap').click(function() { ZoomMap($(this).attr('SearchIndex'), "Thumb", "Thumb: Map"); });
    $('.ThumbEmail').click(function() { ZoomEmail($(this).attr('SearchIndex'), "Thumb", "Thumb: Email"); });
    $('.ThumbPhone').click(function() { ZoomPhone($(this).attr('SearchIndex'), "Thumb", "Thumb: Phone"); });

    // 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");
        var Results = SetResults(SearchIndex);
        PrintPreview(Results.AdvertisementID, Results.EndDate, 'Zoom', 'Zoom: PrintPreview');
        return false;
    });
    $('#UCZoomOptionCart').click(function() {
        var SearchIndex = $('#UCZoomData').attr("SearchIndex");
        var Results = SetResults(SearchIndex);
        CartAdd(Results.AdvertisementID, Results.AccountName, Results.Offer, Results.EndDate, 'Zoom', 'Zoom: Clip');
        return false;
    });
    $('#UCZoomCloseButton').click(function() {
        $('#UCZoom').dialog("close");
    });

    // Events For The Zoom Pages
    $('#UCZoomOptionCoupon').click(function() {
        CurrentNavID = 0;
        var SearchIndex = $('#UCZoomData').attr("SearchIndex");
        var Results = SetResults(SearchIndex);
        Zoom(SearchIndex, "ZoomCoupon");
        Log(LogTypes.Zoom, 'Zoom', Results.AdvertisementID, "Zoom: Zoom", "Zoom: Zoom");
        return false;
    });
    $('#UCZoomOptionMap').click(function() { ZoomMap($('#UCZoomData').attr("SearchIndex"), "Zoom", "Zoom: Map"); });
    $('#UCZoomOptionPhone').click(function() { ZoomPhone($('#UCZoomData').attr("SearchIndex"), "Zoom", "Zoom: Phone"); });
    $('#UCZoomOptionEmail').click(function() { ZoomEmail($('#UCZoomData').attr("SearchIndex"), "Zoom", "Zoom: Email"); });

    // Flag Setup As Done
    Zoomed = 1;
}

function Zoom(SearchIndex, template) {

    // Set Our Coupon Object
    var Results = SetResults(SearchIndex);

    // 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 Template
    if (template === null) {
        template = "ZoomCoupon";
        CurrentNavID = 0;
    }

    // Set Up Our Body
    SetZoomBody(template);

    // The Coupon Zoom Page
    if (template == "ZoomCoupon") {
        $('#UCZoomPic').html("<img src='/Assets/Images/Coupons/" + DeepDirectory(Results.AdvertisementID) + "/" + Results.AdvertisementID + ".jpg' />");
    }

    // The Map Page
    if (template == "ZoomMap") {
        MapZoom($('#UCZoomData').attr("SearchIndex"));
    }

    // These Items Are Shown On Every Zoom Page
    $('#UCZoomOffer').html(Results.Offer);
    var exp = FormatDate(Results.EndDate);
    if (exp !== null) {
        $('#UCZoomExpiration').html("Expires: " + exp);
    }

    // Sort Our Web Address And Account Name
    if (Results.ShowWebsite === true) {
        $('#UCZoomAccount').html("<a onclick=\"SendToBusiness(" + SearchIndex + ", 'Zoom', 'Zoom: SendToBusiness');\">" + Results.AccountName + "</a>");
    }
    else {
        $('#UCZoomAccount').html(Results.AccountName);
    }

    // Turn Off The Map HREF If We Don't Have An Address To Map
    if (Results.ShowAddress === false) {
        ZoomNavOnOff(3, 2);
        RemoveHREF($('#UCZoomOptionMapOff'));
    }
    else {
        ZoomNavOnOff(2, 3);
    }

    // Turn Off Email, Phone, Coupon Cart For Valpak
    if (Results.PublisherID == 15 ||
        Results.PublisherID == 16 ||
        Results.PublisherID == 17 ||
        Results.PublisherID == 20 ||
        Results.PublisherID == 25) {
        ZoomNavOnOff(1, 0);
        RemoveHREF($('#UCZoomOptionCouponOff'));
        ZoomNavOnOff(6, 5);
        RemoveHREF($('#UCZoomOptionCartOff'));
        ZoomNavOnOff(8, 7);
        RemoveHREF($('#UCZoomOptionPhoneOff'));
        ZoomNavOnOff(10, 9);
        RemoveHREF($('#UCZoomOptionEmailOff'));

        // Now Make Print A Send To Vendor
        $('#UCZoomOptionPrint').unbind('click');
        $('#UCZoomOptionPrint').click(function() {
            var SearchIndex = $('#UCZoomData').attr("SearchIndex");
            SendToVendor(SearchIndex, 'Zoom', 'Zoom: SendToVendor Print');
            return false;
        });
    }
    else {
        ZoomNavOnOff(0, 1);
        ZoomNavOnOff(5, 6);
        ZoomNavOnOff(7, 8);
        ZoomNavOnOff(9, 10);
    }

    // Set Our Tabs
    SetZoomTabs();

    return false;
}

// Email Access Into Zoom
function ZoomEmail(SearchIndex, Where, LogDesc) {
    var Results = SetResults(SearchIndex);
    CurrentNavID = 9;
    Zoom(SearchIndex, "ZoomEmail");
    $('#UCEmailPromptSubmit').click(EmailSubmit);
    $('#UCEmailPromptInYourName').focus();
    Log(LogTypes.Email, Where, Results.AdvertisementID, LogDesc, LogDesc);
    TrackEvent('Coupons', LogDesc, Results.AdvertisementID);
    return false;
}

// Phone Access Into Zoom
function ZoomPhone(SearchIndex, Where, LogDesc) {
    var Results = SetResults(SearchIndex);
    CurrentNavID = 7;
    Zoom(SearchIndex, "ZoomPhone");
    $('#UCPhonePromptSubmit').click(PhoneSubmit);
    $('#UCPhonePromptInputNumber').focus();
    Log(LogTypes.Phone, Where, Results.AdvertisementID, LogDesc, LogDesc);
    TrackEvent('Coupons', LogDesc, Results.AdvertisementID);
    return false;
}

// Map Access Into Zoom
function ZoomMap(SearchIndex, Where, LogDesc) {
    var Results = SetResults(SearchIndex);
    CurrentNavID = 2;
    Zoom(SearchIndex, "ZoomMap");
    Log(LogTypes.Map, Where, Results.AdvertisementID, LogDesc, LogDesc);
    TrackEvent('Coupons', LogDesc, Results.AdvertisementID);
    return false;
}

// Thumbnail Access Into Zoom Window
function ZoomZoom(SearchIndex, Where, LogDesc) {
    var Results = SetResults(SearchIndex);
    CurrentNavID = 0;
    Zoom(SearchIndex, "ZoomCoupon");

    var NewIndex = SearchIndex;
    NewIndex = NewIndex.replace(/[^0-9]/g, '');
    if (NewIndex == SearchIndex) {
        Log(LogTypes.Zoom, Where, Results.AdvertisementID, LogDesc, LogDesc); 
    } else {
        Log(LogTypes.CarouselZoom, Where, Results.AdvertisementID, LogDesc, LogDesc);
    }
    TrackEvent('Coupons', LogDesc, Results.AdvertisementID);
    return false;
}

// Determines Which Hash Object To Use
function SetResults(Index) {
    var NewIndex = Index;
    NewIndex = NewIndex + "";
    NewIndex = NewIndex.replace(/[^0-9]/g, '');
    if (NewIndex == Index) {
        return SearchResults[Index];
    } else {
        return CarouselResults[NewIndex];
    }
}

function SetZoomTabs() {
    $("#ZoomNav > li:eq(" + PrevNavID + ")").attr("id", "");
    $("#ZoomNav > li:eq(" + CurrentNavID + ")").attr("id", "current");
    PrevNavID = CurrentNavID;
    return false;
}

function MapZoom(SearchIndex) {

    // Set Our Coupon Object
    var Results = SetResults(SearchIndex);

    // Map It If We Can
    if (GBrowserIsCompatible()) {
        var zoomaddress = Results.Address1 + " " + Results.Address2 + ", " + Results.City + ", " + Results.State + ", " + Results.Zipcode;
        var zoominfowindow = "<span style='font-weight:bold; font-size:12px;color:#0a8db0;'>" + Results.AccountName + "</span><br>" + Results.Address1 + " " + Results.Address2 + "<br>" + Results.City + ", " + Results.State + ", " + Results.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;
}

function ZoomNavOnOff(on, off) {
    $("#ZoomNav > li:eq(" + off +")").hide();
    $("#ZoomNav > li:eq(" + on + ")").show();
    return false;
}

function RemoveHREF(element) {
    element.removeAttr("href");
    element.unbind('click');
    element.css({ cursor: "default", color: "White" });
    return false;
}

function SetZoomBody(template) {

    // Coupon
    if (template == "ZoomCoupon") {
        $('#UCZoomContentBody').html('<div id="UCZoomContentCoupon"><div id="UCZoomPic"></div><div id="UCZoomContentBottom"><div id="UCZoomOffer"></div><div id="UCZoomAccount"></div><div id="UCZoomExpiration"></div></div></div>');
    }

    // Map
    else if (template == "ZoomMap") {
        $('#UCZoomContentBody').html('<div id="UCZoomContentMap"><div id="UCZoomMap"></div><div id="UCZoomContentBottom"><div id="UCZoomOffer"></div><div id="UCZoomAccount"></div><div id="UCZoomExpiration"></div></div></div>');
    }

    // Phone
    else if (template == "ZoomPhone") {
        $('#UCZoomContentBody').html('<div id="UCZoomContentPhone"><div id="UCPhonePromptIntro"><span><h5 style="font-size: 125%">To send this coupon to your phone, please enter your mobile number with area code, select your mobile carrier and click Submit below.</h5></span></div><div id="UCPhonePromptNumber">Mobile Number (Ex: 123-456-7890):<input id="UCPhonePromptInputNumber" /></div><div id="UCPhonePromptCarrier">' + $('#MobileCarriersIn').html() + '</div><div id="UCPhonePromptSubmit"><span class="Color6" style="font-family: arial, helvetica; font-size: 14px;"><b><i>Submit >></i></b> </span></div><div id="UCZoomContentBottom"><div id="UCZoomOffer"></div><div id="UCZoomAccount"></div><div id="UCZoomExpiration"></div></div></div>');
    }

    // Email
    else if (template == "ZoomEmail") {
        $('#UCZoomContentBody').html('<div id="UCZoomContentEmail"><div id="UCEmailPromptIntro"><span><h5 style="font-size: 125%">Please fill in the fields below and click Submit to email this coupon to a friend.</h5></span></div><div id="UCEmailPromptYourName">Your Name:<input id="UCEmailPromptInYourName" /></div><div id="UCEmailPromptYourEmail">Your Email: <input id="UCEmailPromptInYourEmail" /></div><div id="UCEmailPromptTheirName">Their Name:<input id="UCEmailPromptInTheirName" /></div><div id="UCEmailPromptTheirEmail">Their Email:<input id="UCEmailPromptInTheirEmail" /></div><div id="UCEmailPromptMessage">Your Message:<textarea id="UCEmailPromptInMessage" /></div><div id="UCEmailPromptSubmit"><span class="Color6" style="font-family: arial, helvetica; font-size: 14px;"><b><i>Submit >></i></b> </span></div><div id="UCZoomContentBottom"><div id="UCZoomOffer"></div><div id="UCZoomAccount"></div><div id="UCZoomExpiration"></div></div></div>');
    }

    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) {
        Filters.PageNumber = 1;
        CategoryUpdate(catid, parentid);
        Log(LogTypes.Search, ".MenuItem", "", "Search: Category", "Search: Category");
        return false;
    }

    if (vendorid > 0 && catid === undefined) {
        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());
        }
    }

    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;
}


// Set Up The Category/Icon Hash
var CatIcons = [];
CatIcons[1] = "1.png";
CatIcons[2] = "2.png";
CatIcons[3] = "3.png";
CatIcons[4] = "4.png";
CatIcons[6] = "6.png";
CatIcons[7] = "7.png";
CatIcons[8] = "8.png";
CatIcons[9] = "9.png";
CatIcons[10] = "10.png";
CatIcons[11] = "11.png";
CatIcons[12] = "12.png";
CatIcons[13] = "13.png";
CatIcons[14] = "14.png";
CatIcons[15] = "15.png";
CatIcons[16] = "16.png";
CatIcons[17] = "17.png";
CatIcons[17] = "18.png";
CatIcons[20] = "20.png";
CatIcons[21] = "21.png";
CatIcons[22] = "22.png";
CatIcons[23] = "23.png";
CatIcons[24] = "24.png";
CatIcons[25] = "25.png";
CatIcons[27] = "27.png";
CatIcons[29] = "29.png";
CatIcons[30] = "30.png";
CatIcons[31] = "31.png";
CatIcons[32] = "32.png";
CatIcons[33] = "33.png";
CatIcons[34] = "34.png";
CatIcons[35] = "35.png";
CatIcons[36] = "36.png";
CatIcons[37] = "37.png";
CatIcons[38] = "38.png";
CatIcons[45] = "45.png";
CatIcons[46] = "46.png";
CatIcons[47] = "47.png";
CatIcons[48] = "49.png";
CatIcons[49] = "49.png";
CatIcons[52] = "52.png";
CatIcons[53] = "53.png";
CatIcons[54] = "54.png";
CatIcons[55] = "55.png";
CatIcons[60] = "60.png";
CatIcons[61] = "61.png";
CatIcons[62] = "62.png";
CatIcons[63] = "63.png";
CatIcons[64] = "64.png";
CatIcons[65] = "65.png";
CatIcons[66] = "66.png";
CatIcons[67] = "67.png";
CatIcons[68] = "68.png";
CatIcons[81] = "81.png";
CatIcons[82] = "82.png";
CatIcons[83] = "83.png";
CatIcons[84] = "84.png";
CatIcons[85] = "85.png";
CatIcons[86] = "86.png";
CatIcons[87] = "87.png";
CatIcons[89] = "89.png";
CatIcons[90] = "90.png";
CatIcons[91] = "91.png";
CatIcons[93] = "93.png";
CatIcons[94] = "94.png";
CatIcons[96] = "96.png";
CatIcons[97] = "97.png";
CatIcons[98] = "98.png";
CatIcons[100] = "100.png";
CatIcons[101] = "101.png";
CatIcons[102] = "102.png";
CatIcons[103] = "103.png";
CatIcons[104] = "104.png";
CatIcons[105] = "105.png";
CatIcons[106] = "106.png";
CatIcons[111] = "111.png";
CatIcons[112] = "112.png";
CatIcons[113] = "113.png";
CatIcons[120] = "120.png";
CatIcons[121] = "121.png";
CatIcons[122] = "122.png";
CatIcons[123] = "123.png";
CatIcons[124] = "124.png";
CatIcons[125] = "125.png";
CatIcons[126] = "126.png";
CatIcons[127] = "127.png";
CatIcons[128] = "128.png";
CatIcons[139] = "139.png";
CatIcons[140] = "140.png";
CatIcons[141] = "141.png";
CatIcons[142] = "142.png";

// Figures Out Which Icon To Use And Hands Back The Full Path
function CategoryIcon(Cat, SubCat) {

    // Do We Have An Icon For The SubCat?
    if (SubCat > 0 && CatIcons[SubCat] != undefined) {
        return "App_Themes/Common/Images/CatImages/" + CatIcons[SubCat] ;
    }

    // Do We Have An Icon For The Parent Category?
    if (Cat > 0 && CatIcons[Cat] != undefined) {
        return "App_Themes/Common/Images/CatImages/" + CatIcons[Cat] ;
    }

    // Otherwise Use ycn.png
    return "App_Themes/Common/Images/CatImages/ycn.png" ;
}

﻿var CarouselResults;
var ImageIndex = 1;
var CarouselCouponIndex = 0;
var MaxImageIndex = 4;
var CarouselTransitionSpeed = 1000;
var CarouselCouponSwitchSpeed = 5000;
var CarouselStarted = 0;
var CarouselInterval;
var TagLines = [];
var HeaderCount = 0;

// Track Carousel Impressions
function TrackCarouselImpressions() {
    var Ads = [];
    for (var i = 0; i < CarouselResults.length; i++) {
        Ads[i] = CarouselResults[i].AdvertisementID;
    }
    var ads = Ads.join(",");
    if (ads.length === 0) {
        ads = "0,0";
    }
    Log(LogTypes.CarouselImpression, 'Impression Tracker', ads, "Carousel Impression", "Carousel Impression");
    return false;
}

// Set Our Header Text
function SetCarouselHeader() {

    // Populate Our Tag Lines As Needed
    if (TagLines.length === 0) {
        PopulateTagLines();
    }
    
    // Only Run Every 3rd Call
    HeaderCount ++ ;
    if (HeaderCount < 3) {
        return false;
    }
    HeaderCount = 0;

    // Pick A Tag Line
    var TagLine = TagLines[Math.floor(Math.random() * TagLines.length)];
    if (TagLine.length === 0) {
        TagLine = "Popular Coupons From Around The Country...";
    }

    // Set It
    $('#CarouselHeader').fadeOut("slow", function() {
        $('#CarouselHeader').html(TagLine);
        $('#CarouselHeader').fadeIn("slow");
    });

    // And Out
    return false;
}

// Swaps Out The Old Image For The New Image
function SetUpImage(IndexC, e) {
    var src = "/Assets/Images/Coupons/" + DeepDirectory(CarouselResults[IndexC].AdvertisementID) + "/" + CarouselResults[IndexC].AdvertisementID + ".jpg";
    var zoomid = "CAR-" + IndexC;
    e.attr("src", src).attr("zoomid", zoomid);
    return false;
}

// Calls ZoomZoom
function CallZoomZoom(Chunk) {
    ZoomZoom($("#" + Chunk).attr("zoomid"), "CarouselZoom", "Carousel: Zoom Details");
    return false;
}


// Hide An Image Element And Set Up The Next Image
function CarouselHide(IndexC, e) {
    e.fadeOut(CarouselTransitionSpeed, function() {
        SetUpImage(IndexC, e);
    });
    return false;
}

// Show An Image Element
function CarouselShow(e) {
    e.fadeIn(CarouselTransitionSpeed);
    return false;
}

// Handles The Image Rotation
function CarouselRotate() {

    // Fade Out & Redo The Image
    CarouselHide(CarouselCouponIndex, $('#CarImg' + ImageIndex));

    // Fade It In
    CarouselShow($('#CarImg' + ImageIndex));

    // Set Image Index
    ImageIndex += 1;
    if (ImageIndex > MaxImageIndex) {
        ImageIndex = 1;
    }

    // Set Coupon Index
    CarouselCouponIndex += 1;
    if (CarouselCouponIndex == CarouselResults.length) {
        CarouselCouponIndex = 0;
    }

    // Swap The Carousel Header
    SetCarouselHeader();

    // And Out
    return false;
}

// This Start The Carousel For The First Time...
function StartCarousel() {
    if (CarouselStarted === 0) {
        SetCarouselHeader();
        SetUpImage(0, $('#CarImg1'));
        SetUpImage(1, $('#CarImg2'));
        SetUpImage(2, $('#CarImg3'));
        SetUpImage(3, $('#CarImg4'));
        CarouselCouponIndex = 4;
        CarouselShow($('#CarouselImages'));
        $('#CarouselHeader').removeClass("Hidden");
        CarouselStarted = 1;
    }

    // Start The Interval
    CarouselInterval = setInterval(CarouselRotate, CarouselCouponSwitchSpeed);
}

// Restores The Carousel Start State
function ResetCarousel() {
    clearInterval(CarouselInterval);
    CarouselStarted = 0;
    return false;
}

// Update Carousel -- Changes The Carousel Content
function UpdateCarousel(data) {
    CarouselResults = data;    
    ResetCarousel();
    StartCarousel();
    TrackCarouselImpressions();    
    return false;
}

// Grabs Our Most Popular Coupons
function FetchCarouselCoupons() {

    // Run Everywhere Except Florida
    var SS = $(".SiteState").text();
    if (SS != 'Dev1' && SS != 'FLCN' && SS != 'localhosst') {

        if ($('#CarouselImages').css('display') == "none") {
            $('#CarouselImages').fadeOut(CarouselTransitionSpeed);
        }
        var MPurl = "Services/Coupons.svc/MostPopular?publisherid=" + $(".PublisherID").text() + "&categoryid=" + Filters.CategoryID + "&quantity=12";
        $.ajax({ type: "GET", url: MPurl, cache: false, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", complete: function() { }, success: function(msg) { UpdateCarousel(msg.d); } });

    }
    return false;
}

// Populates Our Tag Lines Display
function PopulateTagLines() {

    // Generic Tag Lines
    if ($(".TagLines").text().length === 0) {
        TagLines = [
            "Popular Local Coupons From Your Favorite Merchants...",
            "Hot Deals From Your Favorite Shopping Spots...",
            "Grab A Bunch Of Local Coupons And Save A Bundle!",
            "New Deals And Fabulous Steals Being Added Daily!",
            "Deals and Steals Can Be Seen On Your Smart Phone Via MobiQpons!"
        ];
    }

    // Custom Tag Lines
    else {
        TagLines = $(".TagLines").text().split("|");
    }

    // And Out
    return false;
}

﻿// Scope Banner Specific Stuff
var BannerLeft;
var BannerRight;

// Updates The Banner Components As Needed
function UpdateBanner(placement, banner) {

    // Set Local Values
    var id = $(banner).attr('ID');
    var url = $(banner).attr('WebsiteURL');
    var display = $(banner).attr('WebsiteDisplay');

    // Check Our URL
    if (url.length === 0) {
        url = 'NA';
    }

    // Set Our Image
    var img = "Assets/Images/Banners/" + id + ".jpg";
    if ($(banner).attr('Image') !== null) {
        img = "Assets/Images/Banners/" + $(banner).attr('Image');
    }

    // Write The New Values If Needed
    if ($('#BannerAd' + placement + 'Href').attr('BannerID') != id) {
        $('#BannerAd' + placement + 'Href').attr('BannerID', id);
        $('#BannerAd' + placement + 'Href').attr('WebsiteURL', url);
        $('#BannerAd' + placement + 'Img').attr('src', img);
        $('#BannerAd' + placement + 'Img').attr('alt', display);
    }

    // Save Off Our ID
    if (placement == "Left") {
        BannerLeft = id;
    } else {
        BannerRight = id;
    }

    // And We're Done
    return false;
}

// Fetches Our Banners
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;
}

// Makes The Banners Visible
function BannerStartUp() {
    $('#BannerLeft').css('display', 'block');
    $('#BannerRight').css('display', 'block');
    $('#DivUCAdsLeft').removeClass('Hidden');
    $('#DivUCAdsRight').removeClass('Hidden');
    return false;
}

// Send It And Log It
function SendSubscription(Name, Email, ZipCode, SiteID, Categories) {
    TrackEvent('Coupons', 'Subscribe', AjaxString(Email));
    var Url = "Services/Coupons.svc/Subscribe?name=" + AjaxString(Name) + "&email=" + AjaxString(Email) + "&zipcode=" + AjaxString(ZipCode) + "&siteid=" + AjaxString(SiteID) + "&categories=" + AjaxString(Categories);
    $.ajax({ type: "GET", url: Url, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { SubscribeSuccess(); } });
    return false;
}

// Report Success
function SubscribeSuccess() {
    $.gritter.add({
        title: 'Subscription Sent!',
        text: 'Your preferences have been saved and you should start seeing emails soon.',
        image: '/App_Themes/Common/Images/Gritter/growl_logo.gif',
        sticky: false,
        time: 7500
    });

    // Close The Dialog
    $('#UCUserInteraction').dialog("close");

    // And Out
    return false;
}

// Pick Up And Check Values
function SubscriptionSubmit() {

    // Pull The Basics
    var Name = '';
    var Email = $("#UCUserInteractionSubscribeInYourEmail").val();
    var ZipCode = $("#UCUserInteractionSubscribeInYourZipcode").val();
    var ZCClean = stripNonNumerics(ZipCode);
    var SiteID = $(".SiteID").text();

    // Pull The Categories And Stringify
    var selectedItems = [];
    $("#CatDiv").find(":checked").each(function() {
        if ($(this).val() != 'ALL') {
            selectedItems.push($(this).val());
        } 
    });
    var Categories = "N/A";
    if (selectedItems.length > 0) {
        Categories = selectedItems.join("|");
    }

    // Default Name To Email
    if (Name.length === 0) {
        Name = Email;
    }

    // Handle Errors
    if (isValidEmail(Email) === false) {
        jAlert("Please provide a valid email address.", "Sign-Up To Be Notified About New Local Coupons");
    }
    else if (ZCClean.length != 5 && ZCClean.length != 9) {
        jAlert("Zip codes must be entered as 12345 or 12345-6789. Please provide a valid zip code.", "Sign-Up To Be Notified About New Local Coupons");
    }
    else {
        SendSubscription(Name, Email, ZipCode, SiteID, Categories);
    }

    // And Done!
    return false;
}

// Start Prompt
function SubscriptionStartup() {

    // Make Stuff Visible
    $('#DivUCUserInteraction').removeClass("Hidden");

    // Set Up The Dialog
    $("#UCUserInteraction").dialog({ autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "UCUserInteractionDialog",
        width: 'auto',
        height: 'auto',
        position: 'center',
        stack: 'true',
        zindex: 3900,
        overlay: { opacity: 0.5, background: "black" }
    });

    // Set The Header
    $('#UCUserInteractionContentHeader').html('Subscribe');

    // Set The Body
    $('#UCUserInteractionContentBody').html('<div id="UCUserInteractionSubscribe"><div id="UCUserInteractionSubscribeIntro"><span><h5 style="font-size: 125%">I would like to be notified of coupons and specials in my local area.</h5></span></div><div id="UCUserInteractionSubscribeYourEmail">Your Email: <input id="UCUserInteractionSubscribeInYourEmail" /></div><div id="UCUserInteractionSubscribeYourZipcode">Your Zip Code:<input id="UCUserInteractionSubscribeInYourZipcode" /></div><div id="UCUserInteractionSubscribeCat">Areas Of Interest:</div><div id="CatDiv"><div id="CatInLeft"><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="1"> &nbsp; Auto<br /><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="3"> &nbsp; Personal Care<br/><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="4"> &nbsp; Home / Garden<br /><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="6"> &nbsp; Dining<br /><br /><input id="checkboxall" type="checkbox" value="ALL"> &nbsp; ALL</div><div id="CatInRight"><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="7"> &nbsp; Grocery<br><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="8"> &nbsp; Activites<br><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="9"> &nbsp; Shopping<br><input id="UCUserInteractionSubscribeCatIn" type="checkbox" value="10"> &nbsp; Travel / Tourism<br></div></div><div id="UCUserInteractionSubscribeSubmit"><span class="Color6" style="font-family: arial, helvetica; font-size: 14px;"><b><i>Submit >></i></b> </span></div></div>');

    // Open The Dialog
    $('#UCUserInteraction').dialog("open");

    // Set Up The Submit Event
    $('#UCUserInteractionSubscribeSubmit').click(SubscriptionSubmit);
    $('#UCUserInteractionCloseButton').click(function() {
        $('#UCUserInteraction').dialog("close");
    });

    // Set Up The Check All Event
    $("#checkboxall").click(function() {
        var checked_status = this.checked;
        $("input[id=UCUserInteractionSubscribeCatIn]").each(function() {
            this.checked = checked_status;
        });
    });

    // And We're Out
    return false ;
}

/** 
 * @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 PoundBang.js
 * @depends jquery.alerts.js
 * @depends jquery.gritter.js
 * @depends Display.js
 * @depends SendOffsite.js
 * @depends SendToPhone.js
 * @depends SendToFriend.js
 * @depends Zoom.js
 * @depends Navigation.js
 * @depends Affiliates.js
 * @depends Categories.js
 * @depends Carousel.js
 * @depends BannerAds.js
 * @depends Subscribe.js
 */  

