var gID = function(el){ return document.getElementById(el); }

CARE2.grabWidget={
    borderColor:null,buttonColor:null,widgetSize:null,widgetCode:null,clip:null,

    updateClipboard:function(){

        this.widgetCode =   '<script type="text/javascript" src="http://dingo.care2.com/petitions/embed.js"></script>' +
                            '<div class="care2PetitionEmbed" rssPath="'+this.feedURL+'" adSize="'+this.widgetSize+'" ' +
                            'publisherId="'+this.publisherID+'" grabbed="0" flags="#000000" buttonColor="#'+this.buttonColor+'"></div>';

        var safeCode=this.widgetCode.replace(/\</g,'&lt;').replace(/\>/g,'&gt;');

        gID('embedCodeContent').innerHTML=safeCode;
    },

    crossDomainAjax:function(c){
        $.xdajax(c);
    },

    assignFeedURL:function(f,t,updateHTML){

        if(typeof f == "undefined" || !f || f == "na") {
            f = location.href;
            t = "url";
        }

        switch(t) {
            case "url":
                /* Next Action Page */
                if(f.indexOf("next_action.html?pId=") >= 0) {
                    f = f.split("next_action.html?pId=");
                    this.assignFeedURL(f[1],"single",updateHTML);
                    return;
                }

                /* NPO Petition Page */
                if(f.indexOf("/takeaction/") >= 0) {
                    f = f.split("/takeaction/");
                    this.assignFeedURL(f[1].replace(/\//g,""),"single",updateHTML);
                    return;
                }

                /* Citizen Petition Page */
                if(f.match(/thepetitionsite\.com\/\d+\//gi)) {
                    f = f.split("thepetitionsite.com");
                    var host = "http://" + CARE2.stage + "www.care2.com";
                    var servlet_url = host + "/servlets/petitions/petition_ID_from_custom_url.php";
                    var obj = this;

                    var callback = {
                        url: servlet_url,
                        args: "custom_url=" + f[1],
                        success: function(o){
                            obj.assignFeedURL(o.responseText,"single",updateHTML);
                        }
                    }

                    obj.crossDomainAjax(callback);

                    return;
                }

                /* Category Page (hopefully) */
                f = f.split("thepetitionsite.com/");
                this.assignFeedURL(f[1].replace(/\/$/gi,""),"category",updateHTML);
                return;

                break;
            case "single":
                f = f.slice(0,3)+'/'+f.slice(3,6)+'/'+f.slice(6,9);
                this.feedURL = 'http://www.thepetitionsite.com/xml/petitions/'+f+'/feed.swf';
                break;
            default:
                f=f||"animal-welfare";
                f=f.replace("non-profit", "npo");
                if(f.search('browse-petitions')!=-1){
                    f=(f.search('/')!=-1)?f.split('/')[1]:f.replace('browse-petitions','all');
                } else if(f.search('all')==-1) {
                    if((f.search('/')==-1) || (f.search('activist')==-1 && f.search('hottest')==-1 && f.search('npo')==-1)) { f=f+'/all'; }
                }
                this.feedURL='http://www.thepetitionsite.com/feeds/category/'+f+'/feed.swf';
                break;
        }

        this.updateCode();
        if(updateHTML) this.generateHTML();
    },

    init:function(d,t,f){
        var _self = this;

        _self.assignFeedURL(f,t);

        this.publisherID = (CARE2.loggedIn() && CARE2.loggedIn()!=false)?CARE2.loggedIn().passportID:'1249';

        if(d == "EMBED_TOOL") {
            var obj=this;
            this.embedded = true;
            var clipIntvl = setInterval(function(){
                if(typeof obj.clip != "undefined") {
                    clearInterval(clipIntvl);
                    obj.floaterCallback();
                }
            },50);
        } else {
            this.embedded = false;
            $(d).bind('click',{obj:this},this.showPopup);
        }
    },

    generateHTML:function() {
        var obj = this;

        obj.widgetImage.innerHTML = '<div class="care2PetitionEmbed" rssPath="'+obj.feedURL+'" adSize="'+obj.widgetSize+'" ' +
                            'publisherId="'+obj.publisherID+'" grabbed="0" flags="#000000" buttonColor="#'+obj.buttonColor+'"></div>';

        if(obj.scriptLoaded) {
            obj.resizeFloater();
            window.Care2Widgets.parse();
        } else {
            $.getScript("http://dingo.care2.com/petitions/embed.js", function(){
                obj.scriptLoaded = true;
                obj.resizeFloater();
            });
        }
    },

    floaterCallback:function(){
        this.widgetSize = $("#widgetSizeValue").val();
        this.borderColor = "000000";
        this.buttonColor = $("#widgetColorValue").val();
        this.updateClipboard();
        this.windowElement = $("#petitionWidget");
        this.windowWidth = this.windowElement.width();

        this.widgetImage = gID("widget_preview_sprite");

        this.containerWidth = $("#petitionWidget").width();
        this.widgetWidth = 300;

        this.generateHTML();
        this.widgetImage.style.display="block";

        this.clip.setText(this.widgetCode);
        this.clip.setHandCursor(true);
        this.clip.glue('grab_wdgt_copy_code');
        this.clip.addEventListener( 'onComplete', function(){
            gID('grab_wdgt_copy_code').style.display="none";
            gID('copied_code').style.display="block";
        });
    },

    updatePreview:function(){
        this.buttonColor = $("#widgetColorValue").val();

        this.updateCode(true);
    },

    updateCode:function(updateHTML) {
        updateHTML = updateHTML||false;
        this.widgetSize = $("#widgetSizeValue").val();
        this.buttonColor = $("#widgetColorValue").val();
        this.borderColor = "000000";

        if(gID("widgetPublisherValue") && gID("widgetPublisherValue").value && gID("widgetPublisherValue").value != this.publisherID) {
            this.publisherID = gID("widgetPublisherValue").value;
        }

        if(gID("widgetURLValue") && gID("widgetURLValue").value && gID("widgetURLValue").value != this.widgetURLValue) {
            this.widgetURLValue = gID("widgetURLValue").value;
            this.assignFeedURL(this.widgetURLValue, "url", true);
        } else if(this.embedded || updateHTML) {
            this.generateHTML();
        }

        this.updateClipboard();
        if(typeof this.clip != "undefined" && this.clip) this.clip.setText(this.widgetCode);
        gID('grab_wdgt_copy_code').style.display="block";
        gID('copied_code').style.display="none";

        var obj=this;
    },

    resizeFloater:function(){
        if($.colorbox) {
            if(window.Care2Widgets) {
                var newWidth = window.Care2Widgets.getSizes(this.widgetSize).baseSize.width;
                var innerWidth = (newWidth > this.widgetWidth) ? this.containerWidth + newWidth - this.widgetWidth : this.containerWidth;
                $("#petitionWidget").width(innerWidth);
            }
            $.colorbox.resize({
                innerWidth : innerWidth
            });
        }
    },

    showPopup:function(e,obj){
        obj=e.data.obj;
        $.colorbox({inline:true, href:"#petitionWidget",transition:"none",initialWidth:10,initialHeight:10,onCleanup:function(){clearInterval(obj.maintainZ);$(".care2petition_FlashContainer").remove()}},function(){obj.floaterCallback();});
        e.preventDefault();
    }
}

