﻿if (!window.console)
    window.console = { log: function () { } };
if (!window.GAtrackThis)
    window.GAtrackThis = function () { };

var CFAframe;
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

(function ($) {
    $(".animation-buffer").bind("webkitAnimationEnd mozAnimationEnd msAnimationEnd animationEnd", function () { $(this).toggleClass("spin", false); });
    $.unserialize = function (serializedString) {
        var str = decodeURI(serializedString);
        var pairs = str.split('&');
        var obj = {}, p, idx, val;
        for (var i = 0, n = pairs.length; i < n; i++) {
            p = pairs[i].split('=');
            idx = p[0];

            if (idx.length>1&&idx.indexOf("[]") == (idx.length - 2)) {
                // Eh um vetor                
                var ind = idx.substring(0, idx.length - 2)
                if (obj[ind] === undefined) {
                    obj[ind] = [];
                }
                obj[ind].push(p[1]);
            }
            else {
                obj[idx] = p[1];
            }
        }
        return obj;
    };
})(jQuery);




// Ipad Iphone
$(document).ready(function () {


    $(".faq-accordian").each(function () {
        $(this).find(".faq-q").prepend("<span class='block faq-status'><span class='faq-arrow'></span><span class='faq-t-view'>click to view answer</span><span class='faq-t-hide'>click to hide answer</span></span>");
        $(this).find(".faq-q").toggleClass("no-point", false);
        $(this).find(".faq-q").toggleClass("no-link", true);
        $(this).find(".faq-a").slideUp(function () {
            $(this).toggleClass("closed", false);
        });
        $(this).find(".faq-q").click(function () {
            var set = $(this).parent().parent();
            var rel = $(this).attr("rel");
            set.find(".faq-set:not(.faq-" + rel + ") .faq-a").slideUp().parent().toggleClass("active", false);

            if (!$(this).parent().hasClass("active")) {
                set.find(".faq-" + rel + " .faq-a").slideDown();
                $(this).parent().toggleClass("active", true);
            } else {
                set.find(".faq-" + rel + " .faq-a").slideUp();
                $(this).parent().toggleClass("active", false);
            }
        });


    });
    $('input[title!=""]').hint("hinted");

    //do SD test
    

   /* $(".track-this").click(function (e) {
        var rel = $(this).attr("rel");
        
        _gaq.push(['_trackEvent', rel, 'clicked']);
        window.location = $(this).attr("href");
        return false;


    });*/

});
function is_string(input) {
    return typeof (input) == 'string';
}
/*BEGIN MATTS CRAZY JS */
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
function domSafe(str) {
    //This should be done in a single expression
    str = str.replace(/([A-Z])([A-Z])/g, "$1-$2");
    return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function stripTags(str) {
    if(str&&is_string(str))
    return str.replace(/(<([^>]+)>)/ig, "");
}
function noWrapCFA(str) {
    if (!str || !is_string(str))
        return;

    return str.replace(/Chick-fil-A/ig, "<span class='no-wrap'>Chick-fil-A</span>");
}



Object.size = function (obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

CFAPage.FormatHash = function () {
    var hash = "?";
    var len = "";


    for (var q in this.params) {
        if (!isNumeric(q) && this.params[q])
            len = len + "&" + q + "=" + this.params[q];
    }

    if (len) {
        hash = hash + len.substring(1);
    } else if (this.Cid) {
        hash = hash + this.Cid;
    }
    /*
    Commands are a one time execution, they should not stay on the client string
    if (this.cmd) {
    var cmdarr = [];
    for (var i in this.cmd)
    cmdarr.push(i + "/" + this.cmd[i].join("/"));

    hash = hash + cmdarr.join(":");
    }
    */
    if (hash == "?" && !window.location.hash)
        return;
    window.location.hash = hash;
    var action = $("form").attr("action");
    if (!action || action.indexOf("javascript")!=-1)
        return;
    var indofhash = action.indexOf("#");
    if (indofhash == -1)
        action = action + "#" + hash;    
    else
        action = action.substring(0, indofhash)+"#" + hash;

    $("form").attr("action", action)
}
CFAPage.param = function (param, value) {
    CFAPage.params[param] = stripTags(value);
    CFAPage.FormatHash();
}


CFAPage.evalHash = function (hash) {
    this.params = {};
    if (hash)
        window.location.hash = hash;



    if (window.location.hash != null && window.location.hash != "") {
        if (window.location.hash.indexOf("?") != 1)
            window.location.hash = "#?" + window.location.hash.substring(1);


        this.hash = window.location.hash.substring(2);
        var cmd = this.hash.indexOf("/");
        if (cmd != -1) {

            this.cmd = {};
            //GLOBAL COMMAND
            var cmds = this.hash.substring(cmd + 1).split(":");

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

                var thisCmd = cmds[i].split("/");

                this.cmd[thisCmd[i]] = thisCmd.splice(1, 15);

            }
            this.hash = this.hash.substring(0, cmd);
        }




        if (this.hash.indexOf("=") != -1 || this.hash.indexOf("&") != -1) {
            //PARAM SET



            var hash;
            if (cmd != -1)
                hash = this.hash.substring(0, cmd);
            else
                hash = this.hash;



            var queries = hash.split("&");
            for (var key in queries) {
                var set = queries[key].split("=");
                if (set.length > 1) {
                    this.params[set[0]] = stripTags(set[1]);
                    this.params[key] = stripTags(set[1]);
                } else
                    this.params[key] = stripTags(set[0]);
            }
            this.Cid = this.params[0];
        } else {
            //cid == client ID
            this.Cid = this.hash;
            //this.params = null;
        }
    }
    this.FormatHash();
}
CFAPage.ImplyCid = function (id) {

    if (!this.Cid || this.Cid == "") {
        this.Cid = id;
        this.FormatHash();
    }
}
CFAPage.evalHash();


var ExtMath = {
    interpolate: function (p1, p2, d) {

        return (p2 - p1) * d + p1;
    }
}


var Event = {

    frameCount: 0,
    frameQueue: new Array(),
    queueStaticCount: 0,
    enterFrame: function (e) {
        Event.frameCount++;
        Effects.effectFrame(e);
        CFA.frame({ self: e, count: Event.frameCount });
        if (!Event.frameQueue.length)
            return;
        for (var i = 0, len = Event.frameQueue.length; i < len; i++)
            if (Event.frameQueue[i])
                Event.frameQueue[i].f({ self: e, id: Event.frameQueue[i].id, count: Event.frameCount, target: Event.frameQueue[i].t });


    },
    addEnterFrame: function (func, targ, customId) {

        var id;
        if (customId) {
            id = customId;
            for (var i = 0, len = Event.frameQueue.length; i < len; i++)
                if (Event.frameQueue[i].id == id)
                    return;
        } else {
            Event.queueStaticCount++;
            id = Event.queueStaticCount;
        }
        return Event.frameQueue.push({ id: id, f: func, t: targ });
    },
    removeEnterFrame: function (frameEvent) {
        var id;
        if (frameEvent.id)
            id = frameEvent.id;
        else if (frameEvent.self)
            id = frameEvent.self.id;
        else
            id = frameEvent;
        for (var i = 0, len = Event.frameQueue.length; i < len; i++)
            if (Event.frameQueue[i].id == id) {
                Event.frameQueue.splice(i, 1);
                return Event.frameQueue;
            }
    },

    timerArray: new Object(),

    wait: function (target, seconds, fn, key, onClear) {
        if (!key) {
            Event.queueStaticCount++;
            key = Event.queueStaticCount;
        }
        Event.clearTimer(key);
        var t = window.setTimeout("Event.fireTimeout(Event.timerArray['" + key + "'])", Math.round(seconds * 1000));

        


        Event.timerArray[key] = { target: target, t: t, oc: onClear, fn: fn, active: true };
        return t;
    },
    fireTimeout: function (obj) {
        obj.active = false;
        obj.fn({ target: obj.target });
    },
    clearTimer: function (key) {
        if (!Event.timerArray[key] || !Event.timerArray[key].t)
            return false;
        Event.timerArray[key].active = false;
        clearTimeout(Event.timerArray[key].t);
        if (Event.timerArray[key].oc)
            Event.timerArray[key].oc({ target: Event.timerArray[key].target });
        return true;
    }

};
var QUALITY={
        HIGH: 5,
        MED: 4,
        LOW: 3
        };
var FEATURE= {
        HIGH: 5,
        MED: 4,
        LOW: 3
    };
    var Effects = {
        defaultFrameRate: function () {
            switch (this.quality) {
                case QUALITY.HIGH:
                    return Math.round(1000 / 30);
                case QUALITY.MED:
                    return Math.round(1000 / 60);
                case QUALITY.LOW:
                    return Math.round(1000 / 10);
            }
        },

        resetFrameRate: function () {
            this.frameRate = Effects.defaultFrameRate();
        },

        quality: QUALITY.HIGH,
        feature: FEATURE.HIGH,
        getFrameRate: function () {
            return Effects.frameRate;
        },
        defaultSpeed: function () {
            switch (this.quality) {
                case QUALITY.HIGH:
                    return .1;
                case QUALITY.MED:
                    return .15;
                case QUALITY.LOW:
                    return .2;
            }
        },

        setFrameRate: function (rate) {
            this.frameRate = rate;
            return rate;
        },
        slideShows: [],
        effectFrame: function (e) {
            for (var i in this.slideShows)
                this.slideShows[i].frame(e);

        },
        frame: function (e) {
            Event.enterFrame(e);
            Effects.frameTimer = window.setTimeout(Effects.frame, Effects.frameRate);
        },
        videoBox: function (src, width, height, name, h1) {
            //var myvid = new Video({ target: $("#headline"), src: src, autoPlay: true });
            if (!width)
                width = 640;
            if (!height)
                height = 480;

            if (!name)
                name = src;

            if (!Video.supportsVideo())
                height -= 20;



            $.fancybox({
                content: " ",
                width: width,
                height: height,
                margin: 10,
                style: "cfabox-white",
                autoDimensions: false,
                //title: h1,
                //titlePosition:"over",
                onComplete: function () {

                    Effects.currentVideo = new Video({ target: $("#fancybox-content"), src: src, autoPlay: true, height: height, width: width, videoName: name, h1: h1 });
                },
                onCleanup: function () {
                    $("#fancybox-content").empty();
                    $("*").trigger("closeVideobox");
                    $("#fancybox-content").html(" ");
                }
            });
        },
        audioBox: function (src, name) {
            //var myvid = new Video({ target: $("#headline"), src: src, autoPlay: true });

            if (!name)
                name = src;



            $.fancybox({
                content: " ",
                width: Audio.defaults.width,
                height: Audio.defaults.height,
                margin: 10,
                style: "cfabox-white",
                autoDimensions: false,
                onComplete: function () {

                    Effects.currentVideo = new Audio({ target: $("#fancybox-content"), src: src, autoPlay: true, audioName: name });
                },
                onCleanup: function () {
                    $("#fancybox-content").empty();
                    $("#fancybox-content").html(" ");
                }
            });
        },
        currentVideo: null,
        slideShow: function (target_id, slideClassName, navClassName, arrows, settings) {
            if (CFAPage.Media == "print")
                return;
            var target
            if (target_id.indexOf(".") == 0) {
                target_id = target_id.substr(1);
                target = $("." + target_id);
            } else
                target = $("#" + target_id);
            target.toggleClass("slideshow-root", true);
            var slides = $($(target).find("." + slideClassName));

            var maxWidth = 0;
            var totalWidth = 0;
            var maxHeight = 0;
            var totalHeight = 0;
            var onTransition = function (e) { };
            var timeOut;
            var changeUnit = 1;

            var orientation = "STACKED";
            if (settings) {
                if (settings.timeOut)
                    timeOut = settings.timeOut;
                if (settings.orientation)
                    orientation = settings.orientation;
                if (settings.onTransition)
                    onTransition = settings.onTransition;
                if (settings.changeUnit)
                    changeUnit = settings.changeUnit;
            }

            var wrapper = $(slides.first().parent());
            var innerWrapper = wrapper.wrapInner("<div class='slideshow-inner-wrapper' />").children(".slideshow-inner-wrapper").first();

            wrapper.toggleClass("slideshow-wrapper", true);
            var w = 0;
            for (var i = 0; i < slides.length; i++)
                w += $(slides[i]).width();
            $(wrapper).children(".slideshow-inner-wrapper").css("width", w + "px");

            for (var i = 0; i < slides.length; i++) {
                var slide = $(slides[i]);

                maxWidth = Math.max(slide.outerWidth(), maxWidth);
                totalWidth += slide.outerWidth();
                maxHeight = Math.max(slide.height(), maxHeight);
                totalHeight += slide.height();



                switch (orientation) {
                    case "STACKED":
                        slide.toggleClass("slideshow-stacked", true);
                        break;
                    case "WIDE":
                        slide.toggleClass("slideshow-wide", true);
                        break;
                    case "TALL":
                        slide.toggleClass("slideshow-tall", true);
                        break;
                }



            }
            if (settings.width)
                maxWidth = settings.width;
            if (settings.height)
                maxHeight = settings.height;

            var dat = { orientation: orientation, maxWidth: maxWidth, maxHeight: maxHeight, totalHeight: totalHeight, totalWidth: totalWidth, wrapper: wrapper, innerWrapper: innerWrapper };




            var d = dat;

            d.wrapper.width(d.maxWidth);
            d.wrapper.height(d.maxHeight);


            switch (d.orientation) {
                case "STACKED":
                    d.innerWrapper.width(d.maxWidth);
                    d.innerWrapper.height(d.maxHeight);
                    break;
                case "WIDE":
                    d.innerWrapper.width(d.totalWidth);
                    d.innerWrapper.height(d.maxHeight);
                    break;
                case "TALL":
                    d.innerWrapper.width(d.maxWidth);
                    d.innerWrapper.height(d.totalHeight);
                    break;
            }




            var overflow = 0;
            if (settings.overflow)
                overflow = settings.overflow;

            var nav = null;
            if (navClassName)
                nav = $("." + navClassName);
            var slideShow = { target: target, targetId: target_id, slides: slides, overflow: overflow, changeUnit: changeUnit,
                current: 0,
                size: slides.length,
                timeOut: timeOut,
                currentTime: 0,
                nav: nav,
                wrapper: wrapper,
                innerWrapper: innerWrapper,
                orientation: orientation,
                onTransition: onTransition,
                mouseOver: function () {
                    this.currentTime = -this.timeOut;
                },
                mouseOut: function () {
                    this.currentTime = 0;
                },
                set: function (index, auto) {
                    this.currentTime = 0;
                    this.current = index;
                    //if (index == this.size - 1)
                      //  this.currentTime -= this.timeOut;
                    if (this.nav)
                        for (var i = 0; i < this.nav.length; i++) {
                            if (i != index)
                                $(this.nav[i]).toggleClass("active", false);
                            else
                                $(this.nav[i]).toggleClass("active", true);
                        }

                    $(slides).each(function () {
                        $(this).toggleClass("front", false);

                    });
                    $(slides[index]).toggleClass("front", true);
                    switch (this.orientation) {
                        case "STACKED":
                        case "FADE":
                        case "STACK":
                            $(slides).each(function () {
                                $(this).fadeOut();
                            });
                            $(slides[index]).fadeIn();
                            break;
                        case "WIDE":
                            //var targetPos = $(slides[index]).position().left;
                            if ($(slides[index]).get(0)) {
                                var targetPos = $(slides[index]).get(0).offsetLeft - this.innerWrapper.get(0).offsetLeft;
                                var newTween = new Tween(this.wrapper, "scrollLeft", true, targetPos, Effects.defaultSpeed() / 2);
                                newTween.ease = "OUT";
                                newTween.fire(this.target.attr("id"));
                            }
                            break;
                        case "TALL":
                            //var targetPos = $(slides[index]).position().top;
                            if ($(slides[index]).get(0)) {
                                var targetPos = $(slides[index]).get(0).offsetTop - this.innerWrapper.get(0).offsetTop;
                                var newTween = new Tween(this.wrapper, "scrollTop", true, targetPos, Effects.defaultSpeed() / 2);
                                newTween.ease = "OUT";
                                newTween.fire(this.target.attr("id"));
                            }
                            break;
                    }

                    this.onTransition({ i: index, slides: $(slides), target: $(slides[index]), root: this.target });

                    if (!auto) {
                        if (!slides[index].id)
                            CFAPage.params[this.targetId] = index;
                        else
                            CFAPage.params[this.targetId] = slides[index].id;
                        CFAPage.FormatHash();
                    }

                },
                next: function (auto) {

                    if (this.current + this.changeUnit >= this.size)//Loop
                        this.set(0, auto);
                    else if (this.current + this.changeUnit * 2 >= this.size)
                        this.set(this.size - this.changeUnit, auto);
                    else
                        this.set(this.current + this.changeUnit, auto);
                },
                prev: function () {

                    if (this.current <= 0)//Loop
                        this.set(this.size - this.changeUnit);
                    else if (this.current - this.changeUnit < 0)
                        this.set(0);
                    else
                        this.set(this.current - this.changeUnit);
                },
                currentSlide: function () {
                    return this.slides[this.current];
                },
                frame: function (e) {
                    this.currentTime++;
                    if (this.currentTime > this.timeOut) {
                        this.next(true);
                    }
                }
            };

            slideShow.target.get(0).slideShow = slideShow;
            if (slideShow.size > 1)
                slideShow.target.hover(
        function () { $(this).toggleClass("hover", true); this.slideShow.mouseOver(); },
        function () { $(this).toggleClass("hover", false); this.slideShow.mouseOut(); });

            for (var i in arrows) {
                arrows[i] = document.getElementById(arrows[i]);
                arrows[i].slideShow = slideShow;
                $(arrows[i]).css({ cursor: "pointer" });
                if (Effects.feature >= FEATURE.HIGH) {
                    $(arrows[i]).hover(function () {
                        $(this).css("opacity", 1);
                    }, function () {
                        $(this).css("opacity", .5);
                    });
                    $(arrows[i]).css("opacity", .5);
                }
            }

            $("." + navClassName).each(function (i) {
                this.slideShow = slideShow;
                this.index = i;
                $(this).css("cursor", "pointer");
                $(this).click(function () {
                    this.slideShow.set(this.index);
                });
            });

            if (arrows && arrows.left)
                $(arrows.left).click(function () {
                    this.slideShow.prev();

                });

            if (arrows && arrows.right)
                $(arrows.right).click(function () {
                    this.slideShow.next();
                });

            if (timeOut && slides.length > 1)
                Effects.slideShows.push(slideShow);

            if (!CFAPage.params || !CFAPage.params[target_id])
                slideShow.set(0, true);
            else if (isNumeric(CFAPage.params[target_id]))
                slideShow.set(Number(CFAPage.params[target_id]));
            else {
                for (var i in slideShow.slides) {
                    //if (isNumeric(i))
                    //  alert(slideShow.slides[i].id + ":" + CFAPage.params[target_id] + ":" + (slideShow.slides[i].id == CFAPage.params[target_id]));
                    if (isNumeric(i) && slideShow.slides[i].id == CFAPage.params[target_id]) {
                        slideShow.set(i);
                        break;
                    }
                }
            }

            return slideShow;
        },
        initFrame: function () {
            this.frameTimer = window.setTimeout(this.frame, this.frameRate);
        },
        timeline: function (jque, drag) {
            jque.jScrollPane({ horizontalDragMaxWidth: drag, hideFocus: true });
        },
        backShadow: function (dom, orientation, tooltippos) {
            if (!dom)
                return;


            var shadowoffset = 10;
            var shadowWidth = 9;
            if (!dom.shadow) {
                dom.shadow = $("<div class='back-shadow'><div class='back-shadow-top'><div class='back-shadow-NW'></div><div class='back-shadow-N'></div><div class='back-shadow-NE'></div>" +
            "</div><div class='back-shadow-middle'><div class='back-shadow-W'></div><div class='back-shadow-C'></div><div class='back-shadow-E'></div></div>" +
            "<div class='back-shadow-bottom'><div class='back-shadow-SW'></div><div class='back-shadow-S'></div><div class='back-shadow-SE'></div></div></div>");

                $(dom).append(dom.shadow);
            }
            var offset = $(orientation).position();
            var top = offset.top - shadowoffset;
            var left = offset.left - shadowoffset;
            if (tooltippos && tooltippos.indexOf("left") != -1)
                offset.left += 0;

            var box = {
                NE: { w: 20, h: 24 },
                NW: { w: 25, h: 24 },

                SE: { w: 20, h: 19 },
                SW: { w: 25, h: 19 },

                E: { w: 20, h: 1 },
                W: { w: 25, h: 1 },

                N: { w: 1, h: 24 },
                S: { w: 1, h: 19 },
                C: { w: 1, h: 1 }
            };

            var newW = $(dom).width() + shadowoffset + shadowWidth;
            var newH = $(dom).height() + shadowoffset + shadowWidth;



            $(dom.shadow).find(".back-shadow-N").width(newW - (box.NW.w + box.NE.w));
            $(dom.shadow).find(".back-shadow-S").width(newW - (box.NW.w + box.NE.w));
            $(dom.shadow).find(".back-shadow-C").width(newW - (box.NW.w + box.NE.w));

            $(dom.shadow).find(".back-shadow-W").height(newH - (box.NW.h + box.SW.h));
            $(dom.shadow).find(".back-shadow-E").height(newH - (box.NW.h + box.SW.h));
            $(dom.shadow).find(".back-shadow-C").height(newH - (box.NW.h + box.SW.h));



            var browser;
            var ext;
            if (CFAPage.Browser.id == "IE") {
                browser = "ie-shadow";
                ext = "gif";
            } else {
                browser = "webkit";
                ext = "png";
            }

            for (var i in box) {
                var dim = box[i];
                if (dim.w > 1)
                    $(dom.shadow).find(".back-shadow-" + i).width(dim.w);
                if (dim.h > 1)
                    $(dom.shadow).find(".back-shadow-" + i).height(dim.h);

                $(dom.shadow).find(".back-shadow-" + i).css("background-image", "url(/Media/Img/widgets/popup/" + browser + "/" + i + "." + ext + ")");
                $(dom.shadow).find(".back-shadow-" + i).css("float", "left")
            }

            $(dom.shadow).width(newW);
            $(dom.shadow).height(newH);

            //$(dom.shadow).offset({ top: -2, left: -2});

            $(dom.shadow).css({ top: -shadowoffset + "px", left: -shadowoffset + offset.left + "px" });
            var oldZ = Number($(dom).css("z-index"));
            var newZ = oldZ > 500 ? oldZ - 100 : oldZ - 10;

            if (!isNaN(newZ))
                $(dom.shadow).css("z-index", newZ);


            return dom.shadow;
        },
        toolTip: function (options) {
            var target = options.target;
            var spot = CFA.Quad(target);

            var targetPos, tooltipPos, tipPos;

            var ph = spot.h == "left" ? "right" : "left";

            var pv = spot.v == "bottom" ? "top" : "bottom";
            if (options.fixV) {
                pv = options.fixV;
                spot.v = options.fixV;
            }
            if (options.pullV) {
                if (!options.position)
                    options.position = { adjust: {} };
                switch (pv) {
                    case "top":
                        options.position.adjust.y += options.pullV;
                        break;
                    case "middle":
                        options.position.adjust.y = 0;
                        break;
                    case "bottom":
                        options.position.adjust.y += -options.pullV;
                        break;

                }
            }

            if (!options.position || !options.position.corner || !options.position.corner.target) {
                if (options.axis && options.axis == "v") {
                    targetPos = pv + ph.substring(0, 1).toUpperCase() + ph.substring(1);
                    tooltipPos = spot.v + spot.h.substring(0, 1).toUpperCase() + spot.h.substring(1);
                } else {
                    targetPos = ph + pv.substring(0, 1).toUpperCase() + pv.substring(1);
                    tooltipPos = spot.h + spot.v.substring(0, 1).toUpperCase() + spot.v.substring(1);
                }
            }


            tipPos = tooltipPos;

            var optionsdefaults = {
                Rest: false,
                now: false,
                content: "No Content!",
                show: {
                    effect: { type: "fade", length: 300 },
                    when: "mouseover",
                    solo: false
                },
                hide: {
                    effect: { type: "fade", length: 300 },
                    when: "mouseout",
                    fixed: true
                },

                position: {
                    corner: {
                        target: targetPos,
                        tooltip: tooltipPos
                    },
                    adjust: {
                        resize: false,
                        scroll: false
                    }
                },
                style: {
                    tip: { corner: tipPos, size: { x: 12, y: 24} },
                    name: "cfa",
                    zIndex: 40
                },
                api: {
                    onShow: function () {

                        Effects.backShadow(this.elements.tooltip, this.elements.wrapper, this.options.style.tip.corner);
                    },
                    onRender: this.onShow,
                    onPositionUpdate: this.onShow,
                    onContentUpdate: this.onShow
                }
            };



            options = $.extend(true, {}, optionsdefaults, options);




            if (options.Rest)
                options.content = CFA.getLoaderBox("SM");


            options.api.beforeShow = function () {

                //Effects.backShadow(this.elements.tooltip, this.elements.wrapper, this.options.style.tip.corner);
            }
            options.api.onPositionUpdate = options.api.beforeShow;
            options.api.beforeRender = options.api.beforeShow;
            options.api.onContentUpdate = options.api.beforeShow;
            options.api.beforeContentUpdate = options.api.beforeShadow;

            if (options.Rest) {
                options.api.onContentUpdate = options.api.onShow;
                options.api.onShow = function () {
                    if (!this.options.Rest.loaded)
                        Event.wait(this, 1, function (e) {
                            e.target.options.Rest.Load(e.target, function (e) {
                                e.target.updateContent(e.data);
                                $('.qtip:visible').qtip('api').updatePosition();

                                Effects.backShadow(e.target.elements.tooltip, e.target.elements.wrapper, e.target.options.style.tip.corner);
                            });
                        }, "tooltip_rest");

                    Effects.backShadow(this.elements.tooltip, this.elements.wrapper, this.options.style.tip.corner);
                }

            }


            $(target).qtip(options);
            if (options.now)
                $(target).click();
        }
    };
    Effects.resetFrameRate();
function Tween(target, variable, isValue, end, speed) {
    if (!target)
        return;
    if (!speed)
        speed = Effects.defaultSpeed();
    this.speed = speed;
    this.target = target;
    this.done = 0;
    this.ease = "NONE";
    this.isValue = isValue;
    if (isValue)
        this.start = target[variable]();
    else {
        this.onFrame = variable;
        this.start = end.start; end = end.end;
    }
    this.variable = variable;
    this.end = end;

    

    return this;
}


Tween.prototype.frame = function (d) {
    if (!d) {
        this.done += this.speed;

        d = this.done;
    }
    var action = d;
    if (Effects.quality >= QUALITY.HIGH)
        switch (this.ease) {
        case "IN":
            action = action * action;
        case "OUT":
            action = Math.sqrt(action);
        case "NONE":
        default:
            break;
    }
    var interpValue = ExtMath.interpolate(this.start, this.end, action);
    
    if (this.isValue)
        this.target[this.variable](Math.round(interpValue));
    else {

        this.onFrame({ target: this.target, d: action, start: this.start, end: this.end, pos: interpValue });
    }
    return d;
}

Tween.nextId = 0;
Tween.instances = new Array();

Tween.prototype.reset = function () {
    this.done = 0;
}

Tween.prototype.fire = function (id) {

    if (this.end == this.start)
        return;
    var isAutoId = false;
    if (!id) {
        Tween.nextId++;
        id = Tween.nextId;
        isAutoId = true;
    }
    this.id = id;
    for (var i = 0, len = Tween.instances.length; i < len; i++)
        if (Tween.instances[i].id == id) {
           
            Event.removeEnterFrame(Tween.instances[i].enterFrame);
            Tween.instances.splice(i, 1);
            break;
        }

    Tween.instances.push(this);

    this.enterFrame = Event.addEnterFrame(
		function (e) {
		    var d = e.target.done;

		    if ((d + e.target.speed) >= 1) {
		        e.target.frame(1);
		        Event.removeEnterFrame(e);
		        if (e.target.onComplete)
		            e.target.onComplete({ target: e.target.target, self: e, count: e.count });
		        for (var i = 0, len = Tween.instances.length; i < len; i++)
		            if (Tween.instances[i].id == e.target.id) {
		                Tween.instances.splice(i, 1);
		                return;
		            }
		    } else {
		        e.target.frame();
		    }
		},
		this);

}


		var VideoState = {
            PLAYING:1,
            PAUSED:2,
            STOPPED:3,
            BUFFERING:4,
            ERROR:5
        };

		function Video(argObj) {

		    this.marker = 0;
		    this.loaded = 0;
		    this.length = 0;
		    this.state = VideoState.PLAY;
		    this.reportedHalf = false;
		    this.reportedWhole = false;
            this.started=false;
		    this.videoSrc = argObj.src;

		    this.videoName = "Video";

		    if (argObj.videoName)
		        this.videoName = argObj.videoName;

		    this.targetStyle = null;
            
		    for (var i in Video.defaults)
		        this[i] = Video.defaults[i];

		    for (var i in argObj)
		        this[i] = argObj[i];

		    if (this.target == null)
		        this.target = $("<div id='js-video-wrapper'>").appendTo(document);



		    $(this.target).empty();

		    if (argObj.h1) {

		        $(this.target).append("<div class='video-wrapper'><h3 class='cfa video-title'>" + argObj.h1 + "</h3><div class='vid-target'></div></div>");
		        this.target = $(this.target).find(".vid-target");
		    }

		    if (Video.supportsVideo()) {

		        var vid = $("<video />").appendTo(this.target);

		        if (CFAPage.Browser.flag == "Android")
		            $(vid).click(function () { this.play(); });

                if(this.autoPlay)
                    $(vid).attr("autoplay", "autoplay");
                
                $(vid).attr("controls", "controls");
                $(vid).attr("width", this.width);
                $(vid).attr("height", this.height);
                


		        var src;
		        src = $("<source />").appendTo($(vid));
		        $(src).attr("src", "Media/Mov/ogg/" + this.videoSrc + ".ogv");
		        $(src).attr("type", "video/ogg");
		        $(src).attr("codecs", "theora, vorbis");
		        $(src).attr("error", "alert('error FF');");
		        //$(src).attr("poster", "Media/Img/content/widgets/loadingLG.gif")

		        src = $("<source />").appendTo($(vid));
		        $(src).attr("src", "Media/Mov/mp4/" + this.videoSrc + ".mp4");
		        $(vid).get(0).videoObj = this;
		        $(vid).get(0).addEventListener("play", this.onPlay);
		        $(vid).get(0).addEventListener("pause", this.onPause);
		        $(vid).get(0).addEventListener("seeked", this.onSeek);
		        $(vid).get(0).addEventListener("volumechange", this.onVolume);
		        //$(vid).get(0).addEventListener("ontimeupdate", this.onTime);
		        //$(vid).get(0).addEventListener("onended", this.onEnded);

                Event.addEnterFrame(this.onTime, $(vid).get(0), "frame"+this.videoName);

		        //$(src).attr("type", "video/mp4");
		        //$(src).attr("codecs", "avc1.42E01E, mp4a.40.2");

		    } else if($.flash.available){
		    
		        $(this.target).flash({
		            swf: "Media/Swf/CFAVideo.swf",
		            width: this.width,
                    height:this.height,
                    flashvars: {
                        src: "../Mov/flv/" + this.videoSrc + ".flv",
                        width: this.width,
                        height: this.height,
                        videoName:this.videoName,
                        autoplay:this.autoPlay,
                        skin: "Media/Swf/SkinOverPlayStopSeekMuteVol.swf"
                    },
                    wmode:"transparent"
                });

		    }

		    

		    return this;
		}

		Video.defaults = {
		    target: null,
            src:"notfound",
            width:640,
            height:480,
            autoPlay:true
        };

		Video.supportsVideo = function () {
		    return !!document.createElement('video').canPlayType;
        }
		

		Video.prototype.play = function (timeCode) {
		    if (!timeCode)
		        timeCode = 0;
		}

		Video.prototype.seek = function (timeCode) {
		    if (!timeCode)
		        return;
		}

		Video.prototype.stop = function () {

		}

		Video.prototype.pause = function () {

		}

		Video.prototype.volume = function (set) {

		}

		Video.prototype.mute = function (toggle) {

		}

        /*
        video begin: _gaq.push(['gatt._trackEvent','video player','video start','[VIDEO NAME]']);
        video end: _gaq.push(['gatt._trackEvent','video player','video end',[VIDEO NAME]);
        video pause: _gaq.push(['gatt._trackEvent','video player','pause',[VIDEO NAME]);
        video mute: _gaq.push(['gatt._trackEvent','video player','mute',[VIDEO NAME]);
        video 50% complete: _gaq.push(['gatt._trackEvent','video player','50% complete',[VIDEO NAME]);
        flash player in use: _gaq.push(['gatt._trackEvent','video player','flash player',[VIDEO NAME]);
        */

		Video.prototype.onPlay = function (e) {
		    var self = this;
		    if (!this.sdTool)
		        self = e.target.videoObj;
            if(!self.started)
		    self.sdTool("video start");
		    self.started=true;
		}

		Video.prototype.onSeek = function (e) {

		}

		Video.prototype.onEnded = function (e) {
		    var self = this;
		    if (!this.sdTool)
		        self = e.target.videoObj;
		    self.reportedWhole = true;
		    self.sdTool("video end");
		    $("*").trigger("videoEnd");
		}

        Video.prototype.onTime = function (e) {
            var self = this;
            if (!this.sdTool)
                self = e.target.videoObj;
		    if(!self.started)
		         return;
		    var vid = e.target;
		    if (!self.reportedHalf && e.target.currentTime / e.target.duration > .5)
		        self.onHalf(e);
		    if (!self.reportedWhole && e.target.currentTime / e.target.duration > .99)
		        self.onEnded(e);
		}

		Video.prototype.onHalf = function (e) {
		    var self = this;
		    if (!this.sdTool)
		        self = e.target.videoObj;
           self.reportedHalf=true;
           self.sdTool("50% complete");
		}

		Video.prototype.onPause = function (e) {
		    var self = this;
		    if (!this.sdTool)
		        self = e.target.videoObj;
            self.sdTool("pause");
		}
        Video.prototype.onMute = function (e) {
            var self = this;
            if (!this.sdTool)
                self = e.target.videoObj;
            self.sdTool("mute");
		}

        Video.prototype.onVolume = function (e) {
            var self = this;
            if (!this.sdTool)
                self = e.target.videoObj;
		    if (e.target.volume == 0 || e.target.muted)
		        self.onMute(e);
		}
		Video.prototype.sdTool = function (event) {
		    //if (console)
		        //console.log(event+":"+this.videoName);
            _gaq.push(['gatt._trackEvent','video player',event,this.videoName]);
        }


		var AudioState = {
		    PLAYING: 1,
		    PAUSED: 2,
		    STOPPED: 3,
		    BUFFERING: 4,
		    ERROR: 5
		};

		function Audio(argObj) {

		    this.marker = 0;
		    this.loaded = 0;
		    this.length = 0;
		    this.state = AudioState.PLAY;
		    this.audioSrc = argObj.src;
		    var audioName = "Audio";
		    if (argObj.audioName)
		        audioName = argObj.audioName;

		    this.targetStyle = null;

		    for (var i in Audio.defaults)
		        this[i] = Audio.defaults[i];

		    for (var i in argObj)
		        this[i] = argObj[i];

		    if (this.target == null)
		        this.target = $("<div id='js-audio-wrapper'>").appendTo(document);

		    $(this.target).empty();
		    if (Audio.supportsAudio()) {

		        var aud = $("<audio style='position:relative;top:14px' />").appendTo(this.target);

		        if (CFAPage.Browser.flag == "Android")
		            $(aud).click(function () { this.play(); });

		        if (this.autoPlay)
		            $(aud).attr("autoplay", "autoplay");

		        $(aud).attr("controls", "controls");
		        $(aud).attr("width", this.width);
		        $(aud).attr("height", this.height);



		        var src;
		        src = $("<source />").appendTo($(aud));
		        $(src).attr("src", "Media/Aud/Ogg/" + this.audioSrc + ".ogg");
		        $(src).attr("type", "audio/ogg");
		        $(src).attr("codecs", "theora, vorbis");
		        $(src).attr("error", "alert('error FF');");

		        src = $("<source />").appendTo($(aud));
		        $(src).attr("src", "Media/Aud/Mp3/" + this.audioSrc + ".mp3");
		        //$(src).attr("type", "video/mp4");
		        //$(src).attr("codecs", "avc1.42E01E, mp4a.40.2");

		    } else if ($.flash.available) {

		        $(this.target).flash({
		            swf: "Media/Swf/CFAAudio.swf",
		            width: Audio.defaults.width,
		            height: Audio.defaults.height,
		            flashvars: {
		                src: "Media/Aud/Mp3/" + this.audioSrc + ".mp3",
		                width: this.width,
		                height: this.height,
                        title:audioName,
		                autoplay: "true"		                
		            },
		            wmode: "transparent"
		        });

		    } else {
            /*
                $(this.target).html("<OBJECT id='mediaPlayer' width='300' height='77' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "    standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'> <param name='fileName' value='/Media/Aud/Mp3"+this.audioSrc+".mp3'>"+
                "    <param name='animationatStart' value='true'> <param name='transparentatStart' value='true'> <param name='autoStart' value='true'>"+
                "<param name='showControls' value='true'> <param name='loop' value='false'> <EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'   "+
                "id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1'  bgcolor='darkblue' showcontrols='true' showtracker='-1'  showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='300' height='77' src='/Media/Aud/Mp3" + this.audioSrc + ".mp3' autostart='true' designtimesp='5311' loop='false'> </EMBED> </OBJECT>");
                */
		        $(this.target).html('<OBJECT classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="300"  height="47" codebase="http://www.apple.com/qtactivex/qtplugin.cab">        <param name="src" value="/Media/Aud/Mp3/"' + this.audioSrc + '">        <param name="autoplay" value="true">        <param name="controller" value="true">        <param name="loop" value="true">        <EMBED src="/Media/Aud/Mp3/"' + this.audioSrc + '" width="300" height="47" autoplay="' + this.autoPlay +
                '" controller="true" loop="true" pluginspage="http://www.apple.com/quicktime/download/"></EMBED>        </OBJECT>');

		        //$(this.target).html("<OBJECT CLASSID='clsid:CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' WIDTH='" + this.width + "' HEIGHT='" + this.height + "' STANDBY='Loading Windows Media Player components...' TYPE='application/x-oleobject'" +
                //"<PARAM name='FileName' VALUE='Media/Aud/Mp3/" + this.audioSrc + ".mp3'><PARAM name='autostart' VALUE='" + this.autoPlay + "'><PARAM name='ShowControls' VALUE='true'><PARAM name='ShowStatusBar' VALUE='true'>" +
                //"<EMBED type='application/x-mplayer2' src='Media/Aud/Mp3/" + this.audioSrc + ".mp3' WIDTH='" + this.width + "' HEIGHT='" + this.height + "' Name='MediaPlayer' ShowStatusBar='1' autostart='" + this.autoPlay + "' ShowControls='1'></EMBED></OBJECT>");
		        //$(this.target).html('<EMBED src="Media/Aud/Mp3/"' + this.audioSrc + '" autostart=true hidden=true>');
		    }



		    return this;
		}

		Audio.defaults = {
		    target: null,
		    src: "notfound",		    
		    autoPlay: true,
            width:402,
            height:55
		};

		Audio.supportsAudio = function () {
		    return (!!document.createElement('audio').canPlayType) && (document.createElement('audio').canPlayType("audio/ogg") || document.createElement('audio').canPlayType("audio/mpeg"));
		}


		Audio.prototype.play = function (timeCode) {
		    if (!timeCode)
		        timeCode = 0;
		}

		Audio.prototype.seek = function (timeCode) {
		    if (!timeCode)
		        return;
		}

		Audio.prototype.stop = function () {

		}

		Audio.prototype.pause = function () {

		}

		Audio.prototype.volume = function (set) {

		}

		Audio.prototype.mute = function (toggle) {

		}

/*END MATTS CRAZY JS*/



		var CFA = {
		    Rally: function (follow, lead, usePadding) {
		        if (!usePadding)
		            follow.css("left", lead.offset().left + "px");
		        else {
		            follow.css("padding-left", lead.offset().left + "px");
		        }

		    },
		    loaded: false,
		    Constrain: function (follow, w) {
		        $(follow).css("margin-left", "0px");
		        $(follow).css("width", w + "px");
		    },
		    Refresh: function () {

		    },
		    px: function (str) {
		        return Number(str.replace(/[^0-9\.]/g, ""));
		    },
		    apImg: "",
		    preload: function (arrayOfImages) {

		        $(arrayOfImages).each(function (i) {
		            CFA.apImg = $('<img />')[0];
		            CFA.apImg.setAttribute("src", this.toString());
		            CFA.apImg.setAttribute("class", "hidden");
		            $(document).append(CFA.apImg);

		        });

		        return CFA.apImg;

		    },
		    RefreshSet: [],
		    frame: function (e) {
		        if (e.count % 60 == 0) {
		            CFA.Refresh();
		        }
		    },
		    getLoaderBox: function (size) {
		        var ext = ".png";
		        if (!size)
		            size = "LG";
		        if (size != "LG" || CFAPage.Browser.id == "IE")
		            ext = ".gif";
		        return "<div class='loaderBox'><img src='/Media/Img/widgets/loading" + size + ext + "' class='loaderImg loaderImg-" + size + "'></div>";
		    },
		    Quad: function (dom) {
		        var base = $(".main").offset();

		        base.width = $(".main").width();
		        base.height = $(".main").height();

		        var compare = $(dom).offset();
		        compare.width = $(dom).width();
		        compare.height = $(dom).height();


		        compare.left -= base.left;
		        compare.right -= base.right;
		        base.left = 0;
		        base.right = 0;

		        compare.centerX = compare.left + Math.round(compare.width / 2);
		        compare.centerY = compare.top + Math.round(compare.height / 2);

		        base.centerX = Math.round(base.width / 2);
		        base.centerY = Math.round(base.height / 2);

		        return {
		            h: compare.centerX > base.centerX ? "right" : "left",
		            v: compare.centerY > base.centerY ? "bottom" : "top"
		        };


		    }

		}




/*-------------Browser*/


var Browser = CFAPage.Browser;
Browser.print = function () {
    alert("ID:" + Browser.id + "\nOS:" + Browser.clientOS + "\nVersion:" + Browser.majorVersion + "\nMobile:" + Browser.mobile + "\nSmart Mobile:" + Browser.smartMobile);
}
//Browser.print();
if (Browser.flag) {

    switch (Browser.flag) {
        case "IE6":
            Effects.quality = QUALITY.LOW;
            $("img").each(function () {
                //alert(this.getAttribute("src").replace(/\.png$/gi, ".gif"));
                this.setAttribute("src", this.getAttribute("src").replace(/\.png$/gi, ".gif"));
            });

            break;
        case "IE7":

            break;
        case "iOS":
            Effects.quality = QUALITY.MED;
           
            break;
    }
    switch (Browser.id) {
        case "IE":
            Effects.quality = QUALITY.MED;
            Effects.feature = FEATURE.MED;            
            break;

    }
    Effects.resetFrameRate();
}

Browser.lastSubNav = function () {
    switch (Browser.flag) {
        case "IE6":
        case "IE7":
            return 40;
        default:
            return 51;
    };
    
}


var Utils = {
    is_string: function (input) {
        return typeof (input) == 'string';
    }
};

/*-------------*/

var Rest = function (page, method, builder) {
    this.page = page;
    this.method = method;
    this.id = Rest.instances.length;
    this.loaded = false;
    Rest.instances.push(this);

    if (method.search(/^get/)==-1)
        this.type = "POST";
    else
        this.type = "GET";
    this.data;
    if (builder)
        this.builder = builder;
    else
        this.builder = function (data) { return data; };
    return true;
};
Rest.Root = "Utils/Webmethods/";
Rest.instances = new Array();

Rest.prototype.Load = function (target, fn) {
    this.target = target;
    this.fn = fn;
    var dataType = "json";
    var rest = this;
    if (!Utils.is_string(rest.data)) {
        if (rest.type == "POST")
            rest.data = $.toJSON(rest.data);
        else {
            //rest.data = $.toJSON(rest.data);
            dataType = "text";
            rest.data = $.param(rest.data);
        }
    }
    if (rest.type == "POST") {
        $.ajax({
            type: rest.type,
            context: rest,
            data: rest.data,
            url: (CFAPage.Root + Rest.Root + rest.page + ".asmx/" + rest.method),
            contentType: "application/json; charset=utf-8",
            dataType: dataType,
            success: function (data) {
                //alert($.toJSON(data.d));
                this.loaded = true;
                this.fn({ target: this.target, data: this.builder(data.d) });
            }

        });
    } else {
        $.ajax({            
            context: rest,
            data: rest.data,
            url: (CFAPage.Root + Rest.Root + rest.page + ".asmx/" + rest.method),
            //contentType: "application/json; charset=utf-8",
            success: function (data) {
                //alert($.toJSON(data.d));
                this.loaded = true;
                this.fn({ target: this.target, data: this.builder(data) });
            }

        });
    }

};



/*var testRest = new Rest("Meal", "HelloWorld");
testRest.Load({ obj: 1 }, function (e) { });*/


var HintBox = function (options) {
    return this;
}


//Event.addEnterFrame(function (e) {$("#debug").html(e.count)});


var MyCFA = {
    OrderFood: function () { },
    VisitSite: function () { },
    VisitSite: function () { },
    Map: function () { },
    Edit: function () { },
    RemoveCurrent: function () { },
    freeze:false
};


var StoreFinder = {
    limit: 99,
    detail: "low",
    cancelMessage: "",
    Refresh: function () {
        $('.store-list ul').html("");
        var hdn = "";
        for (var i = 0; i < StoreFinder.stores.length; i++) {
            var store = StoreFinder.stores[i];

            var storeInfo = store.name;

            switch (StoreFinder.detail) {
                case "high":
                    $()
                    //String.format("{0}<br />{1} {2}, {3} {4}<br /><a href='http://www.chick-fil-a.com/{5}' target='_blank'>view store</a>",
                    //);
                    var locRest = new Rest("Location", "LocationById");
                    locRest.data = { pid: store.id };
                    $(".location-finder .small.loader").toggleClass("hidden", false);
                    locRest.Load({ id: store.id }, function (e) {
                        $(".location-finder .small.loader").toggleClass("hidden", true);
                        var store = e.data;
                        var address = store.LocationContact.StreetAddress;
                        var storeInfo = String.format("{0}{6}<br />{1}<br />{2}, {3} {4}<br /><a href='http://www.chick-fil-a.com/{5}' target='_blank'>view store</a>",
                            store.NameNoLocationCode, address.Address1, address.City, address.State, address.ZipCode.Zip, store.MarketableName, 
                            (store.LocationCode=="MALL" && store.NameNoLocationCode.indexOf("Mall")==-1)?" (Mall)":""
                        );
                        $('.store-list ul').append("<li><span class='store-info-text'>" + storeInfo + "</span><a href='javascript:void(0);' onclick='StoreFinder.Remove(\"" + e.target.id + "\")' class='remove-icon small inline'>" + StoreFinder.cancelMessage + "</a></li>");
                        StoreFinder.selectedStore = store;
                        StoreFinder.onAdd(store);
                    });
                    break;
                case "medium":
                    var locRest = new Rest("Location", "LocationById");
                    locRest.data = { pid: store.id };
                    locRest.Load({ id: store.id }, function (e) {
                        var store = e.data;
                        var address = store.LocationContact.StreetAddress;
                        var storeInfo = String.format("{0}<br /><a href='http://www.chick-fil-a.com/{1}' target='_blank'>view store</a>",
                            store.NameNoLocationCode, store.MarketableName
                        );
                        $('.store-list ul').append("<li><span class='store-info-text'>" + storeInfo + "</span><a href='javascript:void(0);' onclick='StoreFinder.Remove(\"" + e.target.id + "\")' class='remove-icon small inline'>" + StoreFinder.cancelMessage + "</a></li>");
                        StoreFinder.selectedStore = store;
                        StoreFinder.onAdd(store);
                    });
                    break;
                case "low":
                default:
                    $('.store-list ul').append("<li><span class='store-info-text'>" + storeInfo + "</span><a href='javascript:void(0);' onclick='StoreFinder.Remove(\"" + store.id + "\")' class='remove-icon small inline'>" + StoreFinder.cancelMessage + "</a></li>");
                    break;
            }




            var comma = i != 0 ? "," : "";
            hdn = (hdn + comma + store.id);
        }

        if (StoreFinder.stores.length >= StoreFinder.limit) {
            $(".find-more").hide();
            $(".story-place-dd").attr("disabled", "disabled");
        } else {
            $(".find-more").show();
            $(".story-place-dd").removeAttr("disabled");
        }

        $(".hdn-stores-selected").val(hdn);
        $(".find-more-msg").html(StoreFinder.firstMsg);
    },
    Remove: function (id) {
        for (var i = 0; i < StoreFinder.stores.length; i++) {
            var store = StoreFinder.stores[i];
            if (store.id == id) {
                StoreFinder.stores.splice(i, 1);
                break;
            }
        }

        StoreFinder.Refresh();
    },
    MoreStores: function () {
        $(".location-finder .find-more").toggleClass("hidden", false);
    },
    onAdd: function () { },
    selectedStore: {},
    stores: [],
    firstMsg: "",
    Add: function (target) {
        if (StoreFinder.stores.length >= StoreFinder.limit)
            return;

        target = $(target);
        var val = $(".hdn-stores-selected").val();

        var option = target.find("option:selected");
        if ($(option).val() == -1)
            return;
        var stores = StoreFinder.stores;

        for (var i = 0; i < stores.length; i++) {
            var store = stores[i].id;
            if (store == option.val())
                return;
        }
        StoreFinder.stores.push({ id: option.val(), name: option.html() });


        StoreFinder.Refresh();


        $(".add-this-location").val("add another location");

    },
    IMeant: function (dd, searchTxt) {
        dd = $(dd);
        searchTxt = $(searchTxt);
        searchTxt.toggleClass("hidden", false);
        dd.toggleClass("hidden", true);
        searchTxt.val(dd.val());
        $(".find-more-msg").html(StoreFinder.firstMsg);
        StoreFinder.Search(searchTxt, dd, dd.val(), dd.find(":selected").html());
    },
    Search: function (src, didYouDd, q, cute) {
        src = $(src);
        if (!q)
            q = src.val();
        src.val('');

        //zip code
        if (q.search(/^[0-9]+$/) != -1 && q.length != 5) {
            $(".find-more-msg").html("Please enter a five digit zip code: ");
            return;
        }

        if (q.length <= 2) {
            $(".find-more-msg").html("Sorry, your search was too short. Please search again: ");
            return;
        }

        $(".location-finder .loader").toggleClass("hidden", false);

        var locRest = new Rest("Location", "Search");
        locRest.data = { q: q, radius: "60" };
        locRest.Load({ dd: $(".story-place-dd"), didYou: $(didYouDd), src: src, q: q, cute: cute }, function (e) {

            e.target.src.toggleClass("hidden", false);
            e.target.didYou.toggleClass("hidden", true);

            $(".location-finder .loader").toggleClass("hidden", true);


            if (!e.data || e.data.Empty) {
                $(".find-more-msg").html("Sorry, no stores were found. Please search again: ");
                return;
            }


            if (e.data.HasLocations) {
                var options = e.target.dd;
                options.html("<option value='-1'>Select a Store</option>");

                if (e.target.cute)
                    e.target.q = e.target.cute;

                $(".location-finder-nearby").html("Locations near " + e.target.q + ":");
                $(".find-more-msg").html(StoreFinder.firstMsg);
                $.each(e.data.Locations, function (i, item) {

                    var opt = $("<option />");
                    opt.val(item.LocationNumber);
                    opt.html(item.NameNoLocationCode);
                    $(".location-finder").data(item.NameNoLocationCode, item);
                    options.append(opt);
                });
            } else if (e.data.MultipleAddresses && e.data.MultipleAddresses.length > 1) {
                $(".find-more-msg").html("<strong>Did you mean</strong>:")
                src.toggleClass("hidden", true);

                var options = e.target.didYou;

                options.html("<option value='-1'>Select a City</option>");
                options.toggleClass("hidden", false);

                $.each(e.data.MultipleAddresses, function (i, item) {

                    var opt = $("<option />");
                    opt.val(item.ZipCode.Zip);
                    opt.html(item.City + ", " + item.State + " " + item.ZipCode.Zip);
                    options.append(opt);
                });
                src.val(options.find("option:selected").val());
            } else {
                $(".find-more-msg").html("Sorry, no stores were found. Please search again.");
                return;
            }

            //$(".location-finder .find-more").toggleClass("hidden", true);
        });
    }
};
$(function () {
    StoreFinder.firstMsg = $(".find-more-msg").html();
    $(".story-place-dd").change(function () {
        StoreFinder.Add('.story-place-dd');
    });
    $(".txt-find-more").keypress(function (e) {
        if (e.which == 13) {
            StoreFinder.Search(this, ".did-you-mean");
            return false;
        }

    });
    if ($(".location-finder").attr("limit")) {
        StoreFinder.limit = Number($(".location-finder").attr("limit"));
    }
    if ($(".location-finder").attr("detail")) {
        StoreFinder.detail = ($(".location-finder").attr("detail"));
    }
    if ($(".location-finder").attr("cancelMessage")) {
        StoreFinder.cancelMessage = ($(".location-finder").attr("cancelMessage"));
    }

})

function _StringFormatInline() {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}

function _StringFormatStatic() {
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
}

if (!String.prototype.format) {
    String.prototype.format = _StringFormatInline;
}

if (!String.format) {
    String.format = _StringFormatStatic;
}





