/**
 * album art Javascript
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var edit = window.gs.edit = {
        // default options/settings
        empty: null
    };

    edit.metaOnload = function(hash) {
        var submitForm;
        gs.modal_show(hash);
        debug('meta onload');
        // handle form ajaxily
        var preFormSubmit = function(data, form, options) {
            // only submit the form
            $('p.error', form).hide();
            $('.loading', form).show();
            $('button',form).attr('disabled','disabled').parent().css('opacity',.3);
            submitForm = form;
        };
        var postFormSubmit = function(json) {
            debug('after meta form submit', json);
            $('.loading', submitForm).hide();
            $('button',submitForm).parent().css('opacity',1);
            if(json.bSuccess) {
                //gs.edit.hideEditBox();
                debug('refresh page');
                gs.refreshPage();
            } else {
                debug('error');
                $('button.submit',submitForm).removeAttr('disabled');
                if(json.error) {
                    $('p.error', submitForm).show().text(json.error);
                }
            }
        };
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        }
        debug('ajax forms');
        $('form',hash.w).ajaxForm(options);
    }
    edit.uploadError = function() {
        alert('upload error');
    }
    edit.artOnload = function(hash) {
        gs.modal_show(hash);
        var submitForm;
        // handle form ajaxily, art so use iframe
        var preFormSubmit = function(data, form, options) {
            debug('pre form submit',data, form, options);
            var terms = $('#agreeToTerms').get(0);
            var file = $('input.fileBrowse',form).get(0);
            var error = false;
            if(!terms || !terms.checked) {
                $(terms).siblings('label').css('color','#ff0000').css('font-size','14px');
                error = true;
            } else {
                $(terms).siblings('label').css('color','#999999').css('font-size','12px');
            }
            debug('file',$(file).parent().prev());
            if(!file || !file.value) {
                $(file).parent().prev().css('color','#ff0000').css('font-size','14px');
                error = true;
            } else {
                $(file).parent().prev().css('color','#000000').css('font-size','12px');
            }
            if(error) {
                return false;
            }
            submitForm = form;
            $('p.error', submitForm).hide();
            $('.loading', submitForm).show();
            $('dl', submitForm).show();
            $('button.submit',form).attr('disabled','disabled').parent().css('opacity',.3);
        }
        var postFormSubmit = function(json) {
            debug('after art form submit', json);
            $('.loading', submitForm).hide();
            $('button.submit',submitForm).parent().css('opacity',1);
            // for right now
            var error = '';
            var url = location.href;
            url = (url.match('\\?')) ? url : url+'?&justUploaded';
            url = (url.match('&justUploaded')) ? url : url+'&justUploaded';
            url = url.replace('#','');
            if(json.uploadReturn) {
                // problem with upload module, most likely users fault
                debug('error in uploadreturn');
                error += ',up-'+(json.uploadReturn || 'false');
            }
            if(json.callbackReturn && json.callbackReturn.length) {
                // problem uploading, db, or sending to static, mostly likely our fault
                for(var i=0; i<json.callbackReturn.length; i++) {
                    debug('curr callbackreturn: ', json.callbackReturn[i]);
                    if(json.callbackReturn[i] !== true) {
                        debug('error in callback');
                        error += ',call-'+(json.callbackReturn[i] || 'false');
                    }
                }
            }
            debug('final error: '+error);
            if(error) {
                var href = $('p.error a', submitForm).attr('href');
                href += error + '-';
                $('p.error a', submitForm).attr('href', href);
                $('p.error', submitForm).show();
                $('dl', submitForm).hide();
                return false;
            }
            location.href = url;
        };
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        }
        $('form',hash.w).ajaxForm(options);
    }

    edit.initUserPicture = function(userID)
    {
        userID = userID || 0;
        // create modal box
        var options = {
            ajax: '/lightboxes/editUserPicture?userID='+userID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.artOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'user'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };

    // Edit artist art lightbox 
    edit.initArtistArt = function(maraID)
    {
        maraID = maraID || 0;
        // create modal box
        var options = {
            ajax: '/lightboxes/editArtistArt?maraID='+maraID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.artOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'artist'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };

    edit.hideEditBox = function()
    {
        gs.lbFactory.disposeModalBox($("#editBox"));
    }

    // Edit album art lightbox 
    edit.initAlbumArt = function(albumID)
    {
        albumID = albumID || 0;
        // create modal box
        var options = {
            ajax: '/lightboxes/editAlbumArt?albumID='+albumID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.artOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'album'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };
    
       
    // Edit album lightbox 
    edit.initAlbum = function(albumID)
    {
        // create modal box
        var options = {
            ajax: '/lightboxes/editAlbumMeta?albumID='+albumID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.metaOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };
    
    // Edit Song lightbox 
    edit.initSong = function(songID, albumID)
    {
        if(!songID && !albumID) { return false; }
        songID = songID || '';
        albumID = albumID || '';
        // create modal box
        var options = {
            ajax: '/lightboxes/editSongMeta?songID='+songID+'&albumID='+albumID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.metaOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };

    edit.upload = function(iframeObj, type)
    {
        type = type || false;
        debug("load iframe obj",iframeObj);
        var iframeDoc = iframeObj.contentWindow || iframeObj.contentDocument;
        if (iframeDoc.document) {
            iframeDoc = iframeDoc.document;
        }
        var response_str = iframeDoc.body.innerHTML;
        debug(response_str);
        if (response_str) {
            try {
                var json = $.parseJSON(response_str);
            } catch(e) {
                var json = {};
            }
            if(!json || !json.filename) {
                json = json || {};
                // todo: need to have error message instead
                debug('error processing uploading');
            } else {
                var obj = $(iframeObj).siblings('.image').find('img');
                debug('change obj', obj, iframeObj);
                obj.attr('src', json.filename);
                $(obj).parent().hide().show();
                gs.refreshPage();
            }
        }
        return false;
    }

    edit.genreSelectChange = function(obj) {
        debug('genre select change', obj);
        if(obj.value=='') {
            $('#otherGenreID').show().attr('name','mainGenreID');
        } else {
            $('#otherGenreID').hide().removeAttr('name');
        }
    }

    // NOTE: The following are special admin-specific js functions. They are basically duplicates of the original method but with an additional argument to allow admin rights.
    
    edit.initAdminArtistArt = function(artistID, maraID)
    {
        artistID = artistID || 0;
        // create modal box
        var options = {
            ajax: '/lightboxes/editArtistArt?artistID='+artistID+"&maraID="+maraID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.artOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'artist'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };

    edit.initAdminAlbumArt = function(albumID, maraID)
    {
        albumID = albumID || 0;
        // create modal box
        var options = {
            ajax: '/lightboxes/editAlbumArt?albumID='+albumID+"&maraID="+maraID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.artOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'album'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };
    
       
    // Edit album lightbox 
    edit.initAdminAlbum = function(albumID, maraID)
    {
        // create modal box
        var options = {
            ajax: '/lightboxes/editAlbumMeta?albumID='+albumID+"&maraID="+maraID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.metaOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };
    
    // Edit Song lightbox 
    edit.initAdminSong = function(songID, albumID, maraID)
    {
        if(!songID && !albumID) { return false; }
        songID = songID || '';
        albumID = albumID || '';
        // create modal box
        var options = {
            ajax: '/lightboxes/editSongMeta?songID='+songID+'&albumID='+albumID+"&maraID="+maraID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: edit.metaOnload
        };
        var divinfo = {
            newid: 'editBox',
            newclass: 'song'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    };

    edit.toggleRowForm = function(obj,songID)
    {
        obj = obj || false;
        songID = songID || false;
        if(!songID) { return false; }
        if(!$(obj).length) { return false; }
        if($(obj).siblings('button').length) {
            $(obj).parent().parent().parent().toggle();
        } else {
            $(obj).parent().parent().parent().next().toggle();
        }
    }
    
    edit.toggleDetailsForm = function(obj)
    {
        obj = obj || false;
        if(!$(obj).length) { return false; }
        if($(obj).siblings('.editDetailsForm').length) {
            $(obj).siblings('.editDetailsForm').toggle().find('button.submit').removeAttr('disabled');
            $(obj).siblings('ul.meta').toggle();
        } else {
            $(obj).parent().parent().toggle().find('button.submit').removeAttr('disabled');
            $(obj).parent().parent().siblings('ul.meta').toggle();
        }
        $(obj).parent().parent().parent().find('a.editLink').toggle();
    }
    edit.toggleAddAlbumForm = function(obj)
    {
        obj = obj || false;
        if(!$(obj).length) { return false; }
        $(obj).parent().parent().parent().siblings('.addAlbumContainer').toggle().find('button.submit').removeAttr('disabled');
    }

    edit.initDetailsForm = function()
    {
        var submitForm;
        debug('init details form');
        // handle form ajaxily
        var preFormSubmit = function(data, form, options) {
            // only submit the form
            $('p.error', form).hide();
            $('.loading', form).show();
            $('button.submit',form).attr('disabled','disabled').parent().css('opacity',.3);
            submitForm = form;
        };
        var postFormSubmit = function(json) {
            debug('after detail form submit', json);
            $('.loading', submitForm).hide();
            $('button.submit',submitForm).parent().css('opacity',1);
            if(json.bSuccess) {
                if(json.source=='page' && json.html) {
                    debug('refresh page form details');
                    $('div.detailsForm').html(json.html);
                }
                if(json.source=='row') {
                    debug('refresh song row form details');
                    debug(submitForm.get(), submitForm.parent().prev('li').get());
                    $(submitForm).parent().prev('li').remove();
                    $(submitForm).parent().before(json.html);
                    $(submitForm).parent().remove();
                }
                gs.edit.initDetailsForm();
            } else {
                debug('error');
                if(json.message) { $('p.error', submitForm).text(json.message).show(); }
                $('button.submit',submitForm).removeAttr('disabled');
            }
        };
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        }
        $('button.submit','form.editDetailsForm').removeAttr('disabled');
        $('form.editDetailsForm').ajaxForm(options);
    }
    
    edit.initAddAlbumForm = function()
    {
        var submitForm;
        debug('init add album form');
        // handle form ajaxily
        var preFormSubmit = function(data, form, options) {
            // only submit the form
            $('p.error', form).hide();
            $('.loading', form).show();
            $('button.submit',form).attr('disabled','disabled').parent().css('opacity',.3);
            submitForm = form;
        };
        var postFormSubmit = function(json) {
            debug('after detail form submit', json);
            $('.loading', submitForm).hide();
            $('button.submit',submitForm).parent().css('opacity',1);
            if(json.bSuccess) {
                gs.refreshPage();
            } else {
                debug('error');
                if(json.message) { $('p.error', submitForm).text(json.message).show(); }
                $('button.submit',submitForm).removeAttr('disabled');
            }
        };
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            dataType: 'json'
        }
        $('button.submit','form.addAlbum').removeAttr('disabled');
        $('form.addAlbumForm').ajaxForm(options);
        edit.initAlbumNameAutocomplete();
    }

    edit.initAlbumNameAutocomplete = function() {
        debug('init album name auto');
        // /catalogue/albumMatch?keyword=
        var lastQuery = '';
        var album = $('#albumName');
        album.autocomplete('/catalogue/albumMatch.json', {
            resultsId: "albumcomplete",
            resultsClass: "ac_results results",
            minChars: 1,
            max: 10,
            delay: gs.search.autoCompleteWait,
            cacheLength: 100,
            width: 520,
            scroll: true,
            scrollHeight: 190,
            matchSubset: false,     // whether to do new query for refinement (false==new query)
            selectFirst: false,     // whether to auto select first item
            //extraParams: {auto:1,type:type}, // extra params to send to endpoint
            offsetTop: -9,
            offsetLeft: -21,
            //highlight: false,    // could be a function or false, defaults to true
            /*
            formatItem: function(item) {
                //debug('format item', item, arguments);
                return item.toString();
            },
            //*/
            formatResult: function(item) {
                debug('format result',item);
                return item[0];
            }
        });
        album.keyup(function(){
            lastQuery = this.value;
        }).result(function(event, item, formatted) {
            debug('result item: '+lastQuery, arguments);
        });
        // remove placeholder
        //$('#albumcomplete').not('.ac_results').remove();
        //$('div.ac_results').css('background','#000000');
        setTimeout(function() {
            debug($('#albumcomplete').get());
            $('#albumcomplete').wrap('<form><dl><dd></dd></dl></form>');
        }, 500);
        /*
        setInterval(function() {
            if($('#albumcomplete').length) {
                debug($('#albumcomplete').get());
            }
        }, 300);
        //*/
    }
    
})();
