﻿/// <reference path="sysjs/jquery-1.4.x.min.js"/>
// (C) 2009 Center Dynamics USA, LLC


// call ajax webservice/pagemethod, get back json object
// parms="{'fname':'dave','lname':'ward'}"
function ajaxWebService(URL, parms, onSuccess, onFail) {
    if (parms == '') parms = "{}";
    $.ajax({
        type: "POST", url: URL, data: parms,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(retval) { if (onSuccess) onSuccess(retval);},
        error: function(XHR, context) { if (onFail) onFail();},
        dataFilter: function (data, type) {
        return data; // NOTE - replace doesnt work in JQuery 1.4.2 - it makes JSON invalid .replace(/"\\\/(Date\(-?[0-9-]+\))\\\/"/gi, "new $1"); // fix MS date http://www.overset.com/2008/07/18/simple-jquery-json-aspnet-webservice-datetime-support/
        /// will need to fix the dates (like for events) to work with 1.4.2
        }    
    });
}

// scan sf menu and find matching urls and highlight them
$.fn.sfshowcurrent = function(activeclass) {
    var url = getURL();
    var element = this;
    return this.each(function() {
        $("li a", element).each(function() {
            var A1 = this;
            if (A1.href.toLowerCase() == url) {
                $(A1).parents("li", element).children("a").addClass(activeclass); // mark self and all A parents
            }
        });
    });

};

// find url in menu array
function findURLinMenu(menuAR) {
    var url = getURLPath();
    var matchbranch = [];
    scanfolderforURL(menuAR.SubF, url, matchbranch);
    return matchbranch;
}

function scanfolderforURL(F, url, matchbranch) {
    var matchitem = null;

    $.each(F, function(i, ele) {
        if ('/' + ele.URL.toLowerCase() == url) {
            matchitem = ele;
            return false;
        }
        if (ele.SubF != null) {
            if (scanfolderforURL(ele.SubF, url, matchbranch)) {// child match, add this one
                matchitem = ele;
                return false;
            }
        }
    });

    if (matchitem != null) {
        matchbranch.push(matchitem);
        return true;
    }
    
}

function getURL() {
    return window.location.href.replace('#', '').toLowerCase();
}
function getURLPath() {
    return (window.location.pathname.replace('#', '') + window.location.search).toLowerCase();
}

function TruncateText(text, maxchars, trail) {
    if (text == null) return '';
    if (text.length > maxchars + trail) {
        var splitLocation = text.indexOf(' ', maxchars);
        return text.substring(0, splitLocation) + '...';
    }
    else {
        return text
    }
}


// ****** cd event list '' todo - refactor to use v ticker plugin added at bottom
//(function($) {
$.fn.cdeventlist = function(options) {

    var defaults = {
        area: '',
        location: '',
        center: 0,
        subloc: -1,
        topicCode: 0,
        maxDays: 30,
        
        visibleRows: 2,
        maxRows: 30,
        maxDescChars: 150,
        scrollList: true,
        scrollPauseSec: 5,
        rowPadding: 6
    };
    var options = jQuery.extend(defaults, options || {});

    var element = this;
    var cdelinterval = null;

    return this.each(function() {

        // call web service (bad bots getting into this asmx, so chunking url)
        ajaxWebService("CDService" + "." + "as" + "mx"  + "/" + "EventJSONFeed",
            "{Area:'" + options.area + "',Location:'" + options.location + "',Center:" + options.center + ",SubLoc:" + options.subloc + ",Topic:" + options.topicCode + ",Days:" + options.maxDays + "}",
                function(webret) {// return back from websvc

                    var elistJSON = webret.d;
                    if (elistJSON == null) {// no events
                        $('.cdel_scroller', element).stop().animate({ height: 0 }, 'slow');
                        return false;
                    }

                    var elist = $('.cdel_scroller', element);
                    var jtmp = $('.cdel_event:first', elist).clone(); // template from first row

                    $('.cdel_event', elist).remove();  // remove all rows
                    $("<div class='cdel_event' style='height:100px'>&nbsp;</div>").appendTo(elist); // add an empty row to scroll up

                    $.each(elistJSON, function(i) {
                        var evt = this;
                        UpdateEvent(jtmp, evt);
                        jtmp.appendTo(elist).hide();
                        jtmp = jtmp.clone();
                    });

                    $('.cdel_event:lt(' + options.visibleRows + ')', elist).show(); // show first visible

                    if (options.scrollList && (elistJSON.length > options.visibleRows)) {// rotate if enough events
                        cdelRotate();
                        cdelinterval = setInterval(cdelRotate, options.scrollPauseSec * 1000);
                        elist.hover(// stop scroll on mouseover
                            function() { clearInterval(cdelinterval); },
                            function() { clearInterval(cdelinterval); cdelinterval = setInterval(cdelRotate, options.scrollPauseSec * 1000); }
                        );
                    }

                }, null
            );

    });

    function UpdateEvent(jitem, evt) {
        jitem.find(".cdel_title").html("<b>" + evt.Title + "</b>").attr("href", evt.Link);
        jitem.find(".cdel_shortdesc").text(TruncateText(evt.Description, options.maxDescChars, 20));
        jitem.find(".cdel_month").text(evt.StartMonthName);
        jitem.find(".cdel_day").text(evt.StartDate.getDate());

    }

    function cdelRotate() {
        var jtop = $('.cdel_event:first', element);
        $('.cdel_event:eq(' + options.visibleRows + ')', element).show(); // next row to be shown

        $('.cdel_scroller', element).stop().animate({ top: -jtop.height() - options.rowPadding }, 1500, 'swing', function() {
            $('.cdel_scroller', element)
            jtop.remove().hide(); // .appento didnt work
            $('.cdel_scroller', element).css('top', '0').append(jtop);
            var top2height = 0; // resize container to show visible rows
            $('.cdel_event:lt(' + options.visibleRows + ')', element).each(function() {
                top2height += $(this).height() + options.rowPadding;
            });
            if (top2height > element.height())
                element.stop().animate({ height: top2height }, 'slow');

        });
    }



};
// end ORIGINAL event list plugin

// ****** cd event list  second version
//(function($) {
$.fn.cdeventticker = function(options) {
    var defaults = {
        area: '',
        location: '',
        center: 0,
        subloc: -1,
        topicCode: 0,
        maxDays: 30,
        
        maxRows: 10,
        maxDescChars: 120,
        speed: 1000,
        pause: 4000,
        targetHeight: 300,
        mousePause: true
    };

    var options = jQuery.extend(defaults, options || {});
    var element = this;    

    return this.each(function() {
        if (options.RowArray == null) {
            // call web service (bad bots getting into this asmx, so chunking url)
            ajaxWebService("CDService" + "." + "as" + "mx" + "/" + "EventJSONFeed",
            "{Area:'" + options.area + "',Location:'" + options.location + "',Center:" + options.center + ",SubLoc:" + options.subloc + ",Topic:" + options.topicCode + ",Days:" + options.maxDays + "}",
               function(webret) {
                   options.RowArray = webret.d;
                   renderListRows();
               }, null);
        }
        else {
            renderListRows();
        }

    });

    function renderListRows() { // add li's for each EVENT
        var $ul = element.find('ul');
        if ($ul.length == 0) {
            $ul = element.append('<ul class="cdscrolllist_scroller"></ul>');
        }
        var $templi = $ul.find('li');
        if ($templi.length == 0) {// no template li  - setup our own simple one
            $templi = $('<li class="cdscrolllist_row"><div><a class="cdscrolllist_title"/></div></li>');
        }

        $ul.children().remove();

        $.each(options.RowArray, function(i, evt) {
            var $li = $templi.clone();
            $li.find(".cdscrolllist_title").text(evt.Title).attr("href", evt.Link); // assume is the link
            if ($.trim(evt.Description).length > 0) { $li.find(".cdscrolllist_desc").text(TruncateText(evt.Description, options.maxDescChars, 20)); }
            $li.find(".cdel_month").text(evt.StartMonthName);
            $li.find(".cdel_day").text(evt.StartDate.getDate());
            $li.find(".cdel_Location").text(evt.Location);
            $ul.append($li);
        });

        element.vTicker(options);

    }    
    

};



// FOLDER ticker plugin2 - for showing resources in folder
$.fn.cdfolderticker = function(options) {
    var defaults = {
        FolderNbr: 0,
        RowArray: null,
        OrderBy: 'entrydesc',
        maxRows: 10,
        maxDescChars: 120,
        speed: 1000,
        pause: 4000,
        targetHeight: 300,
        mousePause: true
    };
    var options = jQuery.extend(defaults, options || {});
    var element = this;

    return this.each(function() {
        if (options.RowArray == null) {
            // call web service (bad bots getting into this asmx, so chunking url)
            ajaxWebService("CDService" + "." + "as" + "mx" + "/" + "FolderJSONFeed",
            "{FolderNbr:'" + options.FolderNbr + "',OrderBy:'" + options.OrderBy + "',MaxCount:" + options.maxRows + "}",
               function(webret) {
                   options.RowArray = webret.d;
                   renderListRows();
               }, null);
        }
        else {
            renderListRows();
        }

    });

    function renderListRows() { // add li's for each doc
        var $ul = element.find('ul');
        if ($ul.length == 0) {
            $ul = element.append('<ul class="cdscrolllist_scroller"></ul>');
        }
        var $templi = $ul.find('li');
        if ($templi.length == 0) {// no template li  - setup our own simple one
            $templi = $('<li class="cdscrolllist_row"><div><a class="cdscrolllist_title"/></div></li>');
        }

        $ul.children().remove();

        $.each(options.RowArray, function(i, doc) {
            var $li = $templi.clone();
            $li.find(".cdscrolllist_title").text(doc.Title).attr("href", doc.Link); // assume is the link
            if ($.trim(doc.Description).length > 0) { $li.find(".cdscrolllist_desc").text(TruncateText(doc.Description, options.maxDescChars, 20)); }
            // todo - dates
            $ul.append($li);
        });

        element.vTicker(options);

    }

};

//*** vert ticker http://plugins.jquery.com/project/vTicker
// modified to fixed height, shows just enough rows to fit
(function($) {
    $.fn.vTicker = function(options) {
        var defaults = {
            speed: 700,
            pause: 4000,
            targetHeight: 400,
            showItems: 2,
            mousePause: true,
            isPaused: false
        };

        var options = $.extend(defaults, options);

        moveUp = function(obj2) {
            if (options.isPaused)
                return;
            var obj = obj2.children('ul');
            var $li = obj.children('li:first');
            first = $li.clone(true);
            height = $li.outerHeight(true)

            obj.animate({ top: '-=' + height + 'px' }, options.speed, function() {
                $(this).children('li:first').remove();
                $(this).css('top', '0px');
                sizeContainer(obj.closest('div'));
            });

            first.hide().appendTo(obj);
        };

        sizeContainer = function(obj3) {
            var showH = 0, totH = 0;
            obj3.children('ul').children('li').each(function() {
                var liH = $(this).outerHeight(true)
                if (totH + liH > options.targetHeight) {
                    $(this).hide();
                }
                else {
                    $(this).fadeIn(options.speed);
                }
                totH += liH;
            });

            return totH;
        }

        return this.each(function() {
            var obj = $(this);
            obj.height(options.targetHeight);

            obj.css({ overflow: 'hidden', position: 'relative' })
			.children('ul').css({ position: 'absolute', margin: 0 }); //, padding: 0

            if (sizeContainer(obj) < options.targetHeight) { return; }; // not enough to scroll
            var interval = setInterval(function() { moveUp(obj); }, options.pause);

            if (options.mousePause) {
                obj.bind("mouseenter", function() {
                    options.isPaused = true;
                }).bind("mouseleave", function() {
                    options.isPaused = false;
                });
            }
        });
    };
})(jQuery);



