/**
 * share - handle share related functionality 
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var share = window.gs.share = {
        // default options/settings
        numChecked: 0,
        selectedSongs: [],
        
        empty: null
    };
    
    share.init = function() {
        // initialize default actions
        // search form
        share.initSearch();
        share.initExportToWidget();
        // init color picker, sliders
        //share.initSliders();
        
        // facebook
        share.initFacebookConnect();
    };
    share.initSearch = function() {
        var postFormSubmit = function(json) {
            debug('after meta form submit', json);
            if(json.html) {
                $('div.results').html(json.html);
            } else {
                debug('error');
            }
        };
        var options = {
            success: postFormSubmit,
            dataType: 'json'
        }
        $('form.search').ajaxForm(options);
    };
    share.initExportToWidget = function() {
        $('form.exportToWidget').submit(function() {
            if(!share.selectedSongs.length) {
                return false;
            }
            var type = (share.selectedSongs.length>1) ? 0 : 1;
            var songs = share.selectedSongs.join(',');
            $(this).children('.type').val(type);
            $(this).children('.songs').val(songs);
        });
    }

    share.toggleCheckAll = function(obj, isChecked) {
        if(!obj) { return false; }
        // get all checkboxes and check them
        //debug('toggle all', obj, isChecked);
        share.selectedSongs = share.selectedSongs || [];
        var container = $(obj).parent().siblings('.songs'), numChecked = 0;
        $('li .checkbox input',container).each(function() {
            //this.checked = isChecked;
            if(!this.checked) {
                this.checked = isChecked;
                share.selectedSongs.push(this.value); 
            } else {
                this.checked = isChecked;
            }
            numChecked++;
        });
        if(!isChecked) {
            // reset array 
            share.selectedSongs = [];
        }
        debug('after toggleselect checked', share.selectedSongs);

        return false;
    }
    share.itemChecked = function(obj) {
        // depending of whether checked, set counter and update arr
        var container = $(obj).parent().parent().parent().parent();
        var albumHash = container.attr('value');
        share.selectedSongs = share.selectedSongs || [];
        //debug('item is checked: ',obj, obj.checked, share.selectedSongs);
        //debug('curr num:', numChecked);
        if(obj.checked) {
            share.selectedSongs.push(obj.value);
        } else {
            share.selectedSongs.remove(share.selectedSongs.indexOf(obj.value));
        }
        //debug('after item checked', share.selectedSongs);
    }

    share.initTinysongLightbox = function(songID) {
        // create modal box
        var options = {
            ajax: '/lightboxes/tinysong?songID='+songID
        };
        var divinfo = {
            newid: 'tinysongBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    }

    share.initSongWidgetLightbox = function(songID) {
        // create modal box
        var options = {
            ajax: '/lightboxes/songWidget?songID='+songID
        };
        var divinfo = {
            newid: 'widgetBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    }

    share.addSelectedSongs = function() {
        debug('add selectedsongs', share.selectedSongs);
        share.addSongs(share.selectedSongs.join('-'));
        share.toggleCheckAll($('#toggleSelectedTop'), false);
        return false;
    } 

    share.initSliders = function()
    {
        // Set up the sliders
        var sliderTimer = null;
        var sliderWait = 750;
        var widthSlider = $("#widthSlider").slider({min:150,max:1000,
                value: $("#widthInputField").attr('value'),
                slide: function(e,ui){
                    //debug(ui);
                    var newLeft;
                    if(ui.value==0) {
                        var left = $("#widthInputField").attr('value');
                        var width = $("#widthSlider").show().width();
                        newLeft = 250 * left / 1000;
                        //debug('width', $(ui.handle, this).css('left', newLeft), this, newLeft, left, width);
                    } else {
                        newLeft = ui.value;
                    }
                    newLeft = parseInt(newLeft);
                    $("#widthInputField").attr('value', newLeft);
                    clearTimeout(sliderTimer);
                    sliderTimer = setTimeout(function() {
                        gs.share.refreshPreview();
                        return false;
                    }, sliderWait);
                }
        });
        
        var heightSlider = $("#heightSlider").slider({
            min:150,max:1000,
            value:$("#heightInputField").attr('value'),
            slide:function(e,ui){
                //debug(ui);
                var newLeft;
                if(ui.value==0) {
                    var left = $("#heightInputField").attr('value');
                    var width = $("#heightSlider").show().width();
                    newLeft = 250 * left / 1000;
                    //debug('height', $(ui.handle, this).css('left', newLeft), this, newLeft, left, width);
                } else {
                    newLeft = ui.value;
                }
                newLeft = parseInt(newLeft);
                $("#heightInputField").attr('value', newLeft);
                clearTimeout(sliderTimer);
                sliderTimer = setTimeout(function() {
                    gs.share.refreshPreview();
                    return false;
                }, sliderWait);
            }
        });
        // Allow for manual changes
        $("#widthInputField").change(function(){
             widthSlider.slider('moveTo',$(this).attr('value'));
        });
        $("#heightInputField").change(function(){
             heightSlider.slider('moveTo',$(this).attr('value'));
        });
        debug('sliders', heightSlider, widthSlider, $('#heightInputField').get(0), $('#widthInputField').get(0));
    }
        
    share.refreshPreview = function()
    {
        debug('refresh preview');
        clearTimeout(gs.share.formRefreshTimeout);
        gs.share.formRefreshTimeout = setTimeout(function() {
            $("#configWidget").ajaxSubmit({data:{getEmbedCode:1}, dataType:'text',
                error: function() { debug(arguments); },
                success: function(result) {
                    var form = $("#configWidget").get(0), width = 0, maxWidth = 0;
                    if(form && form.w) {
                        width = form.w.value;
                    }
                    if(form && form.MAX_WIDTH) {
                        maxWidth = form.MAX_WIDTH.value;
                    }
                    if(width > maxWidth) {
                        $('#widgetNote').show();
                    } else {
                        $('#widgetNote').hide();
                    }
                    if($('#widgetPlaylist').length) {
                        // for reordering songs, flash updates too often, no every 10sec delay
                        clearTimeout(gs.share.shareRefreshTimeout);
                        gs.share.shareRefreshTimeout = setTimeout(function() {
                            $("#widgetPreviewWrapper").empty().html(result);
                        }, gs.share.shareRefreshDuration);
                    } else {
                        $("#widgetPreviewWrapper").empty().html(result);
                    }
                    
                    clearTimeout(gs.share.formRefreshTimeout);
                }
            });
        }, gs.share.formRefreshDuration);
    }

    share.exportToWidgets = function(obj) {
        debug('export list to widgets', share.selectedSongs);
        if(!share.selectedSongs.length) {
            return false;
        }
        var type = (share.selectedSongs.length>1) ? 0 : 1;
        var songs = share.selectedSongs.join(',');
        debug('type: then songs', type, songs, obj);
        $(obj).siblings('.type').val(type);
        $(obj).siblings('.songs').val(songs);
        return false;
    }

    share.imageListOut = function(obj) {
        // do nothing
    }
    share.imageListOver = function(obj) {
         $(obj).parent().siblings().children('.active').removeClass('active');
                 $(obj).addClass('active');
         var className = obj.className.replace('active','');
         $('#descriptionList .'+className).addClass('active').siblings().removeClass('active');
    }
    
    // initialize facebook's cross-domain controller
    // and our "facebookInfo" div
    share.initFacebookConnect = function() {
        if(window.FB && window.FB.Bootstrap) {
            FB.Bootstrap.requireFeatures(["Connect"], function() {
                FB.init('8f05c9ccd4c63a08ef2bd0f492174734','xd_receiver_ssl.htm');
                
                FB.ensureInit(function() {
                    share.facebookInfoUpdate();
                });
            });
        }
    }

    // update facebookInfo div with accurate information
    share.facebookInfoUpdate = function() {
        FB.ensureInit(function() {
            var sequencer = new FB.BatchSequencer();
            var fbUID     = FB.Facebook.apiClient.users_getLoggedInUser(sequencer);

            sequencer.execute(function() {
                if (fbUID.result > 0) {
                    var facebookHTML = "<fb:profile-pic uid=\"" + fbUID.result + "\" facebook-logo=\"true\" linked=\"false\"></fb:profile-pic>";
                    facebookHTML += "<fb:login-button size=\"small\" autologoutlink=\"true\" length=\"short\"></fb:login-button>";
                    $('#facebookInfo').html(facebookHTML);
                    FB.XFBML.Host.parseDomTree();
                } else {
                    $('#facebookInfo').html('');
                }
            });
        });
    }
    
    // show a feed publisher form
    share.showFeedForm = function(songID) {
        var params = {'songID': songID};

        $.getJSON('/catalogue/facebookFeed.json', params, function(json) {
            if (json.error != '') {
                debug("Something went incredibly wrong.  Please reload this page.\n" + json.error);
                return;
            }
            
            FB.ensureInit(function() {
                FB.Connect.showFeedDialog(101334511800, json.feed, null, null, null, FB.RequireConnect.promptConnect, null, 'Leave A Message', {value:'put your message here...'});
                if ($('#facebookInfo').children().length < 2) {
                    share.facebookInfoUpdate();
                }
            });
        });
    }

})();
