// Prefetch the item's image
Plum.subscribe('item.active', function(data) {
    var img = document.createElement('img');
    img.src = Plum.item.image(data.item, 'large');
});

var _debugEnabled = false;
function enableDebug(enabled) {
    _debugEnabled = !!enabled;
}
function debugBus() {
    Plum.subscribe('**', function(data) {
        debug('message: ' + this.topic, data);
    });
}
function debug(msg, dump) {
    if ( _debugEnabled ) {
        if (typeof console != 'undefined' && console && console.log ) {
//            console.log( msg );
            if ( arguments.length == 2 && console.dir ) {
//                console.dir( dump );
            }
        }
    }
}

// Various handlers
(function() {
    var _itemCache = {};
    // Handler for requesting item.overlay
    Plum.handler({
        topic: 'item.overlay',
        publish: false,
        callback: function(ret, data) {

            // to fix #1153
            $("#formShare").remove();
            if ( _itemCache[data.item] && !stateChange('closet_overlay', data.item) ) {
                ret(_itemCache[data.item]);
            } else {
                stateChange('closet_overlay', data.item, false);
                $.ajax({
                    url: '/closet/' + data.item,
                    type: 'POST',
                    dataType: 'html',
                    success: function(html) {
                        _itemCache[data.item] = html;
                        ret(html);
                        if (!hasSession()) {
                            user_has_no_session();
                        }
                    }
                });
            }
        }
    });
})();

//used for the overlay back link functionality
Plum.itemBackhistory = [undefined];
Plum.itemBackhistoryCount = 0;

Plum.handler({
    topic: 'item.share',
    callback: function(ret, data) {
        $.ajax({
            url: '/closet/' + data.shareid,
            type: 'POST',
            data: data,
            dataType: 'json',
            error: function(xhr, status, error) {
                ret({status: 'error', 'message': 'Unable to share item on facebook', ajaxData: { status: status, error: error } });
            },
            success: function(data) {
                ret(data);
            }
        });
    }
});

// Display an item overlay when an item is clicked
Plum.subscribe('ui.show.detail', function(data) {
    var parentElem = $(data.element);
    if ($('body div').is('.view-canvas')) {//only show overlay if its the canvas page
        var imgsrc = parentElem.find('img').attr('src');
        var fb = 'http://graph.facebook.com';
        if (imgsrc.substr(0, fb.length) == fb) { //don't launch overlay for users
            document.location = parentElem.find('a').attr('href');
        } else {
            var item = Plum.item.idFromUrl(imgsrc);
            var itemID = $(parentElem).parent()[0].id;
            
            logClicktale("$('#" + itemID + "').itemOverlay(" + JSON.stringify(item) + ')');
            $(data.element).itemOverlay(item);
        }
    } else {//other wise follow href
        window.location = parentElem.find('a').attr('href');
    }
});


var isAlt  = false,
    isCtrl = false;
$(document).keyup(function(e) {
    if (e.which == 18) isAlt = false;
    if (e.which == 17) isCtrl = false;
});

$(document).keydown(function(e){
    if (e.which == 18) isAlt = true;
    if (e.which == 17) isCtrl = true;
});
                

// Handle a value change from a user prior to an action-* taking place
$(document).bind('click', function(evt) {
    $(evt.target).closest('[data-storage]').each(function() {
        var $t = $(this);
        var key = $t.attr('data-storage'),
            value = $t.attr('data-value');
        if ( key && value ) {
            var prev = Plum.storage.get(key);
            if ( value !== prev ) {
                //console.log('Storing: ' + value + ' to ' + key );
                Plum.storage.set( key, value );
                Plum.publish('storage.save', { key: key, value: value });
            }
        }
    });
});

// Handle user clicking on an element and triggering an action
$('[class*=action-]:not(:text,textarea)')
    .live('click', function(evt) {
        if ( $(evt.target).hasClass('ignore-action') || isCtrl) {
            return;
        }

        // Extract out our action name
        var action = this.className.match(/action-([^\s]+)/i)[1].toLowerCase();
        Plum.publish('ui.' + action.replace(/-/g, '.'), { element: this });
        if (!isCtrl) {
            evt.preventDefault();
        }
        return false;
    });

// Handle user pressing enter on an input
$(':input[class*=action-]')
    .live('keydown', function(evt) {
        // User pressed the enter key
        if ( evt.which == 13 ) {
            // Trigger the UI event
            // Extract out our action name
            var action = this.className.match(/action-([^\s]+)/i)[1].toLowerCase();
            Plum.publish('ui.' + action.replace('-', '.', 'g'), { element: this });
            evt.preventDefault();
            return false;
        }
    });

// Handle user hovering over an element
$('[class*=hover-]')
    .live('hover', function(evt) {
        // Extract out our action name
        var action = this.className.match(/hover-([^\s]+)/i)[1].toLowerCase();
        Plum.publish('ui.' + action.replace('-', '.', 'g'), { type: evt.type, element: this });
    });

// Handle a user changing a value on an input form
$(':input')
    .live('keyup change focus store', function(evt) {
        var $t = $(this);
        if ( $t.hasClass('data-storage') ) {
            var key = $t.attr('name'),
                value = $t.val();
            var prev = $t.data('storage-value');
            $t.data('storage-value', value);

            if ( $t.is(':checkbox') ) {
                value = $t.is(':checked') ? value : '';
                Plum.storage.set( key, value );
                Plum.publish('storage.save', { key: key, value: value });
            } else {
                if ( value !== prev ) {
                    Plum.storage.set( key, value );
                    Plum.publish('storage.save', { key: key, value: value });
                }
            }
        }
    });

// Restoring of storage
$('.data-storage')
    .live('restore', function() {
        var $t = $(this),
            key = $t.attr('name'),
            val = Plum.storage.get(key);
        if ( $t.is(':checkbox') ) {
            if ( val ) {
                $t.attr('checked', 'checked');
            } else {
                $t.removeAttr('checked');
            }
        } else {
            $t.val( val );
        }
    })
    .live('sync', function() {
        var $t = $(this),
            key = $t.attr('name'),
            val = Plum.storage.get(key);
        if ( val !== undefined && val == '' ) {
            $t.trigger('restore');
        } else {
            $t.trigger('store');
        }
    });

//init the thumbnail paginators/pagers/sliders, invite page style
$(document).ready(function() {
    if ($('.view-invite').length || $('#content .oneCol').length) {
        $("#footer").width(1050);
    }

    $('.thumbnailPaginator ul').carouslider({
        infinite: false,
        onbeforenext: function(widget, activeSlide) { //call the ajax method, fetch the next set.

            //we're using onbeforenext, so the activeslide hasnt been set to the next slide yet, we'll need to account for that.
            var activeSlide = activeSlide.next();
            if (activeSlide && activeSlide.next().length) {
                return;
            }

            var id    = widget.element.attr('id');
            var url   = id;
            var args  = $("input[class^=" + id + "]", widget.element.parents('.thumbnailPaginator')).serialize();
            var limit = 3;
            var nextIndex = (activeSlide.data('juice-carouslider').index + 1);
            if ($('#limit_' + id).size() == 1) {
                limit = $('#limit_' + id).val();
            }
            if ($("#" + id + "_url").size() == 1) {
                url = $("#" + id + "_url").val();
            }
            var skip = nextIndex * limit;

            $.ajax({
                url: '/results/' + url + '?type=paginator&' + args  + '&limit=' + limit + '&skip=' + skip,
                dataType: 'json',
                success: function(json) {
                    if (!json || !$.isArray(json)) {
                        return;
                    }
                    var slide = $([]),
                        first = activeSlide.find('div:first');

                    $.each(json, function() {
                        var item = first.clone(),
                            uniboxSize = '250';

                        /*
                        var klass = item.attr('class'),
                            uniboxIndex = klass.indexOf('unibox-') + 'unibox-'.length;
                        if (uniboxIndex >= 0) {
                            klass = klass.substring(uniboxIndex);
                            uniboxSize = klass.substring(0, klass.indexOf(' '));
                        }
                        */

                        if (this.promo && this.promo.length) {
                            $.each(this.promo, function(i, v) {
                                item.append($('<span class="hotdeal '+ v +'"></span>'));
                            });
                        }

                        item.find('a')
                            .attr('href', '/closet/' + this._id)
                            .attr('title', this.name);

                        item.find('img')
                            .attr('src', Plum.config(Plum.imageTypes[this._id.substring(0, 1)] + '_base_url') + this._id + '-' + uniboxSize)
                            .attr('alt', this.name)
                            .removeClass('ui-draggable'); //if the first item needs to be draggable, js will look for this class. remove it so the check passes.

                        item.find('.unibox-caption').html(this.name);

                        slide = slide.add(item);
                    });

                    widget.addSlide(slide);
                }
            });
        }
    });

    //we need to move this out of the carouslider parent element due to overflow issues.
    //not a huge deal. css will take care of this.
    $('.thumbnailPaginator').each(function() {
        $(this).find('.juice-carouslider-pager').appendTo(this);
    });
});

function toggleHelp(id, anchor) {
	$(id).slideToggle("fast");
	$(anchor).toggleClass('opened');
}

////////////////////// update profile and tags ///////////////////

function update_tags(id) {
    var tag_text = $('input[name=tags_ajax]').val();
    $('#content .rightCol').overlay();
    $.ajax({
        type: 'POST',
        url: '/closet/' + id,
        data:  {'tags_ajax' : tag_text},
        dataType: 'json',
        success: function (json) {
            $("#tags_list").html(json.tags);
            $('#content .rightCol').overlay('destroy');
            $('input[name=tags_ajax]').val('');
            stateChange('closet_overlay', id, true);
        },
        error: function() {
            Plum.alert('server ajax error');
            $('#content .rightCol').overlay('destroy');
        }
    });
}

$(function() {
    $(".tag-delete a").live("click", function(e){
        if (confirm("Are you *sure* you want to remove this tag?")) {
            $.ajax({
                type: 'POST',
                url: $(this).attr("href"),
                data: { 'removetag_ajax': $(this).data("tag") },
                dataType: 'json',
                success: function (json) {
                    $("#tags_list").html(json.tags);
                    $('#content .rightCol').overlay('destroy');
                },
                error: function() {
                    Plum.alert('server ajax error');
                    $('#content .rightCol').overlay('destroy');
                }
            });
        }
        e.preventDefault();
        return false;
    });
}); 


$(document).ready(function() {

// make all links external to pw open in new tab
$('a[href^="http://"]')
  .attr({
    target: "_blank", 
    title: "opens in a new window"
  });
	
$("#friends").hide();
$(".view-welcome .pollsHelp").html('<p><strong>start your own poll!</strong><div class="steps"><div class="step"><span id="circle1" class="circle" title="1"></span>go to the <a href="/shop" title="Shop page">Shop</a> or <a href="/discover" title="Discover page">Discover</a></div><div class="step"><span id="circle2" class="circle" title="2"></span>find an outfit or item you love</div><div class="step"><span id="circle3" class="circle" title="3"></span>click "start your own poll"</div></p><div class="clear"></div></div>');
var $profile = $('.updateprofile');
$profile.submit(function() {
    var $form = $(this);
    $('#content .rightCol').overlay();
    $.ajax({
        type: 'POST',
        url: $form.attr('action'),
        data: $form.serialize(),
        dataType: 'json',
        success: function (json) {
            if (!json.result) {
                Plum.alert('internal server ajax error');
            }
            $form.find('.prefSaveConfirm').show('slow').delay(3000).hide('slow');
            $('#content .rightCol').overlay('destroy');
        },
        error: function() {
            Plum.alert('server ajax error');
        }
    });
    return false;
});

var dtext = 'describe yourself in 140 characters or less';
var bio   = $("textarea[name=bio]");
if (bio.size() == 1) {
    bio.click(function() {
        var pthis = bio;
        if ($.trim(pthis.val()) == dtext) {
            pthis.val('');
        }
    });

    bio.blur(function() {
        var pthis = bio;
        if ($.trim(pthis.val()) == '') {
            pthis.val(dtext);
        }
    });

    bio.trigger('blur');

    bio.keyup(function() {
        var pthis = bio;
        $("input[name=counter]").val(140 - pthis.val().length);
        pthis.val(pthis.val().substr(0, 140));
    });
}

});

//tabs in overlay func. to show clicked tab
(function($) {
    $('#overlay-tabs h2 a').live('click',function() {
        $(this).closest('li').siblings().andSelf().removeClass('active').end().end().addClass('active');
        return false;
    });
})(jQuery);

//enlarge image
var doEnlarge = true;
(function($) {

    $('.enlargeImage').live('mouseout', function() {
        doEnlarge = true;
    });

    $('.enlargeImage').live('mouseover', function() {
        var img = $(this).find('img');
        var w = img.width();
        var h = img.height();
        $("#hiddenOverlay").remove();

        $('<div></div>')
                .html('<img src="'+Plum.item.image(Plum.item.idFromUrl($(this).find('img').attr('src')),'orig')+'" />')
                .find('img')
                    .load(function() {
                        var imageW = $(this).width();
                        var imageH = $(this).height();

                        if ( (imageH <= h) && (imageW <= w) ) {
                            doEnlarge = false;
                            // remove the magnifying glass cursor
                            img
                            .css('cursor', 'default')
                            .cond(img.parent().get(0).tagName == "A", function() {
                                img
                                .closest('a').css('cursor', 'default')
                                .closest('.unibox').css('cursor', 'default');
                            });
                        }
                        $(this).remove();
                    })
                .appendTo('body')
                .hide();
    });

    $('.enlargeImage').live('click',function() {
        $('#enlargeImageOverlay').remove();
        $('<div id="enlargeImageOverlay"></div>')
                .html('<div id="overlay-drag-handle"></div><img id="dragbarLeft" src="/images/icon.move.png" alt="" width="25" height="26" /><a title="close" href="#" class="action-close">close</a><img src="'+Plum.item.image(Plum.item.idFromUrl($(this).find('img').attr('src')),'orig')+'" />')
                .find('img:last')
                    .load(function() {
                        var windowWidth = $(window).width();
                        var imageW = $(this).width();

                        if(imageW>windowWidth){
                            $(this).width(windowWidth-20);
                        }

                        $('#enlargeImageOverlay')
                            .css('width',$(this).width()+'px')
                            .position({
                                my: 'left top',
                                at: 'left top',
                                of: window,
                                offset: '10 '+(10+$(window).scrollTop()),
                                collision: 'none'
                            });
                    })
                .end()
                .delegate('.action-close', 'click', function() {
                    $(this).closest('#enlargeImageOverlay').remove();
                    return false;
                })
                .draggable({
                    handle:'#overlay-drag-handle',
                    stop: function() {
                        var offset = $(this).offset();
                        if (offset.top < 0) {
                            $(this).css("top", ("2" + "px"));
                        }
                    }
                })
                .cond(doEnlarge === true, function() {
                    //$(this).css({'left':'-3000px','top':'-3000px'})
                    $(this)
                    .appendTo('body')
                    .show();
                });
        return false;
    });
    
    $('.noEnlargeImage').live('click', function() {
        return false;
    });
})(jQuery);

var _states = [];
function stateChange(type, id, state) {
    if (state) {
        if (_states[type] == undefined) {
            _states[type] = [];
        }
        _states[type][id] = state;
        return true;
    }
    if (_states[type] != undefined && _states[type][id] != undefined) {
        return _states[type][id];
    }
    return false;
}

function wishlist_toggle(id, callback) {
    var url = "/closet/" + id + "?wishlist=1";
    stateChange('closet_overlay', id, true);
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        success: function(json) {
            if (json.message) {
                if (json.message[0] == "a") {
                    $(".wishlist-remove").removeClass('wishlist-remove').addClass('wishlist');
                } else {
                    $(".wishlist").removeClass('wishlist').addClass('wishlist-remove');
                }
                $("#wishlink,#wishlinkWithItem").html(json.message);
                if (callback) {
                    callback(json.message[0] != "a");
                }
            } else {
                Plum.alert('internal server ajax error');
            }
        },
        error: function() {
            Plum.alert('server ajax error');
        }
    });
}

function fav_toggle(id, onsuccess) {
    var url = "/closet/" + id + "?fav=1";
    stateChange('closet_overlay', id, true);
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        success: function(json) {
            if (json.message) {
                if (typeof onsuccess == 'function') {
                    onsuccess(json);
                    return;
                }
                var txt = parseInt(json.total) < 2 ? 'person loves this!' : 'people love this!';
                $("#favlink").toggleClass('unfav');
                $("#favlink").html(json.message);
                $("#favlink").attr("title", json.message);
                $("#favs").html( '<strong>' + json.total + '</strong> ' + txt);
                if (json.total == 0) {
                    $("#favs").hide();
                } else {
                    $("#favs").show();
                }
            } else {
                Plum.alert('internal server ajax error');
            }
        },
        error: function() {
            Plum.alert('server ajax error');
        }
    });
}
$('body').ready(function() {
    $("#comment_text,#comment_text_profile").val('write comment here...');
    $("#comment_text,#comment_text_profile").live('focus', function(e){
        if ( $(this).val() == 'write comment here...' ){
            $(this)
            .val('');
        }
        $(this).css({
            'color': 'black',
            'height': '70px',
            'font-style': 'normal'
        })
    });
    $("#comment_text,#comment_text_profile").live('blur', function(e){
        if ( $(this).val() == '' ){
            $(this)
            .css({
                'color':'grey',
                'height': '25px',
                'font-style': 'italic'
            })
            .val('write comment here...')
        }
    });
    // ribbon global search box
    $("#btnSearchGlobalSubmit").attr('title', 'go');
    if ($("#inpSearchGlobal").val() == '') {
        $("#inpSearchGlobal").val('search...');
    } else {
        $('#inpSearchGlobal').css({'color':'black', 'font-style':'normal'})
    }
    $("#inpSearchGlobal").live('focus', function(e){
        if ( $(this).val() == 'search...' ){
            $(this)
            .val('');
        }
        $(this).css({'color':'black', 'font-style':'normal'})
    });
    $("#inpSearchGlobal").live('blur', function(e){
        if ( $(this).val() == '' ){
            $(this)
            .css({'color':'grey', 'font-style':'italic'})
            .val('search...');
        }
    });

});
function comment_toggle() {
    var link = $("#addComment");
    var form = $("#comForm");

    if (link.is(":visible")) {
        link.hide();
        form.show();
        $("#comment_text, #comment_text_profile").animate(
            {height: "70px"}
        )
        .css({color: 'grey'})
        .val('write comment here...');
    } else {
        $("#comment_text, #comment_text_profile").animate(
            {height: "19px"}, 500, (function(){
                form.hide();
                form.find("textarea").val(''); /* reset value */
                link.show();
        }));
    }
}

function comment_user(id) {
    var url = "/closet/" + id;
    var content = $('#comment_text_profile');

    if ($.trim(content.val()) == "" || content.val() == "write comment here...") {
        alert("Please write something!");
        content.focus();
        return;
    }

    $.ajax({
        url: url,
        type: 'POST',
        data: {'comment_user_ajax' : content.val() },
        success: function(json) {
            if (json.status == "ok") {
                // so something with json.activity
                $('.lstActivity').html(json.myactivity);

                $("#comment_text, #comment_text_profile")
                .val('write comment here...')
                .blur()
                .css({color:'grey', height: "19px"});
            } else {
                Plum.alert('server ajax error');
            }
        },
        error: function() {
            Plum.alert('server ajax error');
        }
    });
}

function comment_post(id, success) {
    var url = "/closet/" + id;
    var content = $("#comment_text");

    if ($.trim(content.val()) == "" || content.val() == "write comment here...") {
        alert("Please write something!");
        content.focus();
        return;
    }

    stateChange('closet_overlay', id, true);

    $.ajax({
        url: url,
        type: 'POST',
        data: {'comment_ajax' : content.val() },
        success: function(json) {
            if (json.status == "ok" && !success) {
                $('#activity_list').html(json.activity);
                $("#comment_text, #comment_text_profile")
                .val('write comment here...')
                .blur()
                .css({color:'grey', height: "19px"});
            } else if (json.status == "ok" && success) {
                success(json);
            } else {
                Plum.alert('server ajax error');
            }
        },
        error: function() {
            Plum.alert('server ajax error');
        }
    });
}

function wishlistShare() {
    if ($("#shareWishlist").length) {
        return;
    }

    $(".ui-dialog-content:visible").dialog('close');
    var $f = $('#formShare');
    $('.active-item-overlay').css({zIndex:1000});
    logClicktale("wishtlist()");
    $f.dialog({
        resizable: false,
        modal: false,
        buttons: {
            'cancel': function() {
                $f.dialog('close');
            },
            'share': function() {
                $.post('/closet/send_wishlist', $f.serialize(), function(data) {
                    if (data.error) {
                        Plum.ui.alert('Error', data.error);
                        $f.find('textarea').focus();
                        return;
                    }
                    var a = Plum.ui.alert('E-mail sent', 'You wishlist has been shared');
                    setTimeout(function() {
                        a.dialog('close');
                        $f.dialog('close');
                    }, 2000);
                }, 'json');
            }
        },
        open: function() {
            $('button', $f.parent()).addClass('item-overlay-trigger');
            $f.find('textarea')[0].focus();
        },
        close: function() {
            $('.active-item-overlay').css({zIndex:10000});
            $('#viewNew').hide();
            $("#shareWishlist").find('#sharefb-drag-handle').remove();
            $("#shareWishlist").find('.action-close').remove();
            $("#shareWishlist").removeAttr('id');
        },
        title: ""
    });
    $("div[role=dialog]").attr('id', 'shareWishlist');
    $("div[role=dialog]").prepend(
        '<div id="sharefb-drag-handle"></div>' +
        '<a class="action-close hidden_link" href="#" title="close" target="_blank">close</a>'
    ).find(".action-close").click(function() {
        $f.dialog('close');
    }).end()
    .draggable({
        handle:'#sharefb-drag-handle',
        containment: 'parent'
    });
}

function fbShare(itemid) {
    if ($("#shareFacebook").length) {
        return;
    }
    var $f = $('#formShare');
    $('.active-item-overlay').css({zIndex:1000});

    logClicktale("fbShare('" + itemid +  "')");
    $f.dialog({
        width: 572,
        height: 335,
        resizable: false,
        modal: false,
        buttons: {
            'cancel': function() {
                $f.dialog('close');
            },
            'share': function() {
                var data = {'shareid' : itemid};
                data['target'] = $("#shareFacebookFriends option:selected").val();
                data['source'] = $("input[name=source]").val();
                Plum.request('item.share', data, function(data2) {
                    $f.dialog('close');
                });
            }
        },
        open: function() {
            $('button', $f.parent()).addClass('item-overlay-trigger');
            $('select', $f).show();
        },
        close: function() {
            $('.active-item-overlay').css({zIndex:10000});
            $('#viewNew').hide();
            $("div[role=dialog]").removeAttr('id');
            $("div[role=dialog]").find('#sharefb-drag-handle').remove();
            $("div[role=dialog]").find('.action-close').remove();
        },
        title: ""
    });
    $("div[role=dialog]").attr('id', 'shareToFacebook');
    $("div[role=dialog]").prepend(
        '<div id="sharefb-drag-handle"></div>' +
        '<a class="action-close hidden_link" href="#" title="close" target="_blank">close</a>'
    ).find(".action-close").click(function() {
        $f.dialog('close');
    }).end()
    .draggable({
        handle:'#sharefb-drag-handle',
        containment: 'parent'
    });
}

function report_abuse() {
    var $f = $('#abuseForm');
    $('.active-item-overlay').css({zIndex:1000});

    logClicktale('report_abuse()');
    $f.dialog({
        width: 572,
        height: 335,
        resizable: false,
        modal: false,
        buttons: {
            'cancel': function() {
                $f.dialog('close');
            },
            'report': function() {
                var params = $f.serialize();
                var $val = $f.find('textarea').val();
                if (!$val || $.trim($val) == "") {
                    Plum.ui.alert("Error", "Please type something");
                    return;
                }
                $.post('/closet/abuse', params, function(data) {
                    $f.dialog('close');
                    Plum.ui.alert("Report abuse", "Thanks for your help");
                    $f.find('textarea').val('');
                }, 'json');
            }
        },
        open: function() {
            $('button', $f.parent()).addClass('item-overlay-trigger');
        },
        close: function() {
            $('.active-item-overlay').css({zIndex:10000});
            $('#viewNew').hide();
            $("div[role=dialog]").removeAttr('id');
        },
        title: ""
    });
    $("#abuseForm").find("textarea").focus();
    $("div[role=dialog]").attr('id', 'abuseDialog');
    $("div[role=dialog]").prepend(
        '<div id="poll-drag-handle"></div>' +
        '<a class="action-close hidden_link" href="#" title="close" target="_blank">close</a>'
    ).find(".action-close").click(function() {
        $f.dialog('close');
    }).end()
    .draggable({
        handle:'#poll-drag-handle',
        containment: 'parent'
    });
    return false;
}

/**
 *  Follow PW on Facebook, Notification toggle
 */
$(document).ready(function() {
    $('#toggleNotifyContent .lstActivity li').each(function() {
        var links = $(this).children('a');
        var href = links[links.length-1].href;
        $(this).click(function() {
            document.location = href;
        });
    });
    $('#toggleNotifyContent .lstActivity li').mouseover(function() {
        $(this).addClass('hover');
    });
    $('#toggleNotifyContent .lstActivity li').mouseout(function() {
        $(this).removeClass('hover');
    });
    $('body').click(function() {
        if ($("#toggleNotifyContent").css("display") == "block") {
            $("#toggleNotifyContent").hide('fast');
        }
    });
    var doHide = [];
    $("#toggleNotify").click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if ($(this).is(':visible')) {
            for (var e in doHide) {
                doHide[e].removeClass('unread').addClass('read');
            }
            doHide = [];
        }
        $("#toggleNotifyContent").toggle('fast', function() {});
        $.post("/closet/showNotifications", function() {
            $("#notifyCount").hide();
            $(".unread").each(function() {
                var $this = $(this);
                doHide.push($this);
            });
        });
    });
    $("#toggleNotifyContent .close").click(function(e) {
        e.preventDefault();
        $("#toggleNotify").trigger('click');
    });
    $("#pwFollowFB").click(function() {
        $.get('/closet/followfb', function(data) {
            alert(data);
        }, 'json');
        return false;
    });
    $("#closetof label").click(function(e) {
        if ($(this).hasClass('selected')) {
            return e.preventDefault();
        }
        $("#closetof label").removeClass('selected');
        var id = $(this).addClass('selected').attr('for');
        $("#" + id).attr('checked', 'true');
        $('a#items_movenext, a#outfits_movenext').attr('href', '#');
    });
    $("#admincontrols").draggable({
        handle:$(this),
        containment: [0, -$('#admincontrols').height() + 30, document.width, document.height]
    });
});

function see_all_friends(type) {
    var pathname = window.location.pathname;
    var url = pathname + '?friend=' + type;
    $('.active-item-overlay').remove();
    logClicktale("see_all_friends('" + type +  "')");
    $.get(url, function(html, s) {
        $('<div class="active-item-overlay" id="seeAllFriends"></div>')
                .css({
                    position: 'absolute',
                    display: 'none',
                    zIndex: 10000
                })
                .html(html)
                .delegate('.action-close', 'click', function() {
                    $(this).closest('.active-item-overlay').remove();
                    $(document).unbind('keydown.active-item-overlay');
                    Plum.itemBackhistory = [undefined];
                    $('#enlargeImageOverlay:visible').hide();
                    return false;
                })
                .appendTo('body')
                .position({
                    my: 'left top',
                    at: 'left top',
                    of: window,
                    offset: Plum.config('overlayPosition')||'10 '+(10+$(window).scrollTop()),
                    collision: 'none'
                })
                .draggable({
                    handle:'#overlay-drag-handle',
                    stop: function(e,ui) {Plum.config('overlayPosition',ui.offset.left +' '+ui.offset.top)},
                    containment: 'parent'
                })
                .find('.action-show-detail').bind('click',function() {
                    Plum.itemBackhistory.push(previousItemInOverlay);
                    ++Plum.itemBackhistoryCount;
                });
            $('.active-item-overlay').fadeIn('fast');

            $(document).bind('keydown.active-item-overlay',function(event) {
            if(event.which == '27') {
                    $('.active-item-overlay').remove();
            }
        });
    });
}

var isLoggedIn = true;

/* code to save canvas (and comments) for nonlogged users */
jQuery.cookie = function (key, value, options) {
    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function hasSession() {
    return isLoggedIn;
}

function loginpopup(loginURL) {
    $.preLoadImages('/images/bg.overlay.pre-login.png');
    var msg_header = "Hi! We are so excited to see you, you are just a click away from joining PlumWillow...";
    var msg_body = '<div id="canvasFirstTimeDialog-screenshot"></div>' +
    			   '<div id="canvasFirstTimeDialog-postit"></div>' +
    			   '<span id="alreadyMember">already a member?</span>';
    
    if (typeof loginURL == 'undefined') {
        loginURL = '';
    }
    
    Plum.ui.confirm(msg_header, msg_body, function() {
        fbLogin(loginURL);
    });
    
    // get three buttons
    var b = $("#canvasErrorDialog, #canvasFirstTimeDialog").find("button");
    // set id for each button
    $(b[0]).attr({
        'id': 'btnDialogCancel',
        'title': 'no thanks'
    })
    .children().html('no thanks');
    $(b[1]).attr({
        'id': 'btnDialogSignin',
        'title': 'sign in'
    });
    $(b[2]).attr({
        'id': 'btnDialogSignup',
        'title': 'sign up'
    });
    
    return false;
}

var isFirstTime = false;
function setFirstTimeUser(c) {
    isFirstTime = c;
    if (!c) {
        return;
    }
    
    var loginURL = '';
    $("#fb-login,#loginTop,#loginFull").click(function() {
        return loginpopup(loginURL);
    }).attr('onclick', '');
}

function isFirstTimeUser() {
    return isFirstTime;
}

function user_has_no_session()  {
    isLoggedIn = false;
    var msg_header = "Oops, looks like you're not signed in!";
    var msg_body = "Please click \"sign in\" to access PlumWillow with your Facebook account.";
    var ids = "#comment_text,#btnCommentPost,#favlink,#lnkShare,#btnCommentPost,#wishlink,#lnkMyCloset,#lnkSaveOutfit,#startpoll,.poll label, .startpoll,.poll input[type=radio],.lnkShareSmall, #scavengerHunt_itemBadge";
    // remove click events
    $(ids).unbind('click');
    $(ids).attr('onclick', '');
    // new click events
    $(ids).live('click', function(e) {
        // stat
        e.preventDefault();
        e.stopImmediatePropagation();

        $.post('/closet/showPromptLogin', {e: $(this).attr('id'), u: document.location.pathname});
        //

        var _id = $(this).attr("id");
        if ( isFirstTimeUser() ) {
            msg_body = 'already a member?';
            switch (_id) {
                case "lnkMyCloset":
                    msg_header = "Hi, to view your profile you first need to sign in. You are just a click away from joining PlumWillow...";
                    break;
                case "favlink":
                    msg_header = "Thanks for your style advice. To ♥ this you need to sign in. You are just a click away...";
                    break;
                case "wishlink":
                    msg_header = "To add this item to your wishlist you need to sign in. You are just a click away...";
                    break;
                case "lnkShare":
                    msg_header = "Great idea! To share this you need to sign in. You are just a click away...";
                    break;
                case "lnkSaveOutfit":
                    msg_header = "What a great look! To save this outfit you need to sign in. You are just a click away...";
                    break;
                case "btnCommentPost":
                    msg_header = "Thanks for your style advice. To post your comment you need to sign in. You are just a click away...";
                    var txt = $("#comment_text");
                    if (txt.length == 0) {
                        txt = $("#comment_text_profile");
                    }
                    if ($.trim(txt.val()) == "" || txt.val() == "write comment here...") {
                        alert("Please write something!");
                        txt.focus();
                        return false;
                    }
                    var comment = {
                        text : txt.val(),
                        pid: txt.attr('class').split(/ /).pop(),
                        type: txt.attr('id')
                    };
                    $(document).bind('before_login', function() {
                        $.cookie('before_login_comment', JSON.stringify(comment));
                    });
                    break;
            }
        } else {
            switch (_id) {
                case "favlink":
                    msg_body = "Hi! You need to sign in to ♥ this.....";
                    break;
                case "lnkShare":
                    msg_body = "Hi! You need to sign in to share this with your FB friends.....";
                    break;
                case "lnkSaveOutfit":
                    msg_body = "Hi! You need to sign in to save this outfit....";
                    break;
                case "btnCommentPost":
                    msg_body = "Hi! You need to sign in before you can post that comment....";
                    var txt = $("#comment_text");
                    if (txt.length == 0) {
                        txt = $("#comment_text_profile");
                    }
                    if ($.trim(txt.val()) == "" || txt.val() == "write comment here...") {
                        alert("Please write something!");
                        txt.focus();
                        return false;
                    }
                    var comment = {
                        text : txt.val(),
                        pid: txt.attr('class').split(/ /).pop(),
                        type: txt.attr('id')
                    };
                    $(document).bind('before_login', function() {
                        $.cookie('before_login_comment', JSON.stringify(comment));
                    });
                    break;
            }
        }

        showLoginPopup(msg_header, msg_body);
        return false;
    });
}

function showLoginPopup(msg_header, msg_body) {
    $('#canvasErrorDialog').remove();
    $('#canvasFirstTimeDialog').remove();

    if (isFirstTimeUser()) {
        // first time user has a diff dialog, so we use the
        // header as its body
        msg_header = msg_body != 'already a member?' ? msg_body : msg_header;
        msg_body   = '<div id="canvasFirstTimeDialog-screenshot"></div>' +
    			   '<div id="canvasFirstTimeDialog-postit"></div>' +
    			   '<span id="alreadyMember">already a member?</span>';
    }

    Plum.ui.confirm(msg_header, msg_body, function() {
        $(document).trigger('before_login');
        fbLogin();
    });
    // get three buttons
    var b = $("#canvasErrorDialog, #canvasFirstTimeDialog").find("button");
    // set id for each button
    $(b[0]).attr({
    'id': 'btnDialogCancel',
    'title': 'no thanks'
    })
    .children().html('no thanks');
    $(b[1]).attr({
    'id': 'btnDialogSignin',
    'title': 'sign in'
    });
    $(b[2]).attr({
    'id': 'btnDialogSignup',
    'title': 'sign up'
    });
    return false;
}

$(document).ready(function() {
    $(document).bind('before_login', function() {
        var vote = $(".vote").find("input:radio:checked");
        if (vote.length == 0) {
            return;
        }
        $.cookie('before_login_poll', JSON.stringify({
            type: 'poll',
            id:   vote.parents("div.poll").attr('id'),
            vote: vote.val()
        }));
    });
    var f = $.cookie("before_login_poll");
    if (f) {
        try {
            var obj = JSON.parse(f);
            if (typeof obj == "object" && obj.type == "poll") {
                setTimeout(function() {
                    $('#'  + obj.id).find("input:radio[value=" + obj.vote + "]").attr('checked', true).parents("form").submit();
                }, 1000);
                document.location.hash = obj.id;
            }
        } catch (e) {}
    }
    $.cookie("before_login_poll", null);
});

$(document).ready(function() {
    var f = $.cookie("before_login_comment");
    if (!f) { return; }
    try {
        var obj = JSON.parse(f);
        if (typeof obj == "object") {
            var txtarea = $("#" + obj.type);
            if (txtarea.attr('class').split(/ /).pop() == obj.pid) {
                txtarea.val( obj.text );
                $("#btnCommentPost").trigger('click');
            }
        }
    } catch (e) {}
    $.cookie("before_login_comment", null);
});

function CTIsPlayback() {
    try {
        return parent && parent.WebPlayer;
    } catch(e) {
        return false;
    }
}

var _CTEBuffer = '';
function _SplitClickTaleExec(str) {
    //ClickTaleExec has a 512 char limit. We lose 15 bytes for the buffer append.
    var limit = 512 - 20;

    ClickTaleExec("_CTEBuffer = ''");

    var tmp, lim;
    var x = 0;
    while (x < str.length) {
        lim = limit;
        while (1) {
            tmp = str.slice(x, x + lim).replace(/(['\\])/g, "\\$1");

            if(tmp.length > limit) {
                lim -= (tmp.length - limit);
            } else {
                break;
            }
        }

        ClickTaleExec("_CTEBuffer+='" + tmp + "'");
        x += lim;
    }

    ClickTaleExec('eval(_CTEBuffer);');
}

function logClicktale(type) {
    if(typeof ClickTaleExec=='function') {
        if (type.length > 200) {
            _SplitClickTaleExec(type);
        } else {
            ClickTaleExec(type);
        }
    }
}

/**
 * fbLogin 
 * 
 * @TODO this is the _ONLY_ function to call popup
 * @param inURL $inURL 
 * @access public
 * @return void
 */
function fbLogin(inURL) {
    if (top.location.href.match(/fb_xd_fragment/)) {
        return;
    }

    var url;
    
    if (typeof inURL != 'undefined' && inURL) {
        url = inURL;
    } else {
        url = $("#fb-login").attr("href");
    }
    
    var obj = popup(url, {"height": 300, "width": 500, "returnobject" : 1});
    if (obj == false) {
        return true;
    }

    return false;
}


$(function() {

    var editPoll;
    $("div .poll").find(".edit, .delete").click(function(e) {
        e.preventDefault();
        if (!confirm("Are you sure? All votes will be lost.")) {
            return false;
        }
        editPoll = $(this).parent().parent().find('input[name=id]').val();
        var action  = $(this).html().toLowerCase() == 'delete' ? 'delete' : 'edit';
        if (action == 'delete') {
            $.post('/closet/deletePoll',  {id:editPoll}, function() {
                document.location.href = document.location.href;
                editPoll=null;
            }, 'json');
            return false;
        }
        var t = $(this).parent().parent();
        var options = t.find('.option');
        var title   = t.find('h2').find('span').html().replace(/<a.+$/, '');
        var expires = t.find('input[name=expires]').val();
        $(".startpoll").trigger('click');

        default_values['poll'] = $("#poll").val();

        var x = $("#createPoll").find('input[name=poll]').val(title);

        $("#pollMultiple").trigger('click');
        for (var i=0; i < options.length; i++) {
            $('#poll_' + i).val( $(options[i]).html().replace(/(<span.+span>)/g, '') );
        }

        $("select[name=expires]").find('option[value=' + expires + ']').
            attr('selected', true);
        $("#createPollModal input").css({
            'color': '#000',
            'font-style': 'normal'
        });
        return false;
    });

    var default_values = new Array();
    $(".startpoll").click(function() {

        if (!hasSession()) {
            return false;
        }
        $(".ui-dialog-content:visible").dialog('close');
        var isEditPoll;
        var $f = $('#createPoll');
        if (editPoll) {
            isEditPoll = editPoll;
            editPoll   = null;
        } else {
            $f.each(function() {
                this.reset();
            });
        }
        $f.dialog({
            width: 572,
            height: 335,
            resizable: false,
            modal: false,
            buttons: {
                'cancel': function() {
                    $f.dialog('close');
                },
                'share': function() {
                    var data = $f;
                    Plum.request('poll.create', [data, isEditPoll]);
                }
            },
            open: function() {
                $('button', $f.parent()).addClass('item-overlay-trigger');
            },
            close: function() {
                $('.active-item-overlay').css({zIndex:10000});
                $('#viewNew').hide();
                $("#createPollModal").find('#poll-drag-handle').remove();
                $("#createPollModal").find('.action-close').remove();
                $("#createPollModal").removeAttr('id');
            },
            title: ""
        });
        $("div[role=dialog]").attr('id', 'createPollModal');
        $("#createPollModal").prepend(
            '<div id="poll-drag-handle"></div>' +
            '<a class="action-close hidden_link" href="#" title="close">close</a>' +
            '<h1>Create a Poll</h1>'
        ).draggable({
            handle:'#poll-drag-handle',
            containment: 'parent'
        }).find(".action-close").click(function() {
            $f.dialog('close');
        }).end()
        .find("button:first").attr({'id': 'btnPollClose', 'title': 'cancel'})
        .end()
        .find("button:last").attr({'id': 'btnPollPublish', 'title': 'publish poll'})
        .end();

        // JS Hack since our form library doesn't support palcerholder
        $("#poll").attr('placeholder', "Can I wear this on a date?").blur();
        $("#poll_0").attr('placeholder', "Yes, it is stylish and fun.");
        $("#poll_1").attr('placeholder', "No way, it's too dressy.");

        if (!$('html').hasClass('placeholder')) {
          Plum.loadJs(
              '/js/lib/jquery.addplaceholder.min.js',
              function() {
                $('#poll,#poll_0,#poll_1').addPlaceholder();
              }
          );
        }

        return false;
    });
});

Plum.subscribe('poll.create', function(args) {
    var elements = args[0];
    var isEdit   = args[1];
    var check = {"poll": "The poll", "poll_0":"Answer #1", "poll_1": "Answer #2"};
    for (var i in check) {
        if ($.trim($("#" + i, elements).css("font-style")) == "italic" || $.trim($("#" + i, elements).val()) == "") {
            Plum.ui.alert("Sorry", "You must enter a poll question and at least 2 answers.");
            $("#canvasErrorDialog .ui-dialog-buttonpane button")
            .css({
                'background' : '#ccc',
                'height' : 'auto',
                'text-indent' : 0,
                'right' : '16px',
                'top' : '5px',
                'border' : '1px outset #ccc'
            });
            return;
        }
    }
    var params = elements.serialize();
    if (isEdit) {
        params += '&editid=' + isEdit;
    }
    $.post('/closet/createPoll', params, function(data) {
        if (data.done) {
            elements[0].reset();
            elements.dialog('close');
            Plum.ui.alert("Okay", "Your poll was created!");
            setTimeout(function() {
                // defered redirect
                var url = document.location.href;
                url = url.replace(/#.+/, '');
                url = url.replace(/[?&]ts=[0-9]+/, '');
                url = (url.indexOf('?') == -1 ? '?' : '&') + "ts=" + (new Date()).getTime();
                document.location.href = url;
            }, 1000);
        } else {
            if (data.error) {
                Plum.ui.alert("Error", data.error);
            } else {
                Plum.ui.alert("Error", "Internal error, please resubmit the form");
            }
        }
    }, 'json');
});

$(document).ready(function() {
    $(".poll label").click(function() {
        if (!hasSession()) {
            return false;
        }
        $("#" +  $(this).attr('for')).attr('checked', true);
        $(this).parents("form").submit();
    });
    $(".poll form").submit(function(e) {
        var post = $(this).serialize();
        var div  = $(this).parent();
        $.post($(this).attr('action'), post, function(data) {
            div.replaceWith ( data );
        });
        return false;
    });
    $(".poll input[type=radio]").click(function() {
        if (!hasSession()) {
            return false;
        }
        $(this).parents("form").submit();
    });
    $("#store_add").click(function() {
        var that  = $("#store_list");
        var name  = that.find(':selected').val();
        var value = ($("#favStoreBrands").val() + ", " + name).split(",");
        var val = "", t = {};
        for (var i in value) {
            var v = $.trim(value[i]).toLowerCase();
            if (v == "" || t[v]) {
                continue;
            }
            val += v + ", ";
            t[v] = true;
        }

        $("#favStoreBrands").val(val);
        that.find(':selected').removeAttr('selected').end()
            .find('option:first').attr('selected', true);
    });

    var buyGoalURL = "/goal/buy";
    var tmp; // buylink is triggered twice on overlay (jquery bug?)
    function goalBuy(e) {
        e.stopPropagation();
        if (typeof _gaq == "undefined") {
            return true;
        }
        if ($(this).parents("#overlay-tabs").length) {
            if (tmp == $(this).attr('href')) {
                _gaq.push(["_trackPageview", buyGoalURL]);
            }
            tmp = $(this).attr('href');
        } else {
           _gaq.push(["_trackPageview", buyGoalURL]);
        }
        return true;
    }
    $('.buy').live('click', goalBuy);
    $('.buylink').live('click', goalBuy);
});

function fbShare2(obj) {
    var defObj = {
        method: "feed"
        //, display: "popup"
    };

    var checkIflogged = $("#fb-login");
    if(checkIflogged.length>0) { //not logged
        checkIflogged.trigger("click");
        return false;
    };

    obj = $.extend(defObj, obj);

    FB.ui(obj, function(response) {
        if (response && response.post_id) {
            obj['id'] = response.post_id;
            // keep in track of shares
            //$.post("/post/", obj);
        }
    });
}

function checkNotIframe() {
    if (CTIsPlayback()) {
        return;
    }
    
    try {
        if (top.location.href.match(/fb_xd_fragment/)) {
            return;
        }

        if (top.location.href != window.location.href) {
            top.location.href = window.location.href;
        }
    } catch (e) {
        top.location.href = window.location.href;
    }
}

function createModalWindow(opts) {
    if (!opts.duplicate && $("#" + opts.id).length) {
        return;
    }
    $('.active-item-overlay').css({zIndex:1000});
    var elem = $(opts.html);
    if (!opts.buttons) {
        opts.buttons = {};
    }
    elem.dialog({
        width: opts.width || 572,
        height: opts.height || 335,
        resizablea: opts.resizablea || false,
        modal: opts.modal ||  false,
        buttons: elem.buttons,
        open: function() {
            $('button', elem.parent()).addClass('item-overlay-trigger');
            $('select', elem).show();
        },
        close: function() {
            $('.active-item-overlay').css({zIndex:10000});
            $('#viewNew').hide();
            $("div[role=dialog]").removeAttr('id');
            $("div[role=dialog]").find('#sharefb-drag-handle').remove();
            $("div[role=dialog]").find('.action-close').remove();
            // not sure about this, please test!
            $("div[role=dialog]").remove();
        },
        title: ""
    });
    $("div[role=dialog]").attr('id', opts.id);
    if (opts.classname) {
        $("div[role=dialog]").attr('class', opts.classname);
    }
    $("div[role=dialog]").prepend(
        '<div id="drag-handle"></div>' +
        '<a class="action-close hidden_link" href="#" title="close" target="_blank">close</a>'
    ).find(".action-close").click(function() {
        elem.dialog('close');
    }).end()
    .draggable({
        handle:'#drag-handle',
        containment: 'parent'
    });
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

function message_setHidden(type, key, hidden) {
    jQuery.ajax({
        url: '/message/setHidden',
        'type': 'POST',
        dataType: 'json',
        data: {
						'type': type,
            'key': key,
            'hidden': hidden
        },
        
        success: function(data) {
            if (key == 'scavengerHunt') {
            		$('div.scavengerHuntMessage').hide();
            }
        }
    });
}

function scavengerHunt_loginButton(loginURL) {
    $('#canvasErrorDialog').remove();
    return loginpopup(loginURL);
}

function scavengerHunt_userNotification() {
    var data = _scavengerHunt_notificationData;
    
    Plum.ui.alert('Scavenger Hunt', data.message, null, {'class': data.msgClass});
    
    if($(".more-content").length > 0) {
      $(".more-content").parent().hover(function() {
          var clue = $(".more-content").parent();
          $(".full-content")
                              .css( { "left": clue.position().left + "px", "top": clue.position().top + "px", "min-height": clue.height() + "px" } )
                              .width( clue.width() )
                              .css("display", "block");
        }, 
        function() {
          $(".full-content").css("display", "none");
        }
      );
      
      $("#canvasErrorDialog").css("overflow", "visible");
    }
    

}

$('#productNavLink').live('click', function() {
    var object = $('.overlay-wrapper');
    object.show();
    $('body').css('overflow', 'hidden');
    $(window).keyup(function(e) {
        if (e.which == 27 && object.is(':visible')) {
            object.hide();
            $('body').css('overflow', '');
        }
    });
    return false;
});

/* to show the top drowndown */
$(document).ready(function() {
	$('#topMyProfile').click(function(event){
		event.preventDefault();
		$('#topDrownDown').slideToggle('fast');
	});
});

// $(function() {
//     if (!$("#fb-login,#loginFull").length || !document.location.hash) {
//         return;
//     }
//     $.post("/redirect/getLoginURL", {next:document.location.href}, function(response) {
//         if (typeof response.url != "undefined") {
//             $("#fb-login,#loginFull").attr("href", response.url);
//         }
//     });
//     return;
//     /* doesnt work */
//     $("#fb-login,#loginFull").each(function() {
//         var url = $(this).attr("href").split("?");
//         if (url[1]) {
//             var re = /([^&=]+)=([^&]*)/g, m, queryString = url[1], result = {};
//             while (m = re.exec(queryString)) {
//                 result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
//             }
//             result.redirect_uri += encodeURIComponent(document.location.hash);
//             url[1] = "";
//             for(var i in result) {
//                 url[1] += encodeURIComponent(i) + "=" + encodeURIComponent(result[i]) + "&";
//             }
//             $(this).attr("href", url[0] + '?' + url[1]);
//         }
//     });
// });

