;
/**
 * ShareThisWidget assigns click actions to the ShareThis widget's icons
 */

(function() {
    if ('function' === typeof window.ShareThisWidget) return;
    var POPUPWINPARAMS = {width:650,height:550,scrollbars:'yes',status:'no',location:'no',resizable:'yes'}
       ,BITLY_API_SCRIPT = 'http://bit.ly/javascript-api.js?version=latest&login=cobalt&apiKey=R_120c5e481588abb04d47969ddefff464'
       ,BITLY_TIMEOUT = 5000
       ,FORMFADE=300;

    var settings = {
            emailTarget : 'verifyCaptcha.do'
           ,emailCaptchaSrc : 'generateCaptchaImage.do?requestId='
           ,eventNameSpace : 'com.cobaltgroup.ws.action.ShareThisWidget'
           ,title : document.title
           ,url : window.location.href
        }
       ,nextId=1
       ,shortUrlCache = {},
       widgets = [];

    function PopupWindow(url,popupParams) {
        var params = paramString(jQuery.extend({},POPUPWINPARAMS,popupParams || {}));
        this.url = url || '';
        this.win = window.open(this.url,'',params);
        if (this.url != '') this.redirect(this.url);
        function paramString(obj) {
            var s = [];
            for (var prop in obj) s.push(prop + '=' + obj[prop]);
            return s.join(',');
        }
    };

    PopupWindow.prototype.redirect = function(url) {
        if (this.win == null) {
            setTimeout(function() {this.redirect(url)},50);
        } else {
            if (this.url != url) this.win.document.location = url;
            this.win.focus();
        }
    };

    function shortenUrl(longUrl,onShortened) {
        var callback = 'shortenUrl_' + (nextId++)
           ,timeoutRef = null
           ,shortUrl;

        function cached(url) { return (longUrl in shortUrlCache) ? shortUrlCache[longUrl] : false; }
        function cache(longUrl,shortUrl) { shortUrlCache[longUrl] = shortUrl; }

        if (shortUrl = cached(longUrl)) {
          // don't request re-shortening for the same URL
          onShortened(shortUrl);
          return;
        }
        var BitlyCB_callback = function(data) {
            var returnName;
            if (timeoutRef) {                         // Bitly returned in time to fire the callback
                clearTimeout(timeoutRef);             // ensure the timeout routine doesn't run
                timeoutRef = null;
                try {
                   for (var r in data.results) {      // Results are keyed by longUrl: grab the first one.
                       returnName = (data.results[r]["shortUrl"].toString());
                       break;
                   }
                } catch(e) {
                    returnName = longUrl;
                }
                delete window.BitlyCB[callback];      // cleanup
                if (returnName != longUrl)
                    cache(longUrl,returnName);        // cache it for quick return on subsequent requests
                onShortened(returnName);
            }
        };
        timeoutRef = setTimeout(function() {
            onShortened(longUrl);
            timeoutRef = null;
        },BITLY_TIMEOUT);
        jQuery.getScript(BITLY_API_SCRIPT,function() {
            try {
                window.BitlyCB[callback] = BitlyCB_callback;
                BitlyClient.shorten(longUrl, 'BitlyCB.'+callback);
            } catch(e) {};
        });
    }

    function publishEvent(type,data) {
        if (window.EventManager && 'function' === typeof EventManager.publish)
            EventManager.publish({eventName: settings.eventNameSpace + '.' + type,publisherData:data});
    }
    function newCaptcha(elm) {
        var requestId = (Math.random() * 1000000) | 0
           ,CAPTCHAIMG = '<img class="captchaImg" alt="captcha image" src="%SRC%"/>';

        elm.find('.captchaRequestId').val(requestId);
        elm.find('.captchaImage').html(CAPTCHAIMG.replace(/%SRC%/,settings.emailCaptchaSrc+requestId));
    }
    function resetEmail(elm) {
        elm.find('.text').val('');
        elm.find('[name=visitedPage]').val(document.location.href);
        newCaptcha(elm);
    }
    function setupEmail(elm) {
        function retry() {
            alert('The keyword you entered does not match the displayed image. Please try again.');
            newCaptcha(elm);
            elm.find('[name=keyword]').addClass('error').focus().val('');
            return false;
        }

        function thankYou() {
            elm.find('form').hide();
            elm.find('.thankYou').show();
            ShareThisWidget.publishEvent('email.thankYou');
        }

        elm.find('.close').unbind('click').click(function() {
            elm.find('div.emailForm').fadeOut(FORMFADE,function() {
                elm.find('.thankYou').hide();
                elm.find('input:text').val('');
                elm.find('input:checkbox').attr('checked',false);
                elm.find('input').removeClass('error');
            });
        });
        elm.find('.thankYou').hide();
        elm.find('form').show().unbind('submit').submit(function() {
            var texts = elm.find('input.text')
               ,valid = true;
            elm.find('.errorMsg').css('visibility','hidden');
            texts.each(function() {
                var $j = jQuery(this)
                   ,val = $j.val();
                $j.removeClass('error');
                if (val.match(/^\s*$/)) {
                    valid = false;
                    $j.addClass('error');
                }
            });
            if (!valid) {
                elm.find('.errorMsg').css('visibility','visible');
            } else {
                jQuery.ajax({
                    type:'post'
                   ,dataType:'text'
                   ,url:settings.emailTarget
                   ,data:elm.find('form').serialize()
                   ,success:function(data,code) {
                       return ('success' === jQuery.trim(data)) ? thankYou() : retry();
                   }
                   ,error:retry
                });
            }
            return false;
        });
    }

    function emailHandler(elm) {
        function px(n) {return n+'px';}
        var icons = elm.find('ul');
        setupEmail(elm);
        ShareThisWidget.publishEvent('email');
        resetEmail(elm);
        elm.find('div.emailForm').css({top:px(-icons.height()),left:px((icons.width()/2)|0)}).fadeIn(FORMFADE);
    }
    function printHandler() {
        ShareThisWidget.publishEvent('print');
        window.print();
        return false;
    }
    function facebookHandler() {
        ShareThisWidget.publishEvent('facebook');
        var popup = new ShareThisWidget.PopupWindow(null,{height:600});
        ShareThisWidget.shortenUrl(settings.url,function(shortUrl) {
            popup.redirect('http://www.facebook.com/sharer.php?t='
                + encodeURIComponent(settings.title)
                + '&u='
                + encodeURIComponent(shortUrl));
        });
        return false;
    }
    function favoritesHandler() {
       ShareThisWidget.publishEvent('favorite');
       if ('undefined' != typeof window.sidebar) {               // Firefox
           window.sidebar.addPanel(settings.title,settings.url,'');
       } else if ('undefined' != typeof window.external && 'undefined' != typeof window.external.AddFavorite) {       // IE
           window.external.AddFavorite(settings.url,settings.title);
       }
       return false;
    }
    function twitterHandler() {
        ShareThisWidget.publishEvent('twitter');
        var popup = new ShareThisWidget.PopupWindow(null,{width:560,height:460});
        ShareThisWidget.shortenUrl(settings.url,function(shortUrl) {
             popup.redirect("http://twitter.com/home?status="
                + shortUrl + " " + encodeURIComponent(settings.title));
        });
        return false;
    }

    function init(elm,initialSettings) {
        jQuery.extend(settings,initialSettings);
        elm.find('div.emailForm').hide();
        elm.show();

        if (('undefined' != typeof window.sidebar) || 
            ('undefined' != typeof window.external && 'undefined' != typeof window.external.AddFavorite)) {
            elm.find('.favorites').click(function() {return ShareThisWidget.favoritesHandler();});
        } else {
            elm.find('.favorites').hide();
        }
        elm.find('.email').click(function() {return ShareThisWidget.emailHandler(elm);});
        elm.find('.print').click(function() {return ShareThisWidget.printHandler();});
        elm.find('.twitter').click(function() {return ShareThisWidget.twitterHandler();});
        elm.find('.facebook').click(function() {return ShareThisWidget.facebookHandler();});

        widgets.push(elm);
        elm.data('shareThisWidget',window.ShareThisWidget);
        ShareThisWidget.publishEvent('init',{widget:elm,object:ShareThisWidget});
    }

    window.ShareThisWidget = {
         PopupWindow : PopupWindow
        ,shortenUrl : shortenUrl
        ,facebookHandler : facebookHandler
        ,emailHandler : emailHandler
        ,twitterHandler : twitterHandler
        ,printHandler : printHandler
        ,favoritesHandler : favoritesHandler
        ,publishEvent : publishEvent
        ,init : init
    }

})();

