Site = {

    innit: function () {

        $(function () {
            //$('#news-link').click();
            Navigation.showSub();

            //hack to get colors working on latest news links on hover
            $('#latest-news li, #mortgage-offer li').hover(function () {
                var li = $(this);
                $('*', li).addClass('all-white');
            }, function () {
                var li = $(this);
                $('*', li).removeClass('all-white');
            });

            //fix the height of the main content div

        });
    }
};

Images = {

    checkPortrait: function (img) {
        //console.log($(img).width());
        //console.log($(img).height());
        $("<img/>") // Make in memory copy of image to avoid css issues
            .attr("src", $(img).attr("src"))
            .load(function () {
                pic_real_width = this.width;   // Note: $(this).width() will not
                pic_real_height = this.height; // work for in memory images.
                if (pic_real_width < pic_real_height) {
                    //image is portrait
                    $(img).attr("height", "247");
                    $(img).attr("width", "149");
                }
            });
    }

};

Navigation = {
    toggleSubNav: function (l) {
        var link = $(l);
        var subholder = link.next();
        link.parent().parent().find("a").removeClass("on");

        if (subholder.hasClass('showing')) {
            subholder.slideUp();
            subholder.removeClass('showing');
        }
        else {
            subholder.slideDown();
            subholder.addClass('showing');
            link.addClass("on");
        }
    },

    toggleQuickSearch: function (l) {
        var link = $(l);
        var quicksearch = $('#quick-search-form');
        if (quicksearch.is(":hidden")) {
            quicksearch.slideDown();
            link.removeClass("closed");
        }
        else {
            quicksearch.slideUp();
            link.addClass("closed");
        }
    },

    togglePriceDropDown: function (dd) {
        //if rental type is property then show price band seleciton, otherwise hide it
        var selection = $(dd).val();
        if (selection == "Investment") {
            $('.InvestmentPriceDropDown').show();
            $('.RentalPriceDropDown').hide();
        }
        else {
            $('.InvestmentPriceDropDown').hide();
            $('.RentalPriceDropDown').show();
        }
    },
    hideSubs: function () {
        $('.sub-menu-holder').css('display', 'none').removeClass('showing');
        $('#left-navigation > li > a').removeClass("on");
    },

    showSub: function () {
        Navigation.hideSubs();
        var currentLocation = window.location.pathname;

        $('#left-navigation .sub-menu-holder a').each(function (i, el) {
            var link = $(el).attr('href');
            if (link == currentLocation) {
                $(el).addClass('active').closest('.sub-menu-holder').addClass('showing').slideDown();
                $(el).parent().parent().parent().prev().addClass("on");

            }
        });
    }
};

var MessageSystem = {

    showMessage: function (title, message, sticky) {
        if (title === undefined) title = "Relenster";
        if (message === undefined) message = "Loading your Request";
        if (sticky === undefined) sticky = false;
        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: title,
            // (string | mandatory) the text inside the notification
            text: message,
            sticky: sticky
        });
    }

};

var Slideshow = {

    holder: ".centre-holder",
    time: 10000,

    run: function (hol, time) {
        if (hol != undefined)
            Slideshow.holder = hol;

        if (time != undefined)
            Slideshow.time = time;

        if($('img', $(Slideshow.holder)).length > 1)
            setInterval("Slideshow.slide()", Slideshow.time);
    },

    slide: function () {
        //get holder
        //console.log("changing image");
        var h = $(Slideshow.holder);
        var active = $('img.active', h);
        if (active.length == 0) active = $('img:last', h);

        var next = active.next().length ? active.next() : $('img:first', h);

        active.addClass('last-active');
        next.css({ opacity: 0.0 })
            .addClass('active')
            .animate({ opacity: 1.0 }, 1000, function () {
                active.removeClass('active last-active');
            });
    }

};

SearchOverview = {

    toLet: '#925C8D',
    toBuy: '#0EB7A2',
    student: '#C16661',

    toggleForm: function (l) {

        var link = $(l);
        var form = link.next();
        //hide all other forms
        $('.overview-form').each(function (i, f) {
            $(f).slideUp().addClass("hidden").parent().animate({ backgroundColor: '#EDF4FC', color: '#003569' }, "fast");
            $('a.title', $(f).parent()).animate({ color: '#003569' }, "fast");
        });
        //now slide down the one we clicked - this has got very slow and unweidly but im leaving it as is as a reminder to not do is again
        if (form.hasClass("hidden")) {
            var colour = '';
            if (form.parent().hasClass("form-student"))
                colour = SearchOverview.student;
            else if (form.parent().hasClass("form-tolet"))
                colour = SearchOverview.toLet;
            else
                colour = SearchOverview.toBuy;

            form.slideDown(function () {
                form.removeClass("hidden");
            }).parent().animate({ backgroundColor: colour, color: '#fff !important' }, "fast");
            $('a.title', form.parent()).animate({ color: '#fff' }, "fast");
        }
        else {
            form.slideUp(function () {
                form.addClass("hidden");
            }).parent().animate({ backgroundColor: '#EDF4FC', color: '#003569 !important ' }, "fast");
            $('a.title', form.parent()).animate({ color: '#003569' }, "fast");
        }

    }

};

SearchFilter = {
    filter: function (f) {
        //$.log("filter intercepted");
        //serialise and add to has
        var form = $(f);
        var data = form.serialize();
        var host = window.location.host;
        var path = window.location.pathname;
        var search = window.location.search;
        //window.location.search = "";
        var fullurl = window.location.href;
        window.location.hash = "/Property/SearchResults/?" + data;

        return false;
    },

    GetSearchResults: function () {
        //url has changed - do something.
        var search_area = $('#search-results');
        var overlay = $('#search-overlay');
        overlay.show();
        var hashlink = window.location.hash;
        var gifloader = $('.ajax-loader');
        gifloader.show();
        if (hashlink.length > 0) {
            var url = hashlink.substring(1, window.location.hash.length);
            $.get(url, null, function (update) {
                search_area.html(update);
                //search_area.slideDown();
                overlay.hide();
                gifloader.hide();
            });
        }
    },

    pageData: function (a) {
        var link = $(a);
        var page = link.attr('rel');
        //set hidden form field and submit form
        var form = $('#filter-search-form');
        $('input[name=page]').val(page);
        //form.submit();
        $('#quick-filter-button').click();
    },

    setOrdering: function (sel) {
        var dd = $('option:selected', $(sel)).val();
        //set hidden input on search form
        var form = $('#filter-search-form');
        $('input[name=orderby]').val(dd);
        //form.submit();
        $('#quick-filter-button').click();


    },

    SwitchMode: function (display) {
        //locate hidden form field

        var form = $('#filter-search-form');
        $('input[name=format]').val(display);
        $('#quick-filter-button').click();
    },

    showFlyout: function (l) {
        var link = $(l);
        $('.flyout').each(function () {
            $(this).hide();
        });
        var flyout = link.next('.flyout');
        flyout.show();
        return false;
    },

    closeFlyout: function (l) {
        var link = $(l);
        var flyout = link.closest('.flyout');

        flyout.hide();
        //remove class from submenu link
        flyout.prev().removeClass("selected");

    },

    setFormElement: function (l) {
        var link = $(l);
        var context = link.closest('ul');
        $('a', context).removeClass('selected');
        link.addClass('selected');
        var info = link.attr('rel');
        var infoArray = info.split('|');
        var select = infoArray[0];
        var value = infoArray[1];
        //ADDED TO HIDE SHOW PRICE BAND SELECTION
        if (select == "RentalType") {
            SearchFilter.toggleSelectors(value);
        }
        //set the hidden form element and call refresh
        var form = $('#filter-search-form');
        var formElement = $('select[name=' + select + ']', form);
        //reset page back to 1 as we are changing the filter
        $('#search-filter-page').val("1");
        formElement.val(value);
        SearchFilter.filter(form.get(0));
    },

    toggleSelectors: function (value) {
        if (value == "Investment") {
            //hide the price flyout and show the price band one
            $('#InvestmentPrice-flyout').parent().show();
            $('#Rent-flyout').parent().hide();
            //console.log("Investment Selected");
        }
        else {
            $('#InvestmentPrice-flyout').parent().hide();
            $('#Rent-flyout').parent().show();
            //console.log("Investment Not Selected");
        }
    }
};

var EnquirySystem = {
    process: function (f) {
        var formholder = $('#form-holder');
        var form = $(f);
        var data = form.serialize();
        var url = form.attr("action");
        $.post(url, data, function (response) {
            formholder.html(response.html);
        }, "json");
    },

    processContactForm: function (f) {
        var form = $(f);
        var data = form.serialize();
        var action = form.attr('action');
        $.post(action, data, function (response) {
            if (response.worked) {
                MessageSystem.showMessage("Contact System", response.message, false);
                Utilities.clearForm(form.attr('id'));
            } else {
                $('#form-holder').html(response.html);
                MessageSystem.showMessage("Enquiry System", response.message, false);
            }
        });

    }
};

var FavSystem = {

    addToFavs: function (a) {
        var link = $(a);
        var prop = link.attr('rel');
        var favsArea = $('#favourites');
        $.post("/Property/AddToFavourites/", { PropertyRef: prop }, function (response) {
            if (response.worked) {
                MessageSystem.showMessage("Favourites", response.message, false);
                favsArea.html(response.html);
                var favsDiv = $('#favourites');
                if (favsDiv.is(":hidden")) {
                    favsDiv.slideDown();
                }
            }
            else {
                MessageSystem.showMessage("Favourites", "Could not add to favourites at this time. Please try again.", true);
            }
        });
    },

    removeFromFavs : function(a) {
        var link = $(a);
        var prop = link.attr('rel');
        var favsArea = $('#favourites');
        $.post("/Property/DeleteFromFavourites/", { propertyRef: prop }, function (response) {
            if (response.worked) {
                MessageSystem.showMessage("Favourites", "Deleted from favourites", false);
                favsArea.html(response.html);
                var favsDiv = $('#favourites');
                if (favsDiv.is(":hidden")) {
                    favsDiv.slideDown();
                }
            }
            else {
                MessageSystem.showMessage("Favourites", "Could not add to favourites at this time. Please try again.", true);
            }
        });
    },

    showFavs: function () {
        var favsDiv = $('#favourites');
        if (favsDiv.is(":hidden")) {
            favsDiv.slideDown();
        }
    },

    hideFavs: function () {
        $('#favourites').slideUp();
    }

};


var SearchFilterGenerator = {

    buildNewForm: function (f) {
        var newElements = new Object();
        var form = $(f);
        //loop over each form select group and add to master array
        $('select', form).each(function (i, sel) {
            //get name of select
            var name = $(sel).attr('name');
            newElements[name] = new Object();
            var options = $('option', sel);
            options.each(function (j, opt) {
                if ($(opt).is(":selected")) {
                    newElements[name][$(opt).val()] = 1;
                }
                else {
                    newElements[name][$(opt).val()] = 0;
                }
            });
        });
        //console.log(newElements);
        //loop over 'array' and make new radio UL's

        var investment = false;

        for (prop in newElements) {
            var flyout = $('#' + prop + "-flyout");

            var html = "<ul class='flyout-submenu'>";
            //modified to account for price band option

            //for (var i = 0; i < newElements[prop].length; i++) {
            //    html += "<li><a rel='" + prop + "|" + newElements[prop][i] + "' onclick='SearchFilter.setFormElement(this); return false;'>" + newElements[prop][i] + "</a></li>";
            //}
            var cssclass = "";

            /*
            UPDATE - need to check if they are looking at investment or other and hide or show the correct price selector
            */

            for (li in newElements[prop]) {

                if (newElements[prop][li] == 1) {
                    cssclass = "selected";
                    if (prop == "RentalType") {
                        //if investment is selected, hide price
                        if (li == "Investment")
                            investment = true;
                    }
                }
                else {
                    cssclass = "";
                }

                html += "<li><a class=\"" + cssclass + "\" rel='" + prop + "|" + li + "' onclick='SearchFilter.setFormElement(this); return false;'>" + li + "</a></li>";
                //html += "<li><a class='" + "test" + "'  rel='" + prop + "|" + li + "' onclick='SearchFilter.setFormElement(this); return false;'>" + li + "</a></li>";
            }

            html += "</ul>";
            //console.log(html);
            var holder = $('.list', flyout);
            holder.html(html);
                
        }
    }

};

var Newsletters = {

    signup: function (f) {
        var form = $(f);
        var data = form.serialize();
        var action = form.attr("action");
        var form = $('#subscribe-form');

        $.post(action, data, function (response) {
            if (response.worked) {
                MessageSystem.showMessage("Newsletter", response.message, false);
                $('input', form).val("");
            }
            else {
                MessageSystem.showMessage("Newsletter", response.message, false);
            }
        });
    }

};

var SearchResults = {

    innit: function () {

        $('.hidden').slideUp("fast");

        //check for presence of hash tag and fire off get request
        var form = $('#filter-search-form');
        $('#search-filter-link').click();
        $('#quick-search-link').click();
        if (window.location.hash.length > 0) {
            //repopulate form from hash data
            var data = window.location.hash.substring(26);

            var d = Utilities.parseUrl(data);
            form.values(d);

            //build new form from current form

            SearchFilter.GetSearchResults();
        }
        else {
            //may have come here from a the quick search. check for search data in the url
            if (window.location.search.length > 0) {
                //have commendted out - no idea why I wrote this
                //console.log(window.location.search);
                //var data = window.location.search.substring(1);

                //var d = Utilities.parseUrl(data);
                //form.values(d);
            }
        }
        SearchFilterGenerator.buildNewForm(form);
        var context = $('#RentalType-flyout');
        var selected = "";
        $('a', context).each(function (i, l) {
            var link = $(l);
            if (link.hasClass("selected"))
                selected = link.html();
        });
        SearchFilter.toggleSelectors(selected);
    }
};

var Googlemap = {
    lats: [],
    lngs: [],
    j: 0,
    info: [],
    m: null,
    imgs: [],

    reset: function () {
        Googlemap.lats = [];
        Googlemap.lngs = [];
        Googlemap.j = 0;
        Googlemap.info = [];
        Googlemap.m = null;
        Googlemap.imgs = [];
    },

    getMed: function (anarray) {
        var max = min = anarray[0];

        for (i in anarray) {
            var t = anarray[i];
            if (t > max) max = t;
            if (t < min) min = t;
        }

        return ((max - min) / 2) + min;
    },

    imagePath: function (type) {
        return "/content/images/map-marker.jpg";

    },

    init: function (map) {
        $('#no-results').length && $('#no-results').fadeOut(5000, function () { $('#no-results').remove() });
        Googlemap.m = new google.maps.Map(document.getElementById(map), {
            zoom: 10,
            center: (Googlemap.j > 1) ? new google.maps.LatLng(Googlemap.getMed(Googlemap.lats), Googlemap.getMed(Googlemap.lngs)) : new google.maps.LatLng(Googlemap.lats[0], Googlemap.lngs[0]),
            //center: new google.maps.LatLng(53.2262139, -0.5448295),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        for (x in Googlemap.lats) Googlemap.marker(Googlemap.lats[x], Googlemap.lngs[x], Googlemap.imgs[x], Googlemap.info[x]);
    },

    marker: function (lat, lng, img, info) {
        var mr = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            map: Googlemap.m,
            //title: info,
            icon: new google.maps.MarkerImage(Googlemap.imagePath(img), new google.maps.Size(10, 10))
            //title: info.replace(/\<br\s*\/\>/g,", ")
        });

        google.maps.event.addListener(mr, 'click', function () {
            //Googlemap.m.panTo(new google.maps.LatLng(lat, lng));
            var infowindow = new InfoBox({ latlng: mr.getPosition(), map: Googlemap.m, content: info });

            //Googlemap.iw.setContent(info);
            //Googlemap.iw.open(Googlemap.m, mr);
        });
    },

    preload: function (lat, lng, img, info) {

        Googlemap.lats.push(lat);
        Googlemap.lngs.push(lng);
        Googlemap.info.push(info);
        Googlemap.imgs.push(img);
        Googlemap.j++;

        var preimg = new Image();
        preimg.src = Googlemap.imagePath(img);
    }
};


$.fn.values = function (data) {
    var els = $(this).find(':input').get();
    
    if (typeof data != 'object') {
        // return all data
        data = {};

        $.each(els, function () {
            if (this.name && !this.disabled && (this.checked
                                                        || /select|textarea/i.test(this.nodeName)
                                                        || /text|hidden|password/i.test(this.type))) {
                //console.log($(this).val());
                data[this.name] = $(this).val();
            }
        });
        return data;
    } else {
        $.each(els, function () {
            if (this.name && data[this.name]) {
                if (this.type == 'checkbox') {
                    this.checked = (data[this.name] == $(this).val());
                } else {
                    
                    $(this).val(data[this.name]);
                }
            }
        });
        return $(this);
    }
};

var Utilities = {
    parseUrl: function (url) {
        var queryString = new Array();
        var pairs = url.split("&");
        var result = new Object();
        for (i in pairs) {
            var keyval = pairs[i].split("=");
            result[keyval[0]] = keyval[1];
        }
        return result;
    },

    clearForm: function (formid) {
        var form = $('#' + formid);
        $(":input").not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
    }
};

//lucy version 12
(function (e) { e.fn.lucy = function (g) { var b, a, c, h = { mover: function (c, d) { var e = 0 - parseInt(a.carousel.css("margin-left")); a.carousel.eq(0).animate({ marginLeft: c }, b.animtime, b.easing, function () { if (b.displayed == 1 && (e /= b.width + b.margin, a.items.eq(e).find("iframe").length)) { var c = a.items.eq(e).html(); a.items.eq(e).empty().html(c) } c = 0 - parseInt(a.carousel.css("margin-left")) / (b.width + b.margin) + 1; if (a.loner && b.scrollbar) { var f = (0 - parseInt(a.carousel.css("margin-left")) / a.carousel.width()) * a.scrollmarker.parent().width(); b.scrollbarsnap ? a.scrollmarker.css({ marginLeft: f }) : a.scrollmarker.animate({ marginLeft: f }, "fast") } else a.loner && b.numbar && (a.numbar.find(".active").removeClass("active"), a.numbar.find("a[rel=" + c + "]").addClass("active")); typeof d == "function" && d(); typeof b.afterAnimation == "function" && b.afterAnimation(c) }) }, reset: function () { d.stop(); b.autoscroll ? h.mover(0, d.go()) : h.mover(0) } }, d = { init: function (f) { b = e.extend({}, { displayed: 1, width: 300, height: 200, margin: 10, left: ".left", right: ".right", autoscroll: !1, easing: "swing", speed: 1E3, animtime: "fast", scrollbar: !1, scrollbarelem: ".scrollbar", scrollbarheight: 0, scrollbarwidth: 200, scrollbarsnap: !1, numbar: !1, numbarelem: ".numbers", afterAnimation: null, freezeOnBlur: !0 }, f); a = { timer: null }; a.div = c; a.carousel = c.find(".view > ul"); a.items = a.carousel.children(); a.count = a.items.length; a.items.width(b.width).height(b.height).css({ marginRight: b.margin }); a.carousel.width(a.count * (b.width + b.margin)); c.find(".view").width(b.displayed * (b.width + b.margin) - b.margin).height(b.height); a.loner = a.items.length > 1 ? !0 : !1; if (a.loner && b.scrollbar) { a.scrollbar = c.find(b.scrollbarelem); a.scrollbar.height(b.scrollbarheight).width(b.scrollbarwidth); a.scrollbar.append('<div class="scrollmarker"></div>'); for (i = 1; i <= a.count; i++) a.scrollbar.append(function () { return '<a href="#" rel="' + i + '"></a>' }); a.scrollmarker = c.find(".scrollmarker"); a.scrollmarker.width(e(c).find(".view").width() / a.carousel.width() * a.scrollbar.width()).height(b.scrollbarheight); a.scrollbar.find("a").width(1 / a.count * a.scrollbar.width()).css({ position: "relative", top: 0 - b.scrollbarheight }).each(function () { e(this).click(function (a) { a.preventDefault(); d.moveTo(e(this).attr("rel")) }) }) } else if (a.loner && b.numbar) { a.numbar = c.find(b.numbarelem); f = "<ul>"; for (i = 1; i <= a.count; i++) f = f + '<li><a href="#" rel="' + i + '">' + i + "</a></li>"; a.numbar.html(f + "</ul>"); a.numbar.find("a").click(function (a) { a.preventDefault(); d.moveTo(e(this).attr("rel")) }); a.numbar.find("li:first-child a").addClass("active") } c.find(b.left).click(function (b) { b.preventDefault(); a.carousel.is(":animated") || d.moveLeft() }); c.find(b.right).click(function (b) { b.preventDefault(); a.carousel.is(":animated") || d.moveRight() }); b.autoscroll && (d.go(), e(c).hover(function () { d.stop() }, function () { d.go() }), b.freezeOnBlur && (e(window).bind("blur", function () { d.stop() }), e(window).bind("focus", function () { d.go() }))) }, go: function () { if (a.timer == null) a.timer = setInterval(function () { d.moveLeft() }, b.speed) }, moveLeft: function () { parseInt(a.carousel.css("margin-left")) - b.displayed * b.margin + parseInt(a.carousel.width()) <= b.displayed * b.width ? h.reset() : h.mover("-=" + (b.width + b.margin)) }, moveRight: function () { var c = "+=" + (b.width + b.margin); parseInt(a.carousel.css("margin-left")) >= 0 && (c = "-=" + (a.count - b.displayed) * (b.width + b.margin)); h.mover(c) }, moveTo: function (c) { var d = a.count - b.displayed; c > d ? c = d : c--; h.mover(0 - c * (b.width + b.margin)) }, stop: function () { clearInterval(a.timer); a.timer = null } }; return this.each(function () { c = e(this); d[g] ? (b = c.data("settings"), a = c.data("constants"), d[g](Array.prototype.slice.call(arguments, 1))) : typeof g === "object" || !g ? (b = {}, a = {}, d.init(g)) : e.error("Method " + g + " does not exist fool!"); c.data("settings", b); c.data("constants", a) }) } })(jQuery);


//jquery columnize plugin - http://plugins.jquery.com/project/columnize
(function () {
    var cloneEls = new Object(); var numColsById = new Object(); var uniqueId = 0; function _layoutElement(elDOM, settings, balance) {
        var colHeight; var colWidth; var col; var currentColEl; var cols = new Array(); var colNum = 0; var colSet = 0; var el = jQuery(elDOM); numColsById[elDOM.id] = settings.columns; el.empty(); function _newColumn() {
            colNum++; col = document.createElement("DIV"); col.className = settings.column; el.append(col); currentColEl = col; colWidth = jQuery(col).width(); cols.push(col); for (var j = 0; j < subnodes.length; j++) {
                newEl = subnodes[j].cloneNode(false); if (j == 0 || innerContinued) { jQuery(newEl).addClass(settings.continued); }
                currentColEl.appendChild(newEl); currentColEl = newEl;
            }
        }
        function _getMarginBottom(currentColEl) {
            var marginBottom = parseInt(jQuery(currentColEl).css("marginBottom")); if (marginBottom.toString() == 'NaN') { marginBottom = 0; }
            var currentColElParents = jQuery(currentColEl).parents(); for (var j = 0; j < currentColElParents.length; j++) {
                if (currentColElParents[j] == elDOM) { break; }
                var curMarginBottom = parseInt(jQuery(currentColElParents[j]).css("marginBottom")); if (curMarginBottom.toString() != 'NaN') { marginBottom = Math.max(marginBottom, curMarginBottom); }
            }
            return marginBottom;
        }
        function _skipToNextNode() {
            while (currentEl && currentColEl && !currentEl.nextSibling) { currentEl = currentEl.parentNode; currentColEl = currentColEl.parentNode; var node = subnodes.pop(); if (node == "A") { href = null; } }
            if (currentEl) { currentEl = currentEl.nextSibling; }
        }
        var maxHeight = settings.height ? settings.height : parseInt(el.css("maxHeight")); if (balance || isNaN(maxHeight) || maxHeight == 0) {
            col = document.createElement("DIV"); col.className = settings.column; jQuery(col).append(jQuery(cloneEls[elDOM.id]).html()); el.append(col); var lineHeight = parseInt(el.css("lineHeight")); if (!lineHeight) { lineHeight = Math.ceil(parseInt(el.css("fontSize")) * 1.2); }
            colHeight = Math.ceil(jQuery(col).height() / settings.columns); if (colHeight % lineHeight > 0) { colHeight += lineHeight; }
            elDOM.removeChild(col); if (maxHeight > 0 && colHeight > maxHeight) { colHeight = maxHeight; }
        } else { colHeight = maxHeight; }
        var minHeight = settings.minHeight ? settings.minHeight : parseInt(el.css("minHeight")); if (minHeight) { colHeight = Math.max(colHeight, minHeight); }
        var currentEl = cloneEls[elDOM.id].children(":first")[0]; var subnodes = new Array(); var href = null; var lastNodeType = 0; _newColumn(); if (colHeight == 0 || colWidth == 0) { return false; }
        while (currentEl) {
            if (currentEl.nodeType == 1) {
                var newEl; var $currentEl = jQuery(currentEl); if ($currentEl.hasClass("dontSplit") || $currentEl.is(settings.dontsplit)) {
                    var newEl = currentEl.cloneNode(true); currentColEl.appendChild(newEl); if (col.offsetHeight > colHeight) { _newColumn(); }
                    _skipToNextNode();
                } else {
                    var newEl = currentEl.cloneNode(false); currentColEl.appendChild(newEl); if (col.offsetHeight - _getMarginBottom(currentColEl) > colHeight) { currentColEl.removeChild(newEl); var toBeInsertedEl = newEl; _newColumn(); currentColEl.appendChild(toBeInsertedEl); newEl = toBeInsertedEl; }
                    if (currentEl.firstChild) { subnodes.push(currentEl.cloneNode(false)); currentColEl = newEl; currentEl = currentEl.firstChild; } else { _skipToNextNode(); }
                }
                lastNodeType = 1;
            } else if (currentEl.nodeType == 3) {
                var newEl = document.createTextNode(""); currentColEl.appendChild(newEl); var marginBottom = _getMarginBottom(currentColEl); var words = currentEl.data.split(" "); for (var i = 0; i < words.length; i++) {
                    if (lastNodeType == 3) { newEl.appendData(" "); }
                    newEl.appendData(words[i]); currentColEl.removeChild(newEl); currentColEl.appendChild(newEl); if (col.offsetHeight - marginBottom > colHeight) {
                        newEl.data = newEl.data.substr(0, newEl.data.length - words[i].length - 1); var innerContinued; if (jQuery(currentColEl).text() == "") { jQuery(currentColEl).remove(); innerContinued = false; } else { innerContinued = true; }
                        _newColumn(); newEl = document.createTextNode(words[i]); currentColEl.appendChild(newEl);
                    }
                    lastNodeType = 3;
                }
                _skipToNextNode(); lastNodeType = 0;
            } else { _skipToNextNode(); lastNodeType = currentEl.nodeType; }
        }
        return cols;
    }; jQuery.fn.columnize = function (settings) {
        settings = jQuery.extend({ column: "column", continued: "continued", columns: 2, balance: true, height: false, minHeight: false, cache: true, dontsplit: "" }, settings); this.each(function () {
            var jthis = jQuery(this); var id = this.id; if (!id) { id = "jcols_" + uniqueId; this.id = id; uniqueId++; }
            if (!cloneEls[this.id] || !settings.cache) { cloneEls[this.id] = jthis.clone(true); }
            var cols = _layoutElement(this, settings, settings.balance); if (!cols) { jthis.append(cloneEls[this.id].children().clone(true)); }
        }); return this;
    }
})();

//jquery easing plugin - http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend(jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c * (t /= d) * t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c * (t /= d) * t * t + b; }, easeOutCubic: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c * (t /= d) * t * t * t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, easeOutQuint: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t = t / d - 1) * t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
}, easeOutElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
}, easeInOutElastic: function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5); if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a); if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
}, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b; }
});

//date extensions for datepicker (hacked by wp)
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; Date.firstDayOfWeek = 1; Date.format = 'dd/mm/yyyy'; Date.fullYearStart = '20'; (function () {
    function add(name, method) { if (!Date.prototype[name]) { Date.prototype[name] = method; } }; add("isLeapYear", function () { var y = this.getFullYear(); return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }); add("isWeekend", function () { return this.getDay() == 0 || this.getDay() == 6; }); add("isWeekDay", function () { return !this.isWeekend(); }); add("getDaysInMonth", function () { return [31, (this.isLeapYear() ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][this.getMonth()]; }); add("getDayName", function (abbreviated) { return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()]; }); add("getMonthName", function (abbreviated) { return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()]; }); add("getDayOfYear", function () { var tmpdtm = new Date("1/1/" + this.getFullYear()); return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000); }); add("getWeekOfYear", function () { return Math.ceil(this.getDayOfYear() / 7); }); add("setDayOfYear", function (day) { this.setMonth(0); this.setDate(day); return this; }); add("addYears", function (num) { this.setFullYear(this.getFullYear() + num); return this; }); add("addMonths", function (num) {
        var tmpdtm = this.getDate(); this.setMonth(this.getMonth() + num); if (tmpdtm > this.getDate())
            this.addDays(-this.getDate()); return this;
    }); add("addDays", function (num) { this.setTime(this.getTime() + (num * 86400000)); return this; }); add("addHours", function (num) { this.setHours(this.getHours() + num); return this; }); add("addMinutes", function (num) { this.setMinutes(this.getMinutes() + num); return this; }); add("addSeconds", function (num) { this.setSeconds(this.getSeconds() + num); return this; }); add("zeroTime", function () { this.setMilliseconds(0); this.setSeconds(0); this.setMinutes(0); this.setHours(0); return this; }); add("asString", function (format) { var r = format || Date.format; return r.split('yyyy').join(this.getFullYear()).split('yy').join((this.getFullYear() + '').substring(2)).split('mmmm').join(this.getMonthName(false)).split('mmm').join(this.getMonthName(true)).split('mm').join(_zeroPad(this.getMonth() + 1)).split('dd').join(_zeroPad(this.getDate())).split('hh').join(_zeroPad(this.getHours())).split('min').join(_zeroPad(this.getMinutes())).split('ss').join(_zeroPad(this.getSeconds())); }); Date.fromString = function (s, format) {
        var f = format || Date.format; var d = new Date('01/01/1977'); var mLength = 0; var iM = f.indexOf('mmmm'); if (iM > -1) {
            for (var i = 0; i < Date.monthNames.length; i++) { var mStr = s.substr(iM, Date.monthNames[i].length); if (Date.monthNames[i] == mStr) { mLength = Date.monthNames[i].length - 4; break; } }
            d.setMonth(i);
        } else { iM = f.indexOf('mmm'); if (iM > -1) { var mStr = s.substr(iM, 3); for (var i = 0; i < Date.abbrMonthNames.length; i++) { if (Date.abbrMonthNames[i] == mStr) break; } d.setMonth(i); } else { d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1); } } var iY = f.indexOf('yyyy'); if (iY > -1) { if (iM < iY) { iY += mLength; } d.setFullYear(Number(s.substr(iY, 4))); } else { if (iM < iY) { iY += mLength; } d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2))); } var iD = f.indexOf('dd'); if (iM < iD) { iD += mLength; } d.setDate(Number(s.substr(iD, 2))); if (isNaN(d.getTime())) { return false; } return d;
    }; var _zeroPad = function (num) { var s = '0' + num; return s.substring(s.length - 2) };
})();
//datepicker plugin - http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/ (hacked by wp)
(function ($) {
    $.fn.extend({ renderCalendar: function (s) {
        var dc = function (a) { return document.createElement(a); }; s = $.extend({}, $.fn.datePicker.defaults, s); if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) { var headRow = $(dc('tr')); for (var i = Date.firstDayOfWeek; i < Date.firstDayOfWeek + 7; i++) { var weekday = i % 7; var day = Date.dayNames[weekday]; headRow.append(jQuery(dc('th')).attr({ 'scope': 'col', 'abbr': day, 'title': day, 'class': (weekday == 0 || weekday == 6 ? 'weekend' : 'weekday') }).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)); } }; var calendarTable = $(dc('table')).addClass('jCalendar').append((s.showHeader != $.dpConst.SHOW_HEADER_NONE ? $(dc('thead')).append(headRow) : dc('thead'))); var tbody = $(dc('tbody')); var today = (new Date()).zeroTime(); today.setHours(12); var month = s.month == undefined ? today.getMonth() : s.month; var year = s.year || today.getFullYear(); var currentDate = (new Date(year, month, 1, 12, 0, 0)); var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1; if (firstDayOffset > 1) firstDayOffset -= 7; var weeksToDraw = Math.ceil(((-1 * firstDayOffset + 1) + currentDate.getDaysInMonth()) / 7); currentDate.addDays(firstDayOffset - 1); var doHover = function (firstDayInBounds)
        { return function () { if (s.hoverClass) { var $this = $(this); if (!s.selectWeek) { $this.addClass(s.hoverClass); } else if (firstDayInBounds && !$this.is('.disabled')) { $this.parent().addClass('activeWeekHover'); } } } }; var unHover = function ()
        { if (s.hoverClass) { var $this = $(this); $this.removeClass(s.hoverClass); $this.parent().removeClass('activeWeekHover'); } }; var w = 0; while (w++ < weeksToDraw) {
            var r = jQuery(dc('tr')); var firstDayInBounds = s.dpController ? currentDate > s.dpController.startDate : false; for (var i = 0; i < 7; i++) {
                var thisMonth = currentDate.getMonth() == month; var d = $(dc('td')).text(currentDate.getDate() + '').addClass((thisMonth ? 'current-month ' : 'other-month ') + (currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
(thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')).data('datePickerDate', currentDate.asString()).hover(doHover(firstDayInBounds), unHover); r.append(d); if (s.renderCallback) { s.renderCallback(d, currentDate, month, year); }
                currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() + 1, 12, 0, 0);
            } tbody.append(r);
        } calendarTable.append(tbody); return this.each(function () { $(this).empty().append(calendarTable); });
    }, datePicker: function (s) {
        if (!$.event._dpCache) $.event._dpCache = []; s = $.extend({}, $.fn.datePicker.defaults, s); return this.each(function () {
            var $this = $(this); var alreadyExists = true; if (!this._dpId) { this._dpId = $.event.guid++; $.event._dpCache[this._dpId] = new DatePicker(this); alreadyExists = false; } if (s.inline) { s.createButton = false; s.displayClose = false; s.closeOnSelect = false; $this.empty(); }
            var controller = $.event._dpCache[this._dpId]; controller.init(s); if (!alreadyExists && s.createButton) {
                controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>').bind('click', function ()
                { $this.dpDisplay(this); this.blur(); return false; }); $this.after(controller.button);
            } if (!alreadyExists && $this.is(':text')) {
                $this.bind('dateSelected', function (e, selectedDate, $td) { this.value = selectedDate.asString(); }).bind('change', function ()
                { if (this.value == '') { controller.clearSelected(); } else { var d = Date.fromString(this.value); if (d) { controller.setSelected(d, true, true); } } }); if (s.clickInput) { $this.bind('click', function () { $this.trigger('change'); $this.dpDisplay(); }); }
                var d = Date.fromString(this.value); if (this.value != '' && d) { controller.setSelected(d, true, true); }
            } $this.addClass('dp-applied');
        })
    }, dpSetDisabled: function (s) { return _w.call(this, 'setDisabled', s); }, dpSetStartDate: function (d)
    { return _w.call(this, 'setStartDate', d); }, dpSetEndDate: function (d) { return _w.call(this, 'setEndDate', d); }, dpGetSelected: function () { var c = _getController(this[0]); if (c) { return c.getSelected(); } return null; }, dpSetSelected: function (d, v, m, e)
    { if (v == undefined) v = true; if (m == undefined) m = true; if (e == undefined) e = true; return _w.call(this, 'setSelected', Date.fromString(d), v, m, e); }, dpSetDisplayedMonth: function (m, y) { return _w.call(this, 'setDisplayedMonth', Number(m), Number(y), true); }, dpDisplay: function (e)
    { return _w.call(this, 'display', e); }, dpSetRenderCallback: function (a) { return _w.call(this, 'setRenderCallback', a); }, dpSetPosition: function (v, h) { return _w.call(this, 'setPosition', v, h); }, dpSetOffset: function (v, h) { return _w.call(this, 'setOffset', v, h); }, dpClose: function ()
    { return _w.call(this, '_closeCalendar', false, this[0]); }, dpRerenderCalendar: function () { return _w.call(this, '_rerenderCalendar'); }, _dpDestroy: function () { }
    }); var _w = function (f, a1, a2, a3, a4) { return this.each(function () { var c = _getController(this); if (c) { c[f](a1, a2, a3, a4); } }); }; function DatePicker(ele)
    { this.ele = ele; this.displayedMonth = null; this.displayedYear = null; this.startDate = null; this.endDate = null; this.showYearNavigation = null; this.closeOnSelect = null; this.displayClose = null; this.rememberViewedMonth = null; this.selectMultiple = null; this.numSelectable = null; this.numSelected = null; this.verticalPosition = null; this.horizontalPosition = null; this.verticalOffset = null; this.horizontalOffset = null; this.button = null; this.renderCallback = []; this.selectedDates = {}; this.inline = null; this.context = '#dp-popup'; this.settings = {}; }; $.extend(DatePicker.prototype, { init: function (s)
    { this.setStartDate(s.startDate); this.setEndDate(s.endDate); this.setDisplayedMonth(Number(s.month), Number(s.year)); this.setRenderCallback(s.renderCallback); this.showYearNavigation = s.showYearNavigation; this.closeOnSelect = s.closeOnSelect; this.displayClose = s.displayClose; this.rememberViewedMonth = s.rememberViewedMonth; this.selectMultiple = s.selectMultiple; this.numSelectable = s.selectMultiple ? s.numSelectable : 1; this.numSelected = 0; this.verticalPosition = s.verticalPosition; this.horizontalPosition = s.horizontalPosition; this.hoverClass = s.hoverClass; this.setOffset(s.verticalOffset, s.horizontalOffset); this.inline = s.inline; this.settings = s; if (this.inline) { this.context = this.ele; this.display(); } }, setStartDate: function (d)
    { if (d) { this.startDate = Date.fromString(d); } if (!this.startDate) { this.startDate = (new Date()).zeroTime(); } this.setDisplayedMonth(this.displayedMonth, this.displayedYear); }, setEndDate: function (d) {
        if (d) { this.endDate = Date.fromString(d); }
        if (!this.endDate) { this.endDate = (new Date('12/31/2999')); } if (this.endDate.getTime() < this.startDate.getTime()) { this.endDate = this.startDate; } this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
    }, setPosition: function (v, h)
    { this.verticalPosition = v; this.horizontalPosition = h; }, setOffset: function (v, h) { this.verticalOffset = parseInt(v) || 0; this.horizontalOffset = parseInt(h) || 0; }, setDisabled: function (s) {
        $e = $(this.ele); $e[s ? 'addClass' : 'removeClass']('dp-disabled'); if (this.button) { $but = $(this.button); $but[s ? 'addClass' : 'removeClass']('dp-disabled'); $but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE); }
        if ($e.is(':text')) { $e.attr('disabled', s ? 'disabled' : ''); }
    }, setDisplayedMonth: function (m, y, rerender) {
        if (this.startDate == undefined || this.endDate == undefined) { return; } var s = new Date(this.startDate.getTime()); s.setDate(1); var e = new Date(this.endDate.getTime()); e.setDate(1); var t; if ((!m && !y) || (isNaN(m) && isNaN(y))) { t = new Date().zeroTime(); t.setDate(1); } else if (isNaN(m)) { t = new Date(y, this.displayedMonth, 1); } else if (isNaN(y)) { t = new Date(this.displayedYear, m, 1); } else { t = new Date(y, m, 1) }
        if (t.getTime() < s.getTime()) { t = s; } else if (t.getTime() > e.getTime()) { t = e; } var oldMonth = this.displayedMonth; var oldYear = this.displayedYear; this.displayedMonth = t.getMonth(); this.displayedYear = t.getFullYear(); if (rerender && (this.displayedMonth != oldMonth || this.displayedYear != oldYear))
        { this._rerenderCalendar(); $(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]); }
    }, setSelected: function (d, v, moveToMonth, dispatchEvents) {
        if (d < this.startDate || d.zeroTime() > this.endDate.zeroTime()) { return; }
        var s = this.settings; if (s.selectWeek) { d = d.addDays(-(d.getDay() - Date.firstDayOfWeek + 7) % 7); if (d < this.startDate) { return; } } if (v == this.isSelected(d)) { return; } if (this.selectMultiple == false) { this.clearSelected(); } else if (v && this.numSelected == this.numSelectable) { return; }
        if (moveToMonth && (this.displayedMonth != d.getMonth() || this.displayedYear != d.getFullYear())) { this.setDisplayedMonth(d.getMonth(), d.getFullYear(), true); } this.selectedDates[d.asString()] = v; this.numSelected += v ? 1 : -1; var selectorString = 'td.' + (d.getMonth() == this.displayedMonth ? 'current-month' : 'other-month'); var $td; $(selectorString, this.context).each(function ()
        { if ($(this).data('datePickerDate') == d.asString()) { $td = $(this); if (s.selectWeek) { $td.parent()[v ? 'addClass' : 'removeClass']('selectedWeek'); } $td[v ? 'addClass' : 'removeClass']('selected'); } }); $('td', this.context).not('.selected')[this.selectMultiple && this.numSelected == this.numSelectable ? 'addClass' : 'removeClass']('unselectable'); if (dispatchEvents)
        { var s = this.isSelected(d); $e = $(this.ele); var dClone = Date.fromString(d.asString()); $e.trigger('dateSelected', [dClone, $td, s]); $e.trigger('change'); }
    }, isSelected: function (d) { return this.selectedDates[d.asString()]; }, getSelected: function ()
    { var r = []; for (var s in this.selectedDates) { if (this.selectedDates[s] == true) { r.push(Date.fromString(s)); } } return r; }, clearSelected: function () { this.selectedDates = {}; this.numSelected = 0; $('td.selected', this.context).removeClass('selected').parent().removeClass('selectedWeek'); }, display: function (eleAlignTo) {
        if ($(this.ele).is('.dp-disabled')) return; eleAlignTo = eleAlignTo || this.ele; var c = this; var $ele = $(eleAlignTo); var eleOffset = $ele.offset(); var $createIn; var attrs; var attrsCalendarHolder; var cssRules; if (c.inline) { $createIn = $(this.ele); attrs = { 'id': 'calendar-' + this.ele._dpId, 'class': 'dp-popup dp-popup-inline' }; $('.dp-popup', $createIn).remove(); cssRules = {}; } else {
            $createIn = $('body'); attrs = { 'id': 'dp-popup', 'class': 'dp-popup' }; cssRules = { 'top': eleOffset.top + c.verticalOffset, 'left': eleOffset.left + c.horizontalOffset }; var _checkMouse = function (e)
            { var el = e.target; var cal = $('#dp-popup')[0]; while (true) { if (el == cal) { return true; } else if (el == document) { c._closeCalendar(); return false; } else { el = $(el).parent()[0]; } } }; this._checkMouse = _checkMouse; c._closeCalendar(true); $(document).bind('keydown.datepicker', function (event)
            { if (event.keyCode == 27) { c._closeCalendar(); } });
        } if (!c.rememberViewedMonth) { var selectedDate = this.getSelected()[0]; if (selectedDate) { selectedDate = new Date(selectedDate); this.setDisplayedMonth(selectedDate.getMonth(), selectedDate.getFullYear(), false); } }
        $createIn.append($('<div></div>').attr(attrs).css(cssRules).append($('<div class="dp-nav-prev"></div>').append($('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '"></a>').bind('click', function ()
        { return c._displayNewMonth.call(c, this, -1, 0); })), $('<h5></h5>'), $('<div class="dp-nav-next"></div>').append($('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '"></a>').bind('click', function ()
        { return c._displayNewMonth.call(c, this, 1, 0); })), $('<div class="dp-calendar"></div>')).bgIframe()); var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup'); if (this.displayClose) {
            $pop.append($('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>').bind('click', function ()
            { c._closeCalendar(); return false; }));
        } c._renderCalendar(); $(this.ele).trigger('dpDisplayed', $pop); if (!c.inline) {
            if (this.verticalPosition == $.dpConst.POS_BOTTOM) { $pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset); }
            if (this.horizontalPosition == $.dpConst.POS_RIGHT) { $pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset); } $(document).bind('mousedown.datepicker', this._checkMouse);
        }
    }, setRenderCallback: function (a)
    { if (a == null) return; if (a && typeof (a) == 'function') { a = [a]; } this.renderCallback = this.renderCallback.concat(a); }, cellRender: function ($td, thisDate, month, year) {
        var c = this.dpController; var d = new Date(thisDate.getTime()); $td.bind('click', function () {
            var $this = $(this); if (!$this.is('.disabled')) {
                c.setSelected(d, !$this.is('.selected') || !c.selectMultiple, false, true); if (c.closeOnSelect) {
                    if (c.settings.autoFocusNextInput) {
                        var ele = c.ele; var found = false; $(':input', ele.form).each(function ()
                        { if (found) { $(this).focus(); return false; } if (this == ele) { found = true; } });
                    } else { c.ele.focus(); } c._closeCalendar();
                }
            }
        }); if (c.isSelected(d)) { $td.addClass('selected'); if (c.settings.selectWeek) { $td.parent().addClass('selectedWeek'); } } else if (c.selectMultiple && c.numSelected == c.numSelectable) { $td.addClass('unselectable'); }
    }, _applyRenderCallbacks: function ()
    { var c = this; $('td', this.context).each(function () { for (var i = 0; i < c.renderCallback.length; i++) { $td = $(this); c.renderCallback[i].apply(this, [$td, Date.fromString($td.data('datePickerDate')), c.displayedMonth, c.displayedYear]); } }); return; }, _displayNewMonth: function (ele, m, y)
    { if (!$(ele).is('.disabled')) { this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y, true); } ele.blur(); return false; }, _rerenderCalendar: function () { this._clearCalendar(); this._renderCalendar(); }, _renderCalendar: function () {
        $('h5', this.context).html((new Date(this.displayedYear, this.displayedMonth, 1)).asString($.dpText.HEADER_FORMAT)); $('.dp-calendar', this.context).renderCalendar($.extend({}, this.settings, { month: this.displayedMonth, year: this.displayedYear, renderCallback: this.cellRender, dpController: this, hoverClass: this.hoverClass })); if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
            $('.dp-nav-prev-month', this.context).addClass('disabled'); $('.dp-calendar td.other-month', this.context).each(function ()
            { var $this = $(this); if (Number($this.text()) > 20) { $this.addClass('disabled'); } }); var d = this.startDate.getDate(); $('.dp-calendar td.current-month', this.context).each(function () { var $this = $(this); if (Number($this.text()) < d) { $this.addClass('disabled'); } });
        } else {
            $('.dp-nav-prev-month', this.context).removeClass('disabled'); var d = this.startDate.getDate(); if (d > 20) {
                var st = this.startDate.getTime(); var sd = new Date(st); sd.addMonths(1); if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
                    $('.dp-calendar td.other-month', this.context).each(function ()
                    { var $this = $(this); if (Date.fromString($this.data('datePickerDate')).getTime() < st) { $this.addClass('disabled'); } });
                }
            }
        } if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
            $('.dp-nav-next-month', this.context).addClass('disabled'); $('.dp-calendar td.other-month', this.context).each(function ()
            { var $this = $(this); if (Number($this.text()) < 14) { $this.addClass('disabled'); } }); var d = this.endDate.getDate(); $('.dp-calendar td.current-month', this.context).each(function () { var $this = $(this); if (Number($this.text()) > d) { $this.addClass('disabled'); } });
        } else {
            $('.dp-nav-next-month', this.context).removeClass('disabled'); var d = this.endDate.getDate(); if (d < 13) {
                var ed = new Date(this.endDate.getTime()); ed.addMonths(-1); if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
                    $('.dp-calendar td.other-month', this.context).each(function ()
                    { var $this = $(this); var cellDay = Number($this.text()); if (cellDay < 13 && cellDay > d) { $this.addClass('disabled'); } });
                }
            }
        } this._applyRenderCallbacks();
    }, _closeCalendar: function (programatic, ele) { if (!ele || ele == this.ele) { $(document).unbind('mousedown.datepicker'); $(document).unbind('keydown.datepicker'); this._clearCalendar(); $('#dp-popup a').unbind(); $('#dp-popup').empty().remove(); if (!programatic) { $(this.ele).trigger('dpClosed', [this.getSelected()]); } } }, _clearCalendar: function ()
    { $('.dp-calendar td', this.context).unbind(); $('.dp-calendar', this.context).empty(); }
    }); $.dpConst = { SHOW_HEADER_NONE: 0, SHOW_HEADER_SHORT: 1, SHOW_HEADER_LONG: 2, POS_TOP: 0, POS_BOTTOM: 1, POS_LEFT: 0, POS_RIGHT: 1, DP_INTERNAL_FOCUS: 'dpInternalFocusTrigger' }; $.dpText = { TEXT_PREV_MONTH: 'Previous month', TEXT_NEXT_MONTH: 'Next month', TEXT_CLOSE: 'Close', TEXT_CHOOSE_DATE: 'Choose date', HEADER_FORMAT: 'mmmm yyyy' }; $.dpVersion = '$Id: jquery.datePicker.js 102 2010-09-13 14:00:54Z kelvin.luck $'; $.fn.datePicker.defaults = { month: undefined, year: undefined, showHeader: $.dpConst.SHOW_HEADER_SHORT, startDate: undefined, endDate: undefined, inline: false, renderCallback: null, createButton: true, showYearNavigation: true, closeOnSelect: true, displayClose: false, selectMultiple: false, numSelectable: Number.MAX_VALUE, clickInput: false, rememberViewedMonth: true, selectWeek: false, verticalPosition: $.dpConst.POS_TOP, horizontalPosition: $.dpConst.POS_LEFT, verticalOffset: 0, horizontalOffset: 0, hoverClass: 'dp-hover', autoFocusNextInput: false }; function _getController(ele)
    { if (ele._dpId) return $.event._dpCache[ele._dpId]; return false; }; if ($.fn.bgIframe == undefined) { $.fn.bgIframe = function () { return this; }; }; $(window).bind('unload', function () { var els = $.event._dpCache || []; for (var i in els) { $(els[i].ele)._dpDestroy(); } });
})(jQuery);


/**
 * jQuery.labelify - Display in-textbox hints
 * Stuart Langridge, http://www.kryogenix.org/
 * Released into the public domain
 * Date: 25th June 2008
 * @author Stuart Langridge
 * @version 1.3
 *
 *
 * Basic calling syntax: $("input").labelify();
 * Defaults to taking the in-field label from the field's title attribute
 *
 * You can also pass an options object with the following keys:
 *   text
 *     "title" to get the in-field label from the field's title attribute 
 *      (this is the default)
 *     "label" to get the in-field label from the inner text of the field's label
 *      (note that the label must be attached to the field with for="fieldid")
 *     a function which takes one parameter, the input field, and returns
 *      whatever text it likes
 *
 *   labelledClass
 *     a class that will be applied to the input field when it contains the
 *      label and removed when it contains user input. Defaults to blank.
 *  
 */
jQuery.fn.labelify = function(settings) {
  settings = jQuery.extend({
    text: "title",
    labelledClass: ""
  }, settings);
  var lookups = {
    title: function(input) {
      return $(input).attr("title");
    },
    label: function(input) {
      return $("label[for=" + input.id +"]").text();
    }
  };
  var lookup;
  var jQuery_labellified_elements = $(this);
  return $(this).each(function() {
    if (typeof settings.text === "string") {
      lookup = lookups[settings.text]; // what if not there?
    } else {
      lookup = settings.text; // what if not a fn?
    };
    // bail if lookup isn't a function or if it returns undefined
    if (typeof lookup !== "function") { return; }
    var lookupval = lookup(this);
    if (!lookupval) { return; }

    // need to strip newlines because the browser strips them
    // if you set textbox.value to a string containing them    
    $(this).data("label",lookup(this).replace(/\n/g,''));
    $(this).focus(function() {
      if (this.value === $(this).data("label")) {
        this.value = this.defaultValue;
        $(this).removeClass(settings.labelledClass);
      }
    }).blur(function(){
      if (this.value === this.defaultValue) {
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);
      }
    });
    
    var removeValuesOnExit = function() {
      jQuery_labellified_elements.each(function(){
        if (this.value === $(this).data("label")) {
          this.value = this.defaultValue;
          $(this).removeClass(settings.labelledClass);
        }
      })
    };
    
    $(this).parents("form").submit(removeValuesOnExit);
    $(window).unload(removeValuesOnExit);
    
    if (this.value !== this.defaultValue) {
      // user already started typing; don't overwrite their work!
      return;
    }
    // actually set the value
    this.value = $(this).data("label");
    $(this).addClass(settings.labelledClass);

  });
};

Date.prototype.toUTCArray= function(){
    var D= this;
    return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
    D.getUTCMinutes(), D.getUTCSeconds()];
};

Date.prototype.toISO= function(){
    var tem, A= this.toUTCArray(), i= 0;
    A[1]+= 1;
    while(i++<7){
        tem= A[i];
        if(tem<10) A[i]= '0'+tem;
    }
    return A.splice(0, 3).join('-')+'T'+A.join(':');    
};

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -65;
  this.offsetHorizontal_ = 0;
  this.height_ = 133;
  this.width_ = 242;
  this.content_ = opts.content;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new google.maps.OverlayView();

/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};

/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function() {
  // Creates the element if it doesn't exist already.
  this.createElement();
  if (!this.div_) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our Bar
  var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (!pixPosition) return;

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.height = this.height_ + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  this.div_.style.display = 'block';
};

/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
InfoBox.prototype.createElement = function () {
    var panes = this.getPanes();
    var div = this.div_;
    if (!div) {
        // This does not handle changing panes.  You can set the map to be null and
        // then reset the map to move the div.
        div = this.div_ = document.createElement("div");
        $(div).addClass('map-marker-window');
        var contentDiv = document.createElement("div");
        //contentDiv.style.padding = "30px"
        contentDiv.innerHTML = this.content_;


        var closeImg = document.createElement("a");
        $(closeImg).addClass("mapCloseIcon");
        contentDiv.appendChild(closeImg);

        function removeInfoBox(ib) {
            return function () {
                ib.setMap(null);
            };
        }

        google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));

        //div.appendChild(topDiv);
        div.appendChild(contentDiv);
        div.style.display = 'none';
        panes.floatPane.appendChild(div);
        this.panMap();
    } else if (div.parentNode != panes.floatPane) {
        // The panes have changed.  Move the div.
        div.parentNode.removeChild(div);
        panes.floatPane.appendChild(div);
    } else {
        // The panes have not changed, so no need to create or move the div.
    }
}

/* Pan the map to fit the InfoBox.
 */
InfoBox.prototype.panMap = function() {
  // if we go beyond map, pan map
  var map = this.map_;
  var bounds = map.getBounds();
  if (!bounds) return;

  // The position of the infowindow
  var position = this.latlng_;

  // The dimension of the infowindow
  var iwWidth = this.width_;
  var iwHeight = this.height_;

  // The offset position of the infowindow
  var iwOffsetX = this.offsetHorizontal_;
  var iwOffsetY = this.offsetVertical_;

  // Padding on the infowindow
  var padX = 40;
  var padY = 40;

  // The degrees per pixel
  var mapDiv = map.getDiv();
  var mapWidth = mapDiv.offsetWidth;
  var mapHeight = mapDiv.offsetHeight;
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degPixelX = longSpan / mapWidth;
  var degPixelY = latSpan / mapHeight;

  // The bounds of the map
  var mapWestLng = bounds.getSouthWest().lng();
  var mapEastLng = bounds.getNorthEast().lng();
  var mapNorthLat = bounds.getNorthEast().lat();
  var mapSouthLat = bounds.getSouthWest().lat();

  // The bounds of the infowindow
  var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
  var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
  var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
  var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

  // calculate center shift
  var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
  var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

  // The center of the map
  var center = map.getCenter();

  // The new map center
  var centerX = center.lng() - shiftLng;
  var centerY = center.lat() - shiftLat;

  // center the map to the new shifted center
  map.setCenter(new google.maps.LatLng(centerY, centerX));

  // Remove the listener after panning is complete.
  google.maps.event.removeListener(this.boundsChangedListener_);
  this.boundsChangedListener_ = null;
};

