/*
  WiP javascript library for smooth control of WiP functionality.
  Copyright Sorenso AS - 2011
*/
var WiP = Class.create({
    initialize: function(opt) {
        this.opt = {
            version : '0.0.1',
            ckeditor : []
        }
        Object.extend(this.opt, opt || {});
        if (this.opt.debug) {
            this.debug('initializing done...');
            this.debug(this.opt);
        }
    },
    debug: function (msg) {
        if (!this.opt.debug_id) {
            this.opt.debug_id = 'wip5_debug';
        }
        if (this.opt.debug && !$(this.opt.debug_id)) {
            document.body.insert({bottom: '<div style="background:#f6f6f6; color: #606060; font-size: 10px; font-family:verdana, arial; padding: 5px; position: fixed; bottom:30px; left:20px; width:800px; overflow:hidden; -moz-box-shadow: 0px 0px 10px #000000; -webkit-box-shadow: 0px 0px 10px #000000; box-shadow: 0px 0px 10px #000000; -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;"><h1>Debug</h1><div id="' + this.opt.debug_id + '" style="height: 250px; overflow : auto;"></div></div>'});
        }
        var message = '';
        if (this.opt.debug && $(this.opt.debug_id)) {
            if (msg.inspect) {
                message = msg.inspect().escapeHTML();
            } else {
                message = msg;
            }
            var date = new Date;
            var time = date.getTime();
            $(this.opt.debug_id).insert({bottom : time + ': ' + message + '<br />'});
            $(this.opt.debug_id).scrollTop = $(this.opt.debug_id).scrollHeight;
        }
    },
    random: function (range) {
        if (!range) range = 101;
        var rand = Math.floor(Math.random() * range);
        return rand;
    },
    ajax: function(opt1, opt2, opt3) {
    /* 
      WiP.ajax({
                url: '/tools/wip5/env.w5',
                div: 'box',
                param: {
                        id: '123',
                        action: 'save'
                       }
               }); 
      WiP.ajax(
               '/tools/wip5/env.w5',
               'box',
               {
                id: '123',
                action: 'save'
               }); 


    */


        this.debug('ajax: ' + opt1 + ', ' + opt2 + ', ' + opt3);
        var opt = {};
        opt.param = {};
        if (Object.isString(opt1)) {
            opt.url = opt1;
        } else if (opt1) {
            Object.extend(opt, opt1 || {});
        }
        if (Object.isString(opt2)) {
            opt.div = opt2;
        } else if (opt2) {
            Object.extend(opt, opt2 || {});
        }
        if (opt3 && !Object.isUndefined(opt3) && !Object.isString(opt3)) {
            Object.extend(opt.param, opt3 || {});
        }
        this.debug($H(opt).inspect());
        //this.debug('url: ' + opt.url);
        new Ajax.Request(opt.url, {
            //contentType: 'application/x-www-form-urlencoded',
            method: (opt.method || "post"),
            onLoading: function() {
                this.debug(opt.url + ' : onLoading...');
                if (opt.onLoading || this.opt.onLoading) {
                    if (opt.onLoading) {
                        this.debug(opt.url + ' : opt.onLoading');
                        opt.onLoading(opt, transport);   
                    } else {
                        this.debug(opt.url + ' : this.opt.onLoading');
                        this.opt.onLoading(opt, transport);
                    }   
                }
                if ($(opt.div + '_status')) {
                    $(opt.div + '_status').show();
                } else if ($('activityIndicator')) {
                    $('activityIndicator').show();
                }
            }.bind(this),
            onLoaded: function() {
                this.debug(opt.url + ' : onLoaded...');
                if (opt.onLoaded || this.opt.onLoaded) {
                    if (opt.onLoaded) {
                        this.debug(opt.url + ' : opt.onLoaded');
                        opt.onLoaded(opt, transport);   
                    } else {
                        this.debug(opt.url + ' : this.opt.onLoaded');
                        this.opt.onLoaded(opt, transport);
                    }   
                }


                if ($(opt.div + '_status')) {
                    $(opt.div + '_status').hide();
                } else if ($('activityIndicator')) {
                    $('activityIndicator').hide();
                }
            }.bind(this),
            onSuccess: function(transport) {
                this.debug(opt.url + ' : onSuccess...');
                if (opt.onSuccess || this.opt.onSuccess) {
                    if (opt.onSuccess) {
                        this.debug(opt.url + ' : opt.onSuccess');
                        opt.onSuccess(opt, transport);
                    } else {
                        this.debug(this.opt.url + ' : this.opt.onSuccess');
                        this.opt.onSuccess(opt, transport);
                    }
                } else {
                    this.debug(opt.url + ' : onSuccess');
                    $(opt.div).update(transport.responseText);
                }
                if (opt.onSuccessAfter || this.opt.onSuccessAfter) {
                    if (opt.onSuccessAfter) {
                        this.debug(opt.url + ' : opt.onSuccessAfter...');
                        opt.onSuccessAfter(opt, transport);
                    } else {
                        this.debug(opt.url + ' : this.opt.onSuccessAfter...');
                        this.opt.onSuccessAfter(opt, transport);
                    }
                }
            }.bind(this),
            onFailure: function (transport) {
                $(opt.div).update(transport.status + ': ' + transport.statusText + ': ' + opt.url);
            }.bind(this),
            parameters: (opt.param || {})
        });

    },

    initRatingFields: function (cssSelector) {
        $$(cssSelector + ' .rating_list a.rating_line_toggle').each( function (element) {
            var art = element.up('.rating_list');
            var rating = element.up('.rating_line_child');
            //alert( 'artid:' + art.id + 'ratingid:' + rating.id );
            $(element).observe('click', function(event){
                // alert(Event.element(event).innerHTML);
                $(rating.id).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
                wipAjax('div='+rating.id+'&type=article&level=1&objid='+art.id+'&parent='+rating.id, rating.id, '/tools/wip_v4/ajax_v2/rating/list_simple.epl', 'get');
            });
        });
        $$(cssSelector + ' .rating_list a.comment_add').each( function (element) {
            var art = element.up('.rating_list');
            var div = art.id;
            var rating = '';
            if ( element.up('.rating_line') ) {
                rating = element.up('.rating_line');
                div = rating.id;
            }
            $(element).observe('click', function(event){
                // alert(Event.element(event).innerHTML);
                $('comment_add_'+div).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
                wipAjax('div=comment_add_'+div+'&type=article&objid='+art.id+'&parent='+rating.id+'&class=ajax_v2_rating_form_sub&submit_txt=txt_form_submit_2&insertion=Before', 'comment_add_'+div, '/tools/wip_v4/ajax_v2/rating/add.epl', 'get');
            });
        });
        $$(cssSelector + ' .rating_list a.like_add').each( function (element) {
            var art = element.up('.rating_list');
            var div = art.id;
            var rating = '';
            if ( element.up('.rating_line') ) {
                rating = element.up('.rating_line');
                div = rating.id;
            }
            $(element).observe('click', function(event){
                // alert(Event.element(event).innerHTML);
                $('like_add_'+div).innerHTML = '<img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." />';
                if (rating) {
                    wipAjax('div=like_add_'+div+'&debug=&type=user_rating&objid='+rating.id+'&action=save&insertion=Before', 'like_add_'+div, '/tools/wip_v4/ajax_v2/rating/like.epl', 'get');
                } else {
                    wipAjax('div=like_add_'+div+'&debug=&type=article&objid='+art.id+'&action=save&insertion=Before', 'like_add_'+div, '/tools/wip_v4/ajax_v2/rating/like.epl', 'get');
                }
            });
        });
    },

    queryString: function () {
        var params = {};
        try {
            var query_string = window.location.search.split("?")[1];
            if (query_string) {
                params = query_string.toQueryParams();
            }
        } catch (err) { }
        return params;
    },


    wi_ckeditor: function (el, w, h, hide) {
        // Destroy the editor.
        // var editor = $(document.body).retrieve(id);
        var instance = CKEDITOR.instances[el.id];
        if (instance) {
            try {
		instance.destroy(true);
            } catch (err) { alert(err); }
	    try {
		delete CKEDITOR.instances[el.id];
	    } catch (err) { alert(err); }
            //try {
            //    instance.remove();
            //} catch (err) { alert(err); }
	}
        this.opt.ckeditor = this.opt.ckeditor.without(el.id);
        this.opt.ckeditor.push(el.id);
        CKEDITOR.replace(el.id, {
            stylesSet : [
                {name:'Facts',element:'div', attributes:{'class':'wip5facts'}},
                {name:'Facts2',element:'div', attributes:{'class':'wip5facts2'}},
                {name:'Full quote',element:'div', attributes:{'class':'wip5quotefull'}},
                {name:'Left quote',element:'div', attributes:{'class':'wip5quoteleft'}},
                {name:'Right quote',element:'div', attributes:{'class':'wip5quoteright'}},
                {name:'Full quote2',element:'div', attributes:{'class':'wip5quotefull2'}},
                {name:'Big',element:'big'},
                {name:'Small',element:'small'},
                {name:'Typewriter',element:'tt'},
                {name:'Computer Code',element:'code'},
                {name:'Keyboard Phrase',element:'kbd'},
                {name:'Sample Text',element:'samp'},
                {name:'Variable',element:'var'},
                {name:'Deleted Text',element:'del'},
                {name:'Inserted Text',element:'ins'},
                {name:'Cited Work',element:'cite'}
            ],
            toolbarStartupExpanded : (hide ? false : true),
            baseHref : '/',
            height : h,
            width : w,
            entities : true,
	    FormatSource : false,
	    //forceSimpleAmpersand : true,
            //entities_latin : false,
            //entities_greek : false,
            toolbar :[
                ['Format'], ['Styles'],
                ['Undo', 'Redo', 'PasteText'],
                ['Bold', 'Italic', 'Underline', 'Strike', '-', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Link', 'Unlink', 'Table'],
                ['Wip5form2mail', 'Wip5rss', 'Wip5rpl', 'Wip5boxleft', 'Wip5boxright', 'Wip5boxup', 'Wip5boxdown'],
                ['Source']
            ],
            //enterMode : CKEDITOR.ENTER_BR,
            //shiftEnterMode: CKEDITOR.ENTER_P,
            on : {
                instanceReady : function(ev) {
                    // Output paragraphs as <p>Text</p>.
                    this.dataProcessor.writer.setRules( 'span', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'div', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'p', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'h1', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'h2', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'h3', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'h4', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'ul', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    this.dataProcessor.writer.setRules( 'li', {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                    
                }
            }

        });
    },
    /* More functions here */


    // Placeholder from /www/docs/hotell/youbay.wip.no/js/wip.js



    hello_world: function () {

    }
});


