﻿jQueryCS.noConflict();

(function($) {

    var BlogService = function(portalId, tabId) {
        this._portalId = portalId;
        this._tabId = tabId;
    };

    BlogService.prototype.test = function() {
        CodingStaff.Modules.Blog.BlogService.HelloWorld(function(res) { alert(res); });
    };

    BlogService.prototype.getTemplateModules = function(templateId, pane, success) {
        CodingStaff.Modules.Blog.BlogService.GetTemplateModules(this._portalId, this._tabId, templateId, pane, success);
    };

    BlogService.prototype.getExternalModules = function(rootId, templateId, success) {
        CodingStaff.Modules.Blog.BlogService.GetExternalModules(this._portalId, this._tabId, rootId, templateId, success);
    };

    BlogService.prototype.insertExternalModule = function(templateId, moduleId, paneName, paneOrder, success) {
        CodingStaff.Modules.Blog.BlogService.InsertExternalModule(this._portalId, this._tabId, templateId, moduleId, paneName, paneOrder, success);
    };

    BlogService.prototype.insertTemplateModule = function(moduleId, paneName, paneOrder, success) {
        CodingStaff.Modules.Blog.BlogService.InsertTemplateModule(this._portalId, this._tabId, moduleId, paneName, paneOrder, success);
    };

    BlogService.prototype.deleteTemplateModule = function(moduleId, success) {
        CodingStaff.Modules.Blog.BlogService.DeleteTemplateModule(this._portalId, this._tabId, moduleId, success);
    };

    BlogService.prototype.updateModuleTitle = function(moduleId, title, success) {
        CodingStaff.Modules.Blog.BlogService.UpdateModuleTitle(this._portalId, this._tabId, moduleId, title, success);
    };

    BlogService.prototype.getPosts = function(rootId, blogId, pageN, pageS, year, month, day, tag, cat, success) {
        CodingStaff.Modules.Blog.BlogService.GetPosts(this._portalId, this._tabId, rootId, blogId, pageN, pageS, year, month, day, tag, cat, success);
    };

    BlogService.prototype.getPostDates = function(rootId, blogId, tTagId, success) {
        CodingStaff.Modules.Blog.BlogService.GetPostDates(this._portalId, this._tabId, rootId, blogId, tTagId, success);
    };

    BlogService.prototype.getCategories = function(blogId, parentId, success) {
        CodingStaff.Modules.Blog.BlogService.GetCategories(this._portalId, this._tabId, blogId, parentId, success);
    };
    BlogService.prototype.addCategory = function(blogId, catName, parentId, success) {
        CodingStaff.Modules.Blog.BlogService.AddCategory(this._portalId, this._tabId, blogId, catName, parentId, success);
    };

    BlogService.prototype.validateAddCategory = function(blogId, catName, parentId, success) {
        CodingStaff.Modules.Blog.BlogService.ValidateAddCategory(this._portalId, this._tabId, blogId, catName, parentId, success);
    };

    BlogService.prototype.deleteCategory = function(catId, success) {
        CodingStaff.Modules.Blog.BlogService.DeleteCategory(this._portalId, this._tabId, catId, success);
    };

    BlogService.prototype.updateCategory = function(blogId, catId, order, parentId, success) {
        CodingStaff.Modules.Blog.BlogService.UpdateCategory(this._portalId, this._tabId, blogId, catId, order, parentId, success);
    };

    $.blogService = undefined;

    $.cs_panes = new Array();
    $.cs_externalPane = undefined;

    $.initBlogService = function(portalId, tabId) {
        $.blogService = new BlogService(portalId, tabId);
    };

    $.fn.blogHover = function() {
        if (this.length == 0) return;
        var elem = $.data(this[0], 'holder');

        $(elem).width($(this).innerWidth());
        $(elem).height($(this).innerHeight());
        $(elem).css('position', 'absolute');
        $(elem).css('left', $(this).position().left + 'px');
        $(elem).css('top', $(this).position().top + 'px');
        $(elem).show();
    };

    $.getTargetPane = function(item) {
        while (!item.attr('paneName')) {
            item = item.parent();
        }
        return item.attr('paneName');
    };

    $.fn.templateModules = function() {
        var pane = $.data(this[0], 'paneName');

        this.find('.cs_template_module').each(function() {
            var id = $(this).attr('templateModuleId');

            var sc_delete = $(this).find('.cs_module_delete');
            var sc_delete_approve = $(this).find('.cs_module_delete_approve');

            sc_delete_approve.hide();

            $(this).find('.mc_module_delete').click(function() {
                sc_delete.hide();
                sc_delete_approve.show();
                return false;
            });

            $(this).find('.mc_module_delete_canel').click(function() {
                sc_delete.show();
                sc_delete_approve.hide();
                return false;
            });

            $(this).find('.mc_module_delete_yes').click(function() {
                $($.cs_externalPane).blogHover();
                $($.cs_panes[pane]).blogHover();

                $.blogService.deleteTemplateModule(id, function() {
                    $($.cs_externalPane).externalLoad();
                    $($.cs_panes[pane]).templateLoad();
                });
                return false;
            });

            var sc_edit = $(this).find('.cs_module_tile_edit');
            var sc_edit_approve = $(this).find('.cs_module_title_edit_approve');

            var label = $(this).find('.m_title');
            var edit = $(this).find('.m_title_edit');

            sc_edit_approve.hide();
            edit.hide();

            $(this).find('.mc_title_edit').click(function() {
                edit.val(label.text());
                label.hide();
                edit.show();
                edit.focus();

                sc_edit.hide();
                sc_edit_approve.show();
                return false;
            });

            $(this).find('.mc_title_update').click(function() {

                //alert(label.text());

                $.blogService.updateModuleTitle(id, edit.val(), function() {
                    label.text(edit.val());
                    label.show();
                    edit.hide();

                    sc_edit.show();
                    sc_edit_approve.hide();
                });

                return false;
            });

            $(this).find('.mc_title_cancel').click(function() {

                label.show();
                edit.hide();

                sc_edit.show();
                sc_edit_approve.hide();
                return false;
            });
        });
    };

    $.fn.templateLoad = function(temlpateId) {
        this.each(function() {
            var paneName = $.data(this, 'paneName');
            var templateId = $.data(this, 'templateId');
            var holder = $.data(this, 'holder');
            var panel = $(this);
            //panel.blogHover(holder);

            $.blogService.getTemplateModules(templateId, paneName, function(res) {
                holder.hide();
                panel.processTemplate(res);
                panel.templateModules();
            });
        });
    };

    $.fn.templatePane = function(temlpateId, locals) {
        this.each(function() {
            $.data(this, 'paneName', $(this).attr('paneName'));
            $.data(this, 'templateId', temlpateId);

            var holder = $('#h_' + $(this).attr('paneName'));
            holder.hide();
            $.data(this, 'holder', holder);
            $.cs_panes[$(this).attr('paneName')] = this;

            $(this).setTemplateElement('t_templateModules');
            $(this).setParam('locals', locals);
            $(this).sortable({
                cursor: 'move'
                , connectWith: '.cs_template_pane'
                //, tolerance: 'pointer'
                //, scrollSensitivity: 40
                , forcePlaceholderSize: true
                , forceHelperSize: true
                , stop: function(event, ui) {
                    var toPane = $.getTargetPane(ui.item);
                    var fromPane = ui.item.attr('pane');
                    var tId = ui.item.attr('templateModuleId');
                    var eId = ui.item.attr('externalModuleId');
                    var order = ui.item.prev().attr('order') || -1;
                    order++;

                    //alert(order);

                    if (tId) {
                        $($.cs_panes[toPane]).blogHover();
                        $($.cs_panes[fromPane]).blogHover();
                        $.blogService.insertTemplateModule(tId, toPane, order, function() {
                            $($.cs_panes[toPane]).templateLoad();
                            $($.cs_panes[fromPane]).templateLoad();
                        });
                    }

                    if (eId) {
                        $($.cs_externalPane).blogHover();
                        $($.cs_panes[toPane]).blogHover();
                        $.blogService.insertExternalModule(temlpateId, eId, toPane, order, function() {
                            $($.cs_externalPane).externalLoad();
                            $($.cs_panes[toPane]).templateLoad();
                        });
                    }
                }
            });

        });
        this.templateLoad();
    };

    $.fn.externalLoad = function() {
        this.each(function() {
            var rootId = $.data(this, 'rootId');
            var templateId = $.data(this, 'templateId');
            var holder = $.data(this, 'holder');

            var panel = $(this);
            //panel.blogHover(holder);
            $.blogService.getExternalModules(rootId, templateId, function(res) {
                holder.hide();
                panel.processTemplate(res);
                panel.find('.cs_external_module').draggable({
                    helper: 'clone'
                    , connectToSortable: '.cs_template_pane'
                });

            });
        });
    };

    $.fn.externalPane = function(templateId, rootId) {
        this.each(function() {
            $.cs_externalPane = this;
            $.data(this, 'rootId', rootId);
            $.data(this, 'templateId', templateId);

            var holder = $('#h_Externals');
            holder.hide();
            $.data(this, 'holder', holder);

            $(this).setTemplateElement('t_externalModules');
        });
        this.externalLoad();
    };

    $.fn.externalModules = function() {
        this.each(function() {
            $(this).find('.cs_blog_externalitem').each(function() {
                var deleteSec = $(this).find('.module_delete');
                var deleteApproveSec = $(this).find('.module_delete_approve');

                deleteSec.show();
                deleteApproveSec.hide();

                $(this).find('.cmd_delete').click(function() {
                    deleteSec.hide();
                    deleteApproveSec.show();
                    return false;
                });

                $(this).find('.cmd_delete_cancel').click(function() {
                    deleteSec.show();
                    deleteApproveSec.hide();
                    return false;
                });


            });
        });
    };

    $.fn.blogManager = function() {
        this.each(function() {
            var add = $(this).find('.cmd_manager_add');
            var addInfo = $(this).find('.blogNameTextbox');

            addInfo.hide();

            add.click(function() {
                addInfo.toggle(200);
                return false;
            });

            var _del = $(this).find('.blog_delete');
            var _del_confirm = $(this).find('.blog_delete_confirm');

            _del.show();
            _del_confirm.hide();

            _del.find('.Delete').click(function() {
                // _del.hide();
                _del_confirm.show();
                return false;
            });

            _del_confirm.find('.cmd_cancel').click(function() {
                _del.show();
                _del_confirm.hide();
                return false;
            });
        });
    };

    $.fn.postManager = function() {
        this.each(function() {
            var _del = $(this).find('.post_delete');
            var _del_confirm = $(this).find('.post_delete_confirm');

            _del.show();
            _del_confirm.hide();

            _del.find('.Delete').click(function() {
                // _del.hide();
                _del_confirm.show();
                return false;
            });

            _del_confirm.find('.cmd_cancel').click(function() {
                _del.show();
                _del_confirm.hide();
                return false;
            });
        });
    };

    PostsLoader = function(rootId, blogId, pageS) {
        this._blogId = blogId;
        this._rootId = rootId;
        this._pageS = pageS;

        this._year = null;
        this._month = null;
        this._day = null;
        this._cat = null;
        this._tag = null;

        this._pageN = 1;
        this._locals = {};
    };

    PostsLoader.prototype.innerGetPosts = function(pageN, callback) {
        $.blogService.getPosts(this._rootId, this._blogId, this._pageN, this._pageS, this._year
        , this._month, this._day, this._tag, this._cat, callback);
    };

    PostsLoader.prototype.gotoPage = function(pageN, callback) {
        this._pageN = pageN || this._pageN;
        this.innerGetPosts(this._pageN, callback);
    };

    PostsLoader.prototype.prevPage = function(callback) {
        if (this._pageN > 1) this._pageN--;
        this.innerGetPosts(this._pageN, callback);
    };

    PostsLoader.prototype.nextPage = function(callback) {
        this._pageN++;
        this.innerGetPosts(this._pageN, callback);
    };

    PostsLoader.prototype.getPosts = function(year, month, day, tag, cat, pageN, callback) {
        this._year = year;
        this._month = month;
        this._day = day;
        this._cat = cat;
        this._tag = tag;

        this._pageN = pageN || this._pageN;

        this.innerGetPosts(this._pageN, callback);

    };


    $.fn.blogPosts = function(rootId, blogId, pageS, locals) {

        return this.each(function() {
            var loader = new PostsLoader(rootId, blogId, pageS);
            loader._locals = locals;
            $.data(this, 'cs_postLoader', loader);

            $(this).find('.blog_posts').setTemplateElement('cs_t_posts', null, { filter_data: false, f_escapeString: false });
            $(this).find('.posts_pages').setTemplateElement('cs_t_posts_pages', null, { filter_data: false, f_escapeString: false });

        });
    };

    $.fn.bindPosts = function() {
        return this.each(function() {
            var loader = $.data(this, 'cs_postLoader');
            var holder = $(this);

            holder.find('.posts_pages .prevPage a').click(function() {

                loader.prevPage(function(posts) {
                    holder.renderPosts(posts);
                });
                return false;
            });

            holder.find('.posts_pages .nextPage a').click(function() {

                loader.nextPage(function(posts) {
                    holder.renderPosts(posts);
                });
                return false;
            });

            holder.find('.posts_pages .pageLink a').click(function() {
                loader.gotoPage($(this).attr('pageN'), function(posts) {
                    holder.renderPosts(posts);
                });
                return false;
            });

            holder.find('.cs_blog_postitem .postTags a').click(function() {
                loader.getPosts(null, null, null, $(this).attr('tag'), null, 1, function(posts) {
                    holder.renderPosts(posts);
                });
                return false;
            });

            holder.find('.cs_blog_postitem .postCategories a').click(function() {
                loader.getPosts(null, null, null, null, $(this).attr('cat'), 1, function(posts) {
                    holder.renderPosts(posts);
                });
                return false;
            });
        });
    };

    $.fn.renderPosts = function(posts) {
        return this.each(function() {
            var loader = $.data(this, 'cs_postLoader');
            var holder = $(this);

            holder.find('.blog_posts').setParam('locals', loader._locals);
            holder.find('.blog_posts').processTemplate(posts);
            holder.find('.posts_pages').setParam('page', loader._pageN);
            holder.find('.posts_pages').setParam('locals', loader._locals);
            holder.find('.posts_pages').processTemplate(posts.Pages);

            holder.bindPosts();

        });
    };

    $.fn.loadPosts = function(year, month, day, tag, cat, pageN) {
        var handled = false;
        this.each(function() {
            var loader = $.data(this, 'cs_postLoader');
            var holder = $(this);
            loader.getPosts(year, month, day, tag, cat, pageN, function(posts) {
                holder.renderPosts(posts);
            });
            handled = true;
        });
        return handled;
    };

    $.fn.blogTags = function(blogPosts) {
        return this.each(function() {
            $(this).find('.cs_tag_link').click(function() {
                var handled = $(blogPosts).loadPosts(null, null, null, $(this).attr('tag'), null, 1);
                return !handled;
            });
        });
    };

    $.findDate = function(dates, y, m, d) {
        var item = null;

        $(dates.Years).each(function() {
            if (this.Year == y) {
                $(this.Months).each(function() {
                    if (this.MonthN == (m + 1)) {
                        $(this.ActiveDays).each(function() {
                            if (this.DayN == d) {
                                item = this;
                                return;
                            }
                        });
                    }
                    if (item) return;
                });
            }
            if (item) return;
        });

        return item;
    };

    $.fn.blogArchive = function(rootId, blogId, tTabId, year, month, day, showM, showY, expandY) {
        return this.each(function() {
            var holder = $(this);

            holder.find('.archive_years').setTemplateElement('cs_t_archive');
            $.blogService.getPostDates(rootId, blogId, tTabId, function(res) {
                var dates = res;
                $.data(this, 'cs_post_dates', dates);
                holder.find('.archive_years').processTemplate(dates);

                holder.find('.month a').click(function() {
                    var handled = $('.cs_blog_posts').loadPosts($(this).attr('year'), $(this).attr('month'), null, null, null, 1);

                    var y = $(this).attr('year');
                    var m = $(this).attr('month');

                    var current = dates.CurrentDate;

                    var cY = current.getFullYear();
                    var cM = current.getMonth() + 1;

                    holder.find('.datepicker_placeholder').datepicker('setDate',
                        (y - cY) + 'y' + ' ' + (m - cM) + 'm');

                    return !handled;
                });

                if (showM) {

                    holder.find('.datepicker_placeholder').datepicker({
                        minDate: dates.MinDate,
                        maxDate: dates.CurrentDate,
                        defaultDate: dates.CurrentDate,
                        beforeShowDay: function(date) {
                            var y = date.getFullYear();
                            var m = date.getMonth();
                            var d = date.getDate();

                            return [$.findDate(dates, y, m, d) != null, ''];
                        },
                        onSelect: function(dateText, inst) {
                            var date = new Date(dateText);
                            var y = date.getFullYear();
                            var m = date.getMonth();
                            var d = date.getDate();

                            var handled = $('.cs_blog_posts').loadPosts(y, m + 1, d, null, null, 1);
                            if (!handled) {
                                var day = $.findDate(dates, y, m, d);
                                document.location = day.Url;
                            }

                            return false;
                        }
                    });


                    var sStr = '';

                    if (year) {
                        sStr += year - dates.CurrentDate.getFullYear() + 'y ';
                    }
                    if (month) {
                        sStr += month - dates.CurrentDate.getMonth() - 1 + 'm ';
                    }
                    if (day) {
                        sStr += day - dates.CurrentDate.getDate() + 'd ';
                    }

                    if (sStr) {
                        holder.find('.datepicker_placeholder').datepicker('setDate', sStr);
                    }
                }

                if (expandY) {
                    holder.find('.archive_years').show();
                    holder.find('.archive_show_years').toggle(
                    function() { holder.find('.archive_years').slideUp(1000); },
                    function() { holder.find('.archive_years').slideDown(1000); });
                }
                else {
                    holder.find('.archive_years').hide();
                    holder.find('.archive_show_years').toggle(
                    function() { holder.find('.archive_years').slideDown(1000); },
                    function() { holder.find('.archive_years').slideUp(1000); });
                }

            });
        });
    };

    $.fn.blogCats2 = function(blogId, isEdit, isSelect) {
        var source = $(this);

        var addPane = source.find('.add_cat_pane');
        var addPaneInner = source.find('.add_cat_pane .cs_blog_categories_addpane');
        if (!isEdit) addPane.hide();
        var errPane = source.find('.cat_validation_error');
        var errMessage = source.find('.error_message');
        errPane.hide();
        addPaneInner.hide();

        if (!isEdit) addPane.hide();

        source.find('.addCategoryLabel').addClass("plus");
        source.find('.addCategoryLabel').toggle(
		        function() {
		            addPaneInner.slideDown(500);
		            $(this).removeClass('plus');
		            $(this).addClass('minus');
		            return false;
		        },
		        function() {
		            addPaneInner.slideUp(700);
		            $(this).removeClass('minus');
		            $(this).addClass('plus');
		            return false;
		        });

        source.find('.add_cat').click(function() {
            errPane.hide();
            var name = source.find('.cat_name').val();
            var parentId = source.find('.cs_blog_categories_list option:selected').val();
            $.blogService.validateAddCategory(blogId, name, parentId, function(res) {
                if (res) {
                    errMessage.text(res);
                    errPane.show();
                    return;
                }
                $.blogService.addCategory(blogId, name, parentId, function() {
                    source.loadCats(blogId, isEdit, isSelect);
                    source.find('.cat_name').val('');
                });
            });
            return false;
        });

        source.find('.cs_blog_categories_list').setTemplateElement('cs_t_cats_select');
        source.loadCats(blogId, isEdit, isSelect);
    };

    $.fn.renderCats = function(edit, select, parentId, catsMap, blogId) {
        return this.each(function() {
            var source = $(this);
            var cats = catsMap[parentId];
            if (cats == null) {
                if (parentId == -1) {
                    cats = new Array();
                }
                else {
                    return;
                }
            }

            source.setTemplateElement('cs_t_cats');
            source.processTemplate(cats, { root: parentId == -1, edit: edit, select: select, parentId: parentId, isRootBlog: blogId == -1 });

            source.find('.cat_childs').each(function() {
                var catParentId = $(this).attr('parentId');
                $(this).renderCats(edit, select, catParentId, catsMap, blogId);
            });

        });
    };

    $.fn.loadCats = function(blogId, edit, select) {
        var superSource = this;
        var reloadCats = function() {
            superSource.loadCats(blogId, edit, select);
        };
        return this.each(function() {

            var source = $(this);

            $.blogService.getCategories(blogId, null, function(cats) {
                var catsMap = new Array();

                $(cats).each(function() {
                    var arr = catsMap[this.ParentId];
                    if (arr == null) {
                        arr = new Array();
                        catsMap[this.ParentId] = arr;
                    }
                    arr.push(this);
                });

                source.find('.cs_cats_list').renderCats(edit, select, -1, catsMap, blogId);
                source.find('.cs_blog_categories_list').processTemplate(cats);

                source.find('.cat_move a').click(function() { return false; });

                source.find('.cat_list').sortable(
                    {
                        connectWith: '.cat_list',
                        //cursor: 'crosshair',
                        handle: '>.cat_move',
                        stop: function(event, ui) {
                            var newOrder = ui.item.prev().attr('order') || -1;
                            newOrder++;
                            var newParentId = ui.item.parent().attr('catId');
                            var catId = ui.item.attr('catId');

                            $.blogService.updateCategory(blogId, catId, newOrder, newParentId, function() {
                                reloadCats();
                            });
                        }
                    }
                );

                source.find('.cat_item').each(function() {
                    var item = $(this);

                    var delSec = item.find('>.cat_delete');
                    var delSecConfirm = item.find('>.cat_delete_confirm');
                    delSecConfirm.hide();

                    delSec.find('.cmd_try_delete').click(function() {
                        delSecConfirm.show();
                        delSec.hide();
                        return false;
                    });

                    delSecConfirm.find('.cmd_delete').click(function() {

                        $.blogService.deleteCategory($(this).attr('catId'), function() {
                            reloadCats();
                        });

                        return false;
                    });

                    delSecConfirm.find('.cmd_delete_cancel').click(function() {
                        delSecConfirm.hide();
                        delSec.show();
                        return false;
                    });
                });

                source.find('.cat_link').click(function() {
                    var handled = $('.cs_blog_posts').loadPosts(null, null, null, null, $(this).attr('cat'), 1);
                    return !handled;
                });

                var splitChecked = function() {
                    var checkeds = new Array();
                    var str = source.find('.cs_cats_checked input').val();
                    $(str.split(';')).each(function() {
                        checkeds[this] = true;
                    });
                    return checkeds;
                };

                var storeChecked = function(checkeds) {
                    var str = '';
                    for (var i in checkeds) {
                        if (checkeds[i]) {
                            if (str != '') str += ';';
                            str += i;
                        }
                    }
                    source.find('.cs_cats_checked input').val(str);
                };

                var temp = splitChecked();

                source.find('.cat_select').each(function() {

                    if (temp[$(this).attr('catId')]) {
                        $(this).attr('checked', 'checked');
                    }
                    else {
                        $(this).removeAttr('checked', 'checked');
                    }
                });

                source.find('.cat_select').change(function() {
                    var checkeds = splitChecked();
                    checkeds[$(this).attr('catId')] = $(this).attr('checked');
                    storeChecked(checkeds);
                });
            });
        });
    };


    $.fn.selectCats = function(blogId) {
        return this.each(function() {
            var holder = $(this);
            $.blogService.getCategories(blogId, null, function(res) {
                holder.processTemplate(res);

            });
        });
    };

    $.fn.blogAddPost = function(dateFormat, currentDate) {
        currentDate = currentDate || new Date();
        return this.each(function() {
            var source = $(this);
            var calInput = source.find('.post_createdOn');
            calInput.datepicker({
                maxDate: currentDate,
                dateFormat: dateFormat
            });
            var btn = source.find('.cs_blog_calendar_icon');

            btn.click(function() {
                calInput.datepicker("show");
            });

        });
    };

    $.createTagPopup = function(tags, control) {
        var popup = $('<div class=\'tagsPopupContainer\'></div>').insertAfter($(control));
        popup.setTemplateElement('cs_t_tagsPopup');
        popup.processTemplate(tags);
        popup.hide();
        popup.find('.tag a.tagLink').each(function() {
            $(this).click(function() {
                var oTags = $(control).val().split(/\s*,\s*/);
                var cTag = $(this).attr('tag');
                var nTags = new Array();
                var contains = false;
                for (var i = 0; i < oTags.length; i++) {
                    if (oTags[i] != cTag) {
                        if (oTags[i] != '') nTags.push(oTags[i]);
                    }
                    else {
                        contains = true;
                    }
                }
                if (!contains) nTags.push(cTag);
                var str = '';

                if (nTags.length > 0) {
                    str += nTags[0];
                    for (var i = 1; i < nTags.length; i++) str += ', ' + nTags[i];
                }
                $(control).val(str);
                return false;
            });
        });
        //popup.css('top', ($(control).position().top + $(control).innerHeight()) + 'px');
        return popup;
    };

    $.fn.tagsPopup = function(tags) {
        return this.each(function() {
            var popup = null;
            var control = $(this);

            $(this).focus(function() {
                if (tags && tags.length > 0) {
                    if (!popup) popup = $.createTagPopup(tags, this);
                    popup.css('width', ($(control).innerWidth() + 2) + 'px');
                    popup.slideDown(400);
                }
            });

            $(this).blur(function() {
                // if (popup) popup.slideUp(300);
            });



        });
    }

})(jQueryCS);

function run_archive($) {

    var minDate = eval($('#min_date').val());
    var maxDate = eval($('#max_date').val());
    var current = eval($('#selected_date').val());


    $('.datepicker1').datepicker({ minDate: minDate, maxDate: maxDate, defaultDate: current,
        onSelect: function(dateText, inst) {
            $('#selected_date').val(dateText);
            eval($('#archive_postback').val());
        }
    });

    var mode = parseInt($('#archive_mode').val());

    if (mode == 1) {
        $('#datepicker').show();
        $('#archive').hide();
        $('#change_view').text('Years');
        $('#change_view').attr('alternative', 'Months');
    }
    else {
        $('#datepicker').hide();
        $('#archive').show();
        $('#change_view').text('Months');
        $('#change_view').attr('alternative', 'Years');
    }

    $('#change_view').click(function() {
        $('#datepicker').toggle();
        $('#archive').toggle();
        var mode = parseInt($('#archive_mode').val());
        mode = (mode + 1) % 2;
        $('#archive_mode').val(mode);
        var temp = $(this).text();
        $(this).text($(this).attr('alternative'));
        $(this).attr('alternative', temp);

    });

}

function run_wizard($) {
    var muSection = $('.cs_blog_wizard_musettings');
    var roleSection = $('.cs_blog_wizard_roles');
    var roleList = $('.cs_blog_wizard_selectrole select');
    var newRolName = $('.cs_blog_wizard_newrole input[type="text"]');

    var isAllowedCreate = function() {
        return $('.cs_blog_wizard_create_role input:checked').size() > 0;
    };

    var isSelectRole = function() {
        return $('.cs_blog_wizard_selectrole input[type="radio"]:checked').size() > 0;
    };

    var isSBMode = function() {
        return $('.cs_blog_wizard_blogtype input[type="radio"]:checked').val() == '0';
    };

    var update = function() {
        if (isSBMode()) {
            muSection.hide();
        }
        else {
            muSection.show();
        }
        if (isAllowedCreate()) {
            roleSection.show();
        }
        else {
            roleSection.hide();
        }
        if (isSelectRole()) {
            newRolName.hide();
            roleList.show();
        }
        else {
            newRolName.show();
            roleList.hide();
        }
        $('.cs_blog_validate').hide();
    };

    update();

    $('.cs_blog_wizard_blogtype input[type="radio"]').change(function() {
        update();
    });

    $('.cs_blog_wizard_create_role').change(function() {
        update();
    });

    $('.cs_blog_wizard_newrole input[type="radio"], .cs_blog_wizard_selectrole input[type="radio"]').change(function() {
        update();
    });


    $('.cs_blog_wizard_init').click(function() {
        $('.cs_blog_validate').hide();
        var val = $('.cs_blog_wizard_blogtype input[type="radio"]:checked').val();

        var isSelect = jQueryCS('.cs_blog_wizard_selectrole input[type="radio"]:checked').size() > 0;
        if (val != '0' && !isSelect && $('.cs_blog_wizard_newrole input[type="text"]').val() == '') {
            $(".cs_blog_validate_role_empty").show();
            return false;
        }
        return true;
    });

}

function run_manager($) {
    $('#cs_add_blog_panel').hide();

    $('#cs_add_blog').click(function() {
        $('#cs_add_blog_panel').slideToggle();
    });
}
