/**
 * widget Javascript
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var widget = window.gs.widget = {
        // variables
        featuredHash: [],
        colorMap: [],
        boo: 1,
        widgetid: 0,
        
        formRefreshTimeout: null,
        formRefreshDuration: 750,
        
        widgetRefreshTimeout: null,
        widgetRefreshDuration: 5000,
        
        sliderThemeCheck: [],
        
        empty: null
    }
    
    widget.init = function(opts)
    {
        widget.initColorPicker();
        widget.initFeaturedColors();
        widget.initNameForm();
        widget.initNewsletterForm();
        var wform = $('#configWidget').get(0);
        if($('#configWidget').length) {
            $('#configWidget input').each(function() {
                if(this.className.match('noEnterSubmit')) {
                    this.onkeydown = function(event) {
                        event = event || window.event;
                        var key = (event.charCode) ? event.charCode : ((event.keyCode) ? event.keyCode : ((event.which) ? event.which : 0));
                        //debug(event);
                        if(key==13) {
                            if($(this).parents('#configWidgetSingle').length) {
                                //gs.widget.refreshSinglePreview();
                                $('#configWidgetSingle input').change();
                            } else {
                                //gs.widget.refreshPreview();
                                $('#configWidget input').change();
                            }
                            $(this).siblings('.colorEx').css('backgroundColor', '#' + this.value);
                            $(this).blur();
                            return false;
                        }
                        
                    }
                }
            });
        }
    }
    
    widget.setFeaturedHash = function(hash)
    {
        widget.featuredHash = hash;
    }
    
    widget.setColorMap = function(map)
    {
        widget.colorMap = map;
    }
    
    widget.initNewsletterForm = function() {
        var preFormSubmit = function(data, form, options) {
            if($('#newsletterEmail').val()=='') {
                return false;
            }
        };
        
        var postFormSubmit = function(response) {
            if(response.Code) {
                // put success here
                $('#noWidgetsFound ul li:first .field.large').html('<span>'+response.Message+'</span>');
                $("#noWidgetsFound ul .error").hide();
            } else {
                // put empty result message here
                $("#noWidgetsFound ul .error").html(response.Message).show();
            }
        };
        
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        };
        $("#newsletterForm").ajaxForm(options);
    }
    
    widget.initNameForm = function() {
        var preFormSubmit = function(data, form, options) {
            var nkey;
            for(var key in data) {
                if(data[key].name=='name') {
                    nkey = key;
                    break;
                }
            }
            if(data[nkey].value=='') {
                // error message here???
                return false;
            }
        };
        
        var postFormSubmit = function(response) {
            if(response.Code) {
                // put success here
                gs.login.showForm();
            } else {
                // put empty result message here
                $("#playlistError").html("Error saving playlist").show();
            }
        };
        
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        };
        $("#widgetNameForm").ajaxForm(options);
    };
    
    widget.refreshPreview = function()
    {
        debug('refresh preview');
        clearTimeout(gs.widget.formRefreshTimeout);
        gs.widget.formRefreshTimeout = setTimeout(function() {
            $("#configWidget").ajaxSubmit({data:{getEmbedCode:1}, dataType:'text',
                error: function() { debug(arguments); },
                success: function(result) {
                    gs.widget.showPreviews();
                    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.widget.widgetRefreshTimeout);
                        gs.widget.widgetRefreshTimeout = setTimeout(function() {
                            $("#widgetPreviewWrapper").empty().html(result);
                        }, gs.widget.widgetRefreshDuration);
                    } else {
                        $("#widgetPreviewWrapper").empty().html(result);
                    }
                    
                    //clearTimeout(gs.widget.formRefreshTimeout);
                }
            });
        }, gs.widget.formRefreshDuration);
    }
    
    widget.refreshSinglePreview = function()
    {
        debug('refrsh single prev');
        clearTimeout(gs.widget.formRefreshTimeout);
        gs.widget.formRefreshTimeout = setTimeout(function() {
            $("#configWidgetSingle").ajaxSubmit({url:'add_songs?getEmbedCode&widgetid='+gs.widget.widgetid, dataType:'text',
                error: function() { debug(arguments); },
                success: function(result) {
                    var width = $("#configWidgetSingle").get(0).w.value;
                    var maxWidth = $("#configWidgetSingle").get(0).MAX_WIDTH.value;
                    if(width > maxWidth) {
                        $('#singleWidgetNote').show();
                    } else {
                        $('#singleWidgetNote').hide();
                    }
                    $("#singleSongPreviewWrapper").empty().html(result);
                    clearTimeout(gs.widget.formRefreshTimeout);
                }
            });
        }, gs.widget.formRefreshDuration); 
    }
    
    widget.setSingleWidgetTheme = function(theme, obj)
    {
        $(obj).parent().parent().children().removeClass('active');
        $(obj).parent().addClass('active');
        $('#themeInputField').val(theme);
        widget.refreshSinglePreview();
    }
    
    widget.submit = function()
    {
        if($('#songCount').length) {
            if(parseInt($('#songCount').text()) <= 0 ) {
                return false;
            }
        }
        $("#configWidget").submit();
        $("#widgetButtonSubmit").click();
    }
    
    widget.submitNameForm = function()
    {
        $("#widgetNameForm").submit();
    }
    
    widget.formSuccess = function(result)
    {
        $("#widgetPreviewWrapper").empty().html(result);
    }
    
    widget.setType = function(type)
    {
        $.post('/make?action=settype&widgetid='+widget.widgetid+'&type='+type);
    }
   
    widget.showPreviews = function()
    {
        $('#singleSongPreviewWrapper,#widgetPreviewWrapper').css('visibility','visible');
    }

    widget.hidePreviews = function()
    {
        $('#singleSongPreviewWrapper,#widgetPreviewWrapper').css('visibility','hidden');
    }

    widget.removeConfirm = function(widgetID)
    {
        var options = {
            ajax: '/my_widgets?delete=1&confirm=1&widgetid='+widgetID,
            onHide: function(hash) {
                gs.widget.showPreviews();
                gs.modal_hide(hash);
            },
            onShow: function(hash) {
                gs.widget.hidePreviews();
                gs.modal_show(hash);
            }
        };
        var divinfo = {
            newid: 'removeConfirm',
            newclass: 'results'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
    }
    
    widget.remove = function(widgetID)
    {
        $('#deleteConfirmProcessing').show();
        $.post('/my_widgets?delete=1&widgetid='+widgetID, function(json) {
            gs.lbFactory.disposeModalBox($("#removeConfirm"));
            $('#'+widgetID);
            $('#'+widgetID).fadeOut();
        });
    }
    
    widget.viewAllSongs = function(obj, self)
    {
        $(obj).children().show();
        $(self).parent().children().toggle();
    }
    
    widget.hideSomeSongs = function(obj, self)
    {
        $(obj).children().hide();
        $(obj).children(':not(.hide)').show();
        $(self).parent().children().toggle();
    }
    
    widget.initFeaturedColors = function()
    {
        $('#customColorsSelect').change(function() {
            var w = gs.widget;
            var colors = w.featuredHash[this.value];
            var base = w.colorMap.baseColors;
            var prim = w.colorMap.primaryColors;
            var sec  = w.colorMap.secondaryColors;
            
            $('#baseColorInput').val(colors[base[0]]).siblings('.colorEx').css('backgroundColor', '#'+colors[base[0]]);
            for(var i=0; i<base.length; i++) {
                $('#'+base[i]+'Input').val(colors[base[i]]).siblings('.colorEx').css('backgroundColor', '#'+colors[base[i]]);
            }
            $('#primaryColorInput').val(colors[prim[0]]).siblings('.colorEx').css('backgroundColor', '#'+colors[prim[0]]);
            for(var i=0; i<prim.length; i++) {
                $('#'+prim[i]+'Input').val(colors[prim[i]]).siblings('.colorEx').css('backgroundColor', '#'+colors[prim[i]]);
            }
            $('#secondaryColorInput').val(colors[sec[0]]).siblings('.colorEx').css('backgroundColor', '#'+colors[sec[0]]);
            for(var i=0; i<sec.length; i++) {
                $('#'+sec[i]+'Input').val(colors[sec[i]]).siblings('.colorEx').css('backgroundColor', '#'+colors[sec[i]]);
            }
            gs.widget.refreshPreview();
        });
    }
    
    widget.showFormByType = function(type)
    {
        var obj, objHash;
        if(typeof type == 'string' || typeof type == 'number') {
            objHash = '#theme-'+type;
            obj = $(objHash);
        } else {
            obj = $(type);
            objHash = $(obj).text();
            if(!obj.length) {
                // not a valid type
                return;
            }
        }
        obj.parent().children().hide();
        obj.show();
        
        // make sure when hidden, grab latest stuff
        if(!widget.sliderThemeCheck[objHash]) {
            $('div.ui-slider', obj).each(function() {
                if($(this).slider('value',0)==0) {
                    var input = $(this).siblings('.field').children('input').get(0);
                    var value = $(input).val();
                    if(value) {
                        $(this).slider('moveTo', value, 0);
                    }
                }
            });
            widget.sliderThemeCheck[objHash] = true;
        }
    }
    
    widget.initColorPicker = function()
    {
        // Set up the sliders
        var sliderTimer = null;
        var sliderWait = 750;
        var widthSlider = $("#widthSlider").slider({min:150,max:1000,
                startValue: $("#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.widget.refreshPreview();
                        return false;
                    }, sliderWait);
                }
        });
        
        var heightSlider = $("#heightSlider").slider({min:150,max:1000,
                startValue:$("#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.widget.refreshPreview();
                        return false;
                    }, sliderWait);
                }
        });
        
        // for single song
        var singleWidthSlider = $("#singleWidthSlider").show().slider({min:150,max:1000,
                startValue: $("#singleWidthInputField").attr('value'),
                slide: function(e,ui){
                    //debug(ui);
                    var newLeft;
                    if(ui.value==0) {
                        var left = $("#singleWidthInputField").attr('value');
                        var width = $("#singleWidthSlider").show().width();
                        newLeft = 265 * left / 1000;
                        //debug('single', $(ui.handle, this).css('left', newLeft), this, newLeft, left, width);
                    } else {
                        newLeft = ui.value;
                    }
                    newLeft = parseInt(newLeft);
                    $("#singleWidthInputField").attr('value', newLeft);
                    $("#singleSongWidth").attr('value', newLeft);
                    clearTimeout(sliderTimer);
                    sliderTimer = setTimeout(function() {
                        gs.widget.refreshSinglePreview();
                        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'));
        });
        // for single song
        $("#singleWidthInputField").change(function(){
             singleWidthSlider.slider('moveTo',$(this).attr('value'));
             debug(this, singleWidthSlider);
        });
        /*
        setTimeout(function() {
            debug($("#singleWidthInputField").attr('value'), $("#widthInputField").attr('value').toString(), $("#heightInputField").attr('value').toString());
            $("#widthSlider").slider('moveTo', $("#widthInputField").attr('value').toString(), 0);
            $("#heightSlider").slider('moveTo', $("#heightInputField").attr('value').toString(), 0);
            $("#singleWidthSlider").slider('moveTo', $("#singleWidthInputField").attr('value').toString(), 0);
        }, 500);
        //*/
        // Switch between simple and advanced colors
        $('#simpleButton').click(function(){
            $(this).addClass('active');
            $('#advancedButton').removeClass('active');
            $('#detailedView').hide();
            $('#simpleView').show();
        });
        
        $('#advancedButton').click(function(){
            $(this).addClass('active');
            $('#simpleButton').removeClass('active');
            $('#detailedView').show();
            $('#simpleView').hide();
        });
        
        // The simple settings affect the advanced
        $('#baseColorInput').change(function(){
            $('input.base').attr('value', $(this).val()).siblings('.colorEx').css('backgroundColor', '#' + $(this).attr('value'));
        });
        $('#primaryColorInput').change(function(){
            $('input.primary').attr('value', $(this).val()).siblings('.colorEx').css('backgroundColor', '#' + $(this).attr('value'));
        });
        $('#secondaryColorInput').change(function(){
            $('input.secondary').attr('value', $(this).val()).siblings('.colorEx').css('backgroundColor', '#' + $(this).attr('value'));
        });
        
        // Tie the buttons to the color picker
        /**
         * b/c of retarded order of operation, you have to keep track of last button, and 
         * whether you just ran the show method.
         * this is to make sure that all of the different hide conditions are met without
         * having to change the default behavior of the color picker
         */
        var lastButton = null;
        var justDidShow = false;
        $('button.colorPicker').each(function(i){
            var button = $(this);
            
            $(this).ColorPicker({
                onHide: function(colorPicker){
                    if(justDidShow) {
                        lastButton.removeClass('isopen');
                    }
                    button.removeClass('active');
                    $(colorPicker).slideUp(500);
                    justDidShow = false;
                    return false;
                },
                onShow: function (colorPicker){
                    if(lastButton && lastButton != button) {
                        lastButton.removeClass('isopen');
                    }
                    if($(colorPicker).is(':visible')) {
                        button.removeClass('isopen');
                        lastButton.removeClass('isopen');
                        $(colorPicker).hide();
                        lastButton = null;
                        justDidShow = false;
                    } else {
                        $(colorPicker).slideDown(500);
                        button.addClass('active').addClass('isopen');
                        lastButton = button;
                        justDidShow = true;
                    }
                    return false;
                },
                onBeforeShow: function (){
                    $(this).ColorPickerSetColor($(this).siblings('input').attr('value'));
                    return false;
                },
                onChange: function(hsb, hex, rgb){
                    button.siblings('.colorEx').css('backgroundColor', '#' + hex);
                    button.siblings('input').attr('value',hex);
                    button.siblings('input').change();
                }
            });
        });
        
        var refreshTimer = null;
        var refreshWait = 750;
        $('#configWidget input').each(function() {
            this.onchange = function() {
                //clearTimeout(refreshTimer);
                //refreshTimer = setTimeout(function() {
                    gs.widget.refreshPreview();
                    return false;
               // }, refreshWait);
            }
        });
    }
    
    gs.widget.embedAboutVideo = function(alink,clipid)
    {
        $('.movie .highlight.active').removeClass('active');
        $(alink).addClass('active');
        
        var params = vars = {clip_id: clipid, 
            server:'www.vimeo.com', 
            fullscreen:1, 
            show_title:0, 
            show_byline:0, 
            show_portrait:0, 
            color:'00ADEF'
        };
        swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf", "video", "533", "300", "9.0.0", "/expressInstall.swf", vars, params);
        location.hash = 'feature';
    }
    
    widget.copy = function(widgetID)
    {
        if(widgetID) {
            location.href = '/make?copy=1&widgetid='+widgetID;
        }
    }
    
    widget.copyEmbedCode = function()
    {
        var textarea = document.getElementById('embedCode');
        debug(textarea);
        gs.copy(textarea);
        $('#copyConfirm').show();
    }
    
    gs.widget.gotoMake = function()
    {
        location.href = '/make?widgetid='+widget.widgetid;
    }
    gs.widget.gotoAddSongs = function()
    {
        location.href = '/add_songs?widgetid='+widget.widgetid;
    }
    gs.widget.gotoFinished = function()
    {
        location.href = '/finished?widgetid='+widget.widgetid;
    }
})();
