/**
 * IN ARRAY
 */
function inArray(needle,haystack) {
    if (haystack.indexOf(needle) > -1) return true;
    else return false;
}

/**
 * REMOVE FROM ARRAY
 */
function removeFromArray(needle,haystack) {
    var i = haystack.indexOf(needle); /* indexOf was part of prototype, do we still have it? */
    if (i > -1) delete haystack[i];
}

/**
 * IS EMPTY
 */
function isEmpty(x) {
    if (x==''||x==undefined||x==null||x==false||x=='0'||x==0) return true;
    else return false;
}

/**
 * IS NUMERIC
 */
function isNumeric(value) {
    if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
    return true;
}

/**
 * IS (POSITIVE) INTEGER
 */
function isInteger(value){
	return /^[0-9]+$/.test(value);
}

/**
 * TOGGLE
 */
function toggle(id) {
    $('#'+id).toggle();
}

/**
 * TRIM
 */
function trim(str) {
    return (typeof str == 'string') ? str.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : false;
}

/**
 * STRIP TAGS
 */
function stripTags(str){
    return (typeof str == 'string') ? str.replace(/(<[^>]+>)/g,'') : false;
}

/**
 * IS EMAIL
 *
 * Sophisticated email validation pattern.  Will (technically) require update if and when ICANN adds TLDs.
 */
function isEmail(str) {
    var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
    return regex.test(str);
}

/**
 * JQUERY EXTENSIONS
 */
jQuery.fn.extend({

    /**
     * HOVER CLASS
     *
     * Credit: Myles Angell <mangell [at] cronin [dash] co [dot] com>
     *         See http://be.twixt.us/jquery/suckerFish.php
     */
    hoverClass : function(c) {
        return this.each(function() {
            $(this).hover(
                function() { $(this).addClass(c);  },
                function() { $(this).removeClass(c); }
            );
        });
    },

    /**
     * RESTORE STRIPES
     *
     * Restores "odd" and "even" stripe classes.  Can call on the target
     * itself or any child element (e.g. the header row of a table).
     *
     * @param string tag Default: 'TABLE'. Target tag type.  Other sensible choices: UL, OL, DL.
     */
    restoreStripes : function(tag) {
        if (typeof tag != 'string') var tag = 'TABLE';
        return this.each(function() {
            if (this.tagName == tag){
                $(':nth-child(even)',this).removeClass('odd').addClass('even');
                $(':nth-child(odd)',this).removeClass('even').addClass('odd');
            } else {
                $(this).parents(tag).restoreStripes();
            }
        });
    },

    /**
     * CHECK BOX FUNCTIONS
     */
    check : function() {
        return this.each(function() { this.checked = true; });
    },
    uncheck : function() {
        return this.each(function() { this.checked = false; });
    },
    toggleCheck : function() {
        return this.each(function() { this.checked = !this.checked; });
    },

    /**
     * MAKE CLICKABLE
     *
     * @param string hover What hover class, if any.  Default: 'hover'.
     * @param bool cursor Whether to add the CSS rule { cursor:pointer; }. Default: true.
     */
    makeClickable : function(hover, cursor){

        // Validate input and apply defaults
        if (typeof hover == 'undefined') var hover = 'hover';
        if (typeof cursor != 'boolean') var cursor = true;

        return this.each(function(){
            var url         = $('a',this).attr('href');
            var target      = $('a',this).attr('target');
            var title       = $('a',this).attr('title');

            // Only make target clickable if there is a link inside it
            if (!isEmpty(url)) {
                $(this).click(function(){
                    if (target == '_blank') {
                        window.open(url);
                    }
                    else {
                        top.location.href = url;
                    }
                });
                $(this).attr('title',title);
                if (hover) $(this).hoverClass(hover);
                if (cursor) $(this).css('cursor','pointer');
            }
        });
    },

    /**
     * WINDOWSHADE
     *
     * @usage               $('.windowshade-parent').windowshade();
     */
    windowshade : function(){
        var control                            = '<a class="windowshade-control" href="javascript:void(0);"><b>+</b></a>';
        return this.each(function(){
            $('.windowshade-section-not-toggled',this).append(control);
            $('.windowshade-control',this).click(function(){
                $(this).parents('.windowshade-parent').toggleClass('windowshade-mode-on');
            });
        });
    }
});

/**
 * SITE
 *
 * Creates namespace to prevent conflicts with other included javascript files.
 */
var SiteLib = function() {

    return{

        inPreviewMode                       : false,

        /**
         * LOG OUT
         */
        logOut : function(){

            response.showProcessingMessage('Logging out');

            $.ajax({
                type                        : 'POST',
                url                         : '/admin/api/Account/logOut/',
                success : function(result){
                    var returnData          = response.process(result);

                    // If logout is successful, response.process() will return true.
                    // Page is reloaded and logout will be detected upon refresh.
                    if (returnData === true){
                        // pause a moment to load the dialog icon
                        setTimeout('location.reload(true);',100);
                    }
                    else {
                        //alert('Unexpected response to logout.\nreturnData = '+returnData+'\n\nrawData = '+result);
                    }
                },
                error : function(result){
                    response.process(result);
                }
            });
            return false;
        },

        /**
         * SUBMIT FORM
         *
         * @param form Form element
         * @param success AJAX success function
         */
        submitForm : function(form, success){

            // Default success function
            if (typeof success != 'function'){
                success = function(result){
                    var result              = response.process(result);
                }
            }

            // Submit form via AJAX
            $.ajax({
                type: 'POST',
                url: form.action,
                data: $(form).formSerialize(), // requires jquery.form.js
                success: success,
                error: function(result){
                    response.process(result);
                }
            });
        },

        /**
         * SCROLL TO
         *
         * @param bool updateURL Whether to add #anchorName to the end of the URL.  Default: true.
         */
        scrollTo : function(selector, updateURL, event){

            if (typeof updateURL != 'boolean') var updateURL = true;

            var targetOffset = $(selector).offset().top + $('a[name=top]').offset().top;

            if (event) event.preventDefault();

            $('html,body').animate({scrollTop: targetOffset}, 'normal', function(){
                if (updateURL){
                    location.hash = $(selector).attr('name');
                }
            });
        },

        /**
         * SCROLL TO TOP
         *
         * @param bool updateURL Whether to add #anchorName to the end of the URL.  Default: true.
         */
        scrollToTop : function(updateURL, event){
            SiteLib.scrollTo('a[name="top"]', updateURL, event);
        },

        /**
         * INIT SORTABLE TABLE HEADERS
         *
         * Initializes sortable table headers
         */
        initSortableTableHeaders: function(){

            var colCounter              = 0;

            /* Set hover class for table headers */
            $('table.sortable th').hoverClass('hover');

            /* Add tooltip */
            $('table.sortable th').each(function(){

                colCounter++;

                $(this).qtip({

                    content:            'Sort by ' + $(this).html(),
                    show:               "mouseover",
                    hide:               "mouseout",
                    position:{
                        corner:{
                            target:     "bottomMiddle",
                            tooltip:    "topMiddle"
                        }
                    },
                    style:{
                        background:     "#000000",
                        color:          "#FFFFFF",
                        border:{
                            width:      2,
                            radius:     4,
                            color:      "#333C40"
                        },
                        tip:            "topMiddle"
                    },
                    show:{
                        delay:          0,
                        solo:           true,
                        effect:{
                            type:       "none"
                        }
                    }
                });
            });

            //var firstRow                = $('table.sortable tr:first');
            //firstRow.after('<tr colspan="'+colCounter+'" class="sorting">SORTING</tr>');
        },

        /**
         * ADD TO MY SHORT STACK
         */
        addToMyShortStack : function(artistSongID){

            $.ajax({
                type                        : 'POST',
                url                         : '/admin/api/Playlist/addToMyShortStack/',
                data : {
                    id                      : artistSongID
                },
                success : function(result){
                    response.process(result);
                },
                error : function(result){
                    response.process(result);
                }
            });
        },
        
        /**
         * Initializes shim ad (if any). Position and overflow need to be
         * toggled on mouseover/mouseout so links are clickable under the
         * transparent part of the flash.
         */
        initShim : function(){
            
            $('.shim').mouseover(function(){
                $('.shim-container').css('overflow','visible');
                $(this).css('position','absolute');
            });
            
            $('.shim').click(function(){
                $('.shim-container').css('overflow','hidden');
                $(this).css('position','inherit');
            });
        },

        /**
         * INIT
         */
        init : function() {
            
            SiteLib.initShim();
            
            $('.js-hover').hoverClass('hover');
            SiteLib.initSortableTableHeaders();

            $('a.back-to-top').click(function(event){
                SiteLib.scrollTo('a[name=top]',event);
            });
        }
    };
}();
$(document).ready(SiteLib.init);
