/*
 * Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
 * 
 * 2010-5-17 modify by zhaol (bitauto PersonalHome v1.0)
 * 
 */

var bitPerson = {

    jQuery: $,

    settings: {
        columns: '.col-three',
        widgetSelector: '.line_box',
        handleSelector: '.line_box_head',
        contentSelector: '.infolist_box',
        container: '.bt_page',
        prompt: '.yellow_tishi',

        isLogined: true,
        /* 位置存储的cookies */
        positionCookies: 'bitauto-personhome-position',
        /* 模块保存的cookies */
        moduleCookies: 'bitauto-personhome-module',
        /* 保存用户当前的浏览信息， 从接口得来 */
        linkCookies: 'bitauto-link-module',

        /* If you don't want preferences to be saved change this value to
        false, otherwise change it to the name of the cookie: */
        saveToCookie: 'bitPerson-widget-preferences',



        widgetDefault: {
            movable: true,
            removable: true,
            collapsible: true,
            editable: true
            // colorClasses: ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual: {}
    },

    init: function(loginTag) {
        // 设置是否登录状态
        this.settings.isLogined = loginTag;

        // 未登录时使用未登录cookies的名称 位置&模块
        if (!this.settings.isLogined) {
            this.settings.positionCookies = 'un-' + this.settings.positionCookies;
            this.settings.moduleCookies = 'un-' + this.settings.positionCookies;
            this.settings.linkCookies = 'un-' + this.settings.linkCookies;
        }
        // 装载自定义的css
        // this.attachStylesheet('bitPerson.js.css');
        // 远程请求模块内容, 并加载到加载区
        this.loadRemoteModule();
    },


    bindModule: function() {

        // 用户浏览过的数据
        // var linkCookiesValue = $.cookie(this.settings.linkCookies);

        var linkCookiesValue = "";
        // 判断当前是否存在位置信息， 不存在位置信息， 则读取默认信息接口
        // 读取 模块 position 信息
        var positionCookiesValue = $.cookie(this.settings.positionCookies);

        // 请求位置参数
        var queryPosition = positionCookiesValue != "" ? positionCookiesValue : "";
        var columnsClass = this.settings.columns;
        var personHome = this;
        // 装载模块到指定的列中
        $.getJSON("./bitPersonInterface.aspx?action=load&position=" + positionCookiesValue + "&ulink=" + linkCookiesValue + "&" + Math.random(), function(json) {
            // 遍历模块
            $.each(json.modules, function(i, module) {
                $(module.html).addClass(module.collapsed).appendTo($("#column" + module.column));
            });

            // 添加最大化最小化
            personHome.addWidgetControls();
            // 绑定拖拽
            personHome.makeSortable();
        });
    },

    /* 进行远程请求模块及内容 */
    loadRemoteModule: function() {

        this.bindModule();
        /*
        // 用户浏览过的数据
        var linkCookiesPara = "";
        var linkCookiesValue = $.cookie(this.settings.linkCookies);
        var person = this;
        if (linkCookiesValue == null || linkCookiesValue == "") {
        var i = 0;
        try {
        // 读取接口中信息
        $.getScript("http://go.bitauto.com/cheyisou/userlook.ashx", function() {
        linkCookiesValue = bitautoData.view;
        alert(linkCookiesValue); 
                   
        $.cookie(person.settings.linkCookies, linkCookiesValue, {
        expires: 30
        });
        person.bindModule();
        });
        }
        catch (e) {
        }
        }
        else {
        // 作为参数传入后台
        person.bindModule();
        }
        */
        /*
        // 测试自定义添加模块
        $('<div class="line_box"><h3 class="line_box_head"><span><a href="#">test</a></span></h3><div class="infolist_box">abc</div>'
        + '<div class="more"><a href="#" class="minimize" title="最小化">最小化</a><a href="#" class="close" title="关闭">关闭</a></div>'
        + '<div class="clear"></div></div>').addClass('collapsed').appendTo($("#column1")); 
    
        // 添加最大化最小化
        personHome.addWidgetControls();
        // 绑定拖拽
        personHome.makeSortable();
        */
    },

    getWidgetSettings: function(id) {
        var $ = this.jQuery,
            settings = this.settings;
        return (id && settings.widgetIndividual[id]) ? $.extend({}, settings.widgetDefault, settings.widgetIndividual[id]) : settings.widgetDefault;
    },

    addWidgetControls: function() {
        var bitPerson = this,
            $ = this.jQuery,
            settings = this.settings;

        $(settings.widgetSelector, $(settings.columns)).each(function() {

            var thisWidgetSettings = bitPerson.getWidgetSettings(this.id);
            if (thisWidgetSettings.removable) {
                var headDrop = $('.line_box_head', this);
                $('.more .close', this).mousedown(function(e) {
                    /* STOP event bubbling */
                    e.stopPropagation();
                }).click(function() {
                  if (confirm('是否要删除\"' + headDrop.text() + '\"?')) {
                    /*
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0
                        }, function() {
                            $(this).wrap('<div/>').parent().slideUp(function() {
                                $(this).remove();
                                bitPerson.savePreferences();
                            });
                        });*/
                        $(this).parents(settings.widgetSelector).remove();
                        bitPerson.savePreferences();
                    }
                    return false;
                });
            }

            if (thisWidgetSettings.collapsible) {
                $('.more .minimize', this).mousedown(function(e) {
                    /* STOP event bubbling */
                    e.stopPropagation();
                }).click(function() {
                    var s = $(this).parents(settings.widgetSelector);
                    s.toggleClass('collapsed');
                    if (s.hasClass("collapsed")) {
                        $(this).attr("title", "最大化");
                    }
                    else
                        $(this).attr("title", "最小化");
                    /* Save prefs to cookie: */
                    bitPerson.savePreferences();
                    return false;
                });
            }
        });

    },

    attachStylesheet: function(href) {
        /*var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');*/
    },

    makeSortable: function() {
        var bitPerson = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function() {
                return $('.line_box', settings.columns);
            })();
        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mousemove(function(e) {
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }).mousedown(function(e) {
            // $sortableItems.css({ width: '' });
            /*$(this).parent().css({
            width: $(this).parent().width() + 'px'
            });*/
            $(settings.columns).addClass("col-bottom");
        }).mouseup(function() {
            /*
            if (!$(this).parent().hasClass('dragging')) {
            $(this).parent().css({ width: '' });
            } else {
            $(settings.columns).sortable('disable');
            }*/
            $(settings.columns).removeClass("col-bottom");

        });

        $(settings.columns).sortable({
            items: $sortableItems,
            connectWith: $(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 20,
            delay: 50,
            opacity: 0.8,
            containment: 'document',
            start: function(e, ui) {
                $(ui.helper).addClass('dragging');
            },
            stop: function(e, ui) {
                $(ui.item).css({ width: '', position: '', opacity: '', left: '', top: '' }).removeClass('dragging');
                $(settings.columns).removeClass("col-bottom");
                $(settings.columns).sortable('enable');
                /* Save prefs to cookie: */
                bitPerson.savePreferences();
                if (!bitPerson.isLogined) {
                    //alert("test"); 
 //                   alert($(bitPerson.settings.prompt).html());
                    $(bitPerson.settings.prompt).css("display", "");
                }
            }
        }).disableSelection();
    },


    /* 保存 位置信息 到cookies */
    savePreferences: function() {
        var bitPerson = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';

        if (!settings.saveToCookie) { return; }

        /* Assemble the cookie string */
        $(settings.columns).each(function(i) {
            cookieString += (i === 0) ? '' : '|';
            $(settings.widgetSelector, this).each(function(i) {
                cookieString += (i === 0) ? '' : ';';
                /* ID of widget: */
                cookieString += $(this).attr('id') + ',';

                var dis = $(settings.contentSelector, this).css('display');
                /* Collapsed/not collapsed widget? : */
                cookieString += $(settings.contentSelector, this).css('display') === 'none' ? 'collapsed' : 'not-collapsed';
            });
        });
        // alert(cookieString); 
        // 保存位置与模块信息到COOKIES
        $.cookie(settings.positionCookies, cookieString, {
            expires: 30
        });
        // 如果登录后, 则保存到远程服务器
        if (settings.isLogined) {
            $.get("./bitPersonInterface.aspx", { action: "save", position: cookieString });
        }
    }

};


