// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function addEngine()
{
        if ((typeof window.sidebar == "object") && (typeof
        window.sidebar.addSearchEngine == "function"))
        {
                window.sidebar.addSearchEngine(
                        "http://www.spotdj.com/spotdj-search.src",
                        "http://www.spotdj.com/spotdj-search.png",
                        'SpotDJ','Web');
                alert('Download completed');
        }
        else
        {
                errorMsg("Sorry, your browser doesn't seem to support search plugins. Try Firefox!");
        }
}

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

function contains(a, b) {

  // Return true if node a contains node b.
  while (b.parentNode)
    if ((b = b.parentNode) == a)
      return true;
  return false;
}


function show_tooltip(event, tt_id, automated) {
    if (currently_shown_tooltip != tt_id) {

        if (currently_shown_tooltip != 0) {
           hide_tooltip(event, currently_shown_tooltip, automated);
        }

        new Effect.Appear('tt_' + tt_id, {duration: 0.3, to: 0.9, queue: 'end', limit: 1});
        currently_shown_tooltip = tt_id;
    }

    if(!automated) {
        // it's a manual hover - stop the periodic script
        pe.currentlyExecuting = true;
    }
}

function hide_tooltip(event, tt_id, automated) {
    if (tt_id == currently_shown_tooltip) {

        var current, related;
        var is_safari = (document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName)?true:false;
        if (event != null) {
            if (window.event && !is_safari) {
                if (window.event.type == 'mouseout') { // we're not coming from show_tooltip
                    current = this;
                    related = window.event.toElement;
                } else {
                    current = window.event.toElement;
                    related = this;
                }
            } else {
                current = event.currentTarget;
                related = event.relatedTarget;
            }
        }

        if (event == null || (typeof event == 'undefined') || (current != related && !contains(current, related))) {
            var queue = Effect.Queues.get('global');
            queue.each(function(e) { if (e.element.id == 'tt_' + tt_id) { e.cancel(); }});
            new Effect.Fade('tt_' + tt_id, {duration: 0.3, queue: 'end', limit: 1});
            currently_shown_tooltip = 0;
        }
    }
    if(!automated) {
        pe.currentlyExecuting = false;
    }
}

function show_random_tooltip() {
    new_tooltip = currently_shown_tooltip;
    while (new_tooltip == currently_shown_tooltip) {
        new_tooltip = rand(cells);
    }

    show_tooltip(null, new_tooltip, true);
}

var TickerDisplayer = {
  updating: null,
  target: null,
  curIndex: 0,
  fadeCurrent: function() {
    $('ticker-item-' + self.curIndex) && new Effect.Fade('ticker-item-' + self.curIndex, {queue: 'end'});
  },

  fetch: function(div_id) {
    this.target = div_id;
    if (!this.periodicExecuter) {
      this.periodExecuter = new PeriodicalExecuter(function() {
        updating = true;
        if (TickerUpdater.updating || TickerDisplayer.updating) return;
        var toHide = $('ticker-item-' + TickerDisplayer.curIndex);
        var toShow = null;
        while (toShow == null) {
            TickerDisplayer.curIndex = (TickerDisplayer.curIndex + 1) % 10;
            toShow = $('ticker-item-' + TickerDisplayer.curIndex);
        }

        (toHide && toShow) && new Effect.Fade(toHide, {queue: 'end'});
        toShow && Effect.Appear(toShow, {queue: 'end'});

      }, 10);

      // show the 0th item
      $('ticker-item-0') && new Effect.Appear('ticker-item-0');
    }
  },

  update: function(new_content) {
    this.updating = false;
//    $(this.target).innerHTML = new_content;
  }
}

var TickerUpdater = {
  updating: null,
  target: null,
  fetch: function(div_id) {
    this.target = div_id;
    if (!this.periodicExecuter) {
      this.periodExecuter = new PeriodicalExecuter(function() {
        if (TickerUpdater.updating || TickerDisplayer.updating) return;
        TickerDisplayer.fadeCurrent();
        new Ajax.Request('/spot_dj/update_ticker');
        updating = true;
      }, 105);
    }
  },

  update: function(new_content) {
    this.updating = false;
    $(this.target).innerHTML = new_content;
  }
}

function go_to_spot(id) {
    window.location = "/spot/" + id;
}

// removes the name/value pair from the form if it exists and submits via form or button
function submitWithout(formElem, submitName, theButton) {
        var theForm = formElem.form;
        if (theForm) {
        for (i = 0; i < theForm.elements.length; i++) {
          if (theForm.elements[i].name == submitName) {
            theForm.removeChild(theForm.elements[i]);
          }
        }
        if (theButton)
            theButton.click();
        else
                    theForm.submit();
        }
}


// adds a new name/value pair to the form and then submits it via the form itself or a button
function submitWith(formElem, submitName, submitValue, theButton) {
        var theForm = formElem.form;
        if (theForm) {
                var newElt = document.createElement("input");
                newElt.type = "hidden";
                newElt.name = submitName;
                if (typeof(submitValue) == "undefined")
                        newElt.value = "true";
                else
                        newElt.value = submitValue;
                theForm.appendChild(newElt);
        if (theButton)
            theButton.click();
        else
                    theForm.submit();
        }
}

// adds a hidden field to a form
function addHidden(formElem, submitName, submitValue) {
        var theForm = formElem.form;
        if (theForm) {
                var newElt = document.createElement("input");
                newElt.type = "hidden";
                newElt.name = submitName;
                if (typeof(submitValue) == "undefined")
                        newElt.value = "true";
                else
                        newElt.value = submitValue;
                theForm.appendChild(newElt);
        }
}

// removes a hidden field to a form
function removeHidden(formElem, submitName) {
    var theForm = formElem.form;
    if (theForm) {
        for (i = 0; i < theForm.elements.length; i++) {
          if (theForm.elements[i].name == submitName) {
            theForm.removeChild(theForm.elements[i]);
          }
        }
    }
}


var Badge = Class.create();
Badge.prototype = {
    
    initialize: function(element) {
        this.element = element;
        this.badge_id = this.element.id.split("_")[1];
        this.x = this.element.getStyle('left').split("px")[0];
        this.y = this.element.getStyle('top').split("px")[0];
        this.show_controls = this.element.down('div.show');
        this.hide_controls = this.element.down('div.hide');
        this.observer = null;
        Event.observe(this.element.down('a.gimme'),'click',this.gimme.bind(this),false);
        if (this.element.down('a.customize')) {
          Event.observe(this.element.down('a.customize'),'click',this.customize.bind(this),false);
        }
        Event.observe(this.element.down('a.hide'),'click',this.hide.bind(this),false);
    },
    
    create_updater: function(element, value) {
        new Ajax.Updater(this.element.down('.badge'), '/badge/update', {asynchronous:true, evalScripts:true, parameters:value});
    },
    
    gimme: function() { 
        var fade = new Array();

        if (this.badge_id == "1") {
            $('badge_code_output').value = this.element.down(".badge").innerHTML;
        } else {
          new Ajax.Updater($('badge_hidden'), '/badge/output', {asynchronous:true, parameters: {badge_id: this.badge_id}, onComplete: function(){$('badge_code_output').value = $('badge_hidden').innerHTML;}});        
        }
        this.hide_other_badges_and_controls(fade);

        fade.push(new Effect.Move(this.element, {x: 0, y: 100, sync: true, mode: 'absolute', transition: Effect.Transitions.sinoidal}));
        fade.push(new Effect.Appear('badge_code', {sync: true}));
        fade.push(new Effect.Move('badge_code', {x: -20, y: -220, sync: true, mode: 'relative', transition: Effect.Transitions.sinoidal}));
        fade.push(new Effect.Appear(this.hide_controls, {sync: true}));

        new Effect.Parallel(fade, {duration: 1});
    },
    
    customize: function() {
        var fade = new Array();

        this.element.addClassName('active');
        $('badge_code_output').value = "Click 'Gimme!'";
        $('badge_id').value = this.badge_id;
        this.show_specific_customization();
        this.hide_other_badges_and_controls(fade);

        fade.push(new Effect.Move(this.element, {x: 0, y: 100, sync: true, mode: 'absolute', transition: Effect.Transitions.sinoidal}));
        fade.push(new Effect.Appear('customize_badge', {sync: true}));
        fade.push(new Effect.Appear('badge_code', {sync: true}));
        fade.push(new Effect.Appear(this.hide_controls, {sync: true}));

        new Effect.Parallel(fade, {duration: 1});
    
        if (this.observer) {
          this.observer.start();
        } else {
          this.observer = new Form.Observer('customize_form', 0.2, this.create_updater.bind(this));
        }
        
    },
    
    hide: function() { 
        var show = new Array();
        
        // Clean up the observer
        if (this.observer) {
          this.observer.stop();
        }
        
        this.element.removeClassName('active');
        this.show_other_badges_and_controls(show);
    
        show.push(new Effect.Move(this.element, {x: this.x, y: this.y, sync: true, mode: 'absolute', transition: Effect.Transitions.sinoidal}));
    
        if ($('customize_badge').visible()) {
          show.push(new Effect.Fade('customize_badge', {sync: true}));
        } else {
          show.push(new Effect.Move('badge_code', {x: 20, y: 220, sync: true, mode: 'relative', transition: Effect.Transitions.sinoidal}));
        }
        
        show.push(new Effect.Fade('badge_code', {sync: true}));  
        show.push(new Effect.Fade(this.hide_controls, {sync: true}));
        new Effect.Parallel(show, {duration: 1, afterFinish: this.hide_specific_customization.bind(this)});
    },
    
    hide_specific_customization: function() {
      if ($('customize_' + this.element.id)) {
        $('customize_' + this.element.id).hide();
      }
      $('badge_hidden').innerHTML = '';
    },

    show_specific_customization: function() {
      $('customize_' + this.element.id).show();
    },
    
    hide_other_badges_and_controls: function(effect_array) {
        $$('.badge_container').without(this.element).each(function(elt) { 
          effect_array.push(new Effect.Fade(elt, {sync: true}));        
        });
        effect_array.push(new Effect.Fade(this.show_controls , {sync: true}));    
    },

    show_other_badges_and_controls: function(effect_array) {
        $$('.badge_container').without(this.element).each(function(elt) { 
          effect_array.push(new Effect.Appear(elt, {sync: true}));        
        });
        effect_array.push(new Effect.Appear(this.show_controls , {sync: true}));    
    }

};


