/*



Dynamic Application of Functions to DOM
*/

var debug = false;


Event.observe(window, "unload", function(){
  $$(".stopped").invoke("removeClassName", "stopped");
  removeAllFlash();
});

function removeAllFlash (exclude) {
  cl('removeAllFlash');
  $$("object[id^=player]",
  "object[name^=player]",
  "embed[name^=player]",
  "embed[id^=player]").invoke("remove");
  resetIcons(exclude);
}

/*



This is the function that applies the functions to the DOM
Defined just before </body> in the markup.
This occurs before initAfterImages();
*/
function init(){
  
  if ($("SideTestimonial")){
    if(!location.href.include("PriceStardust")){
      var SideTestimonial = $("SideTestimonial");
      new Ajax.Request("/SideTestimonials", {
        method: "get",
        onSuccess: function(r){
          var testimonials = $A(r.responseText.split("-delimiter-"));
          var randomTestimonial = testimonials[Math.floor(testimonials.length * Math.random() - .001)];
          SideTestimonial.update(randomTestimonial);
        },
        onComplete: function(){
          new Effect.Appear("TestimonialFade", {from: 0, to: 1});
        }
      });
    }
  }

  $$(".MusicSample").each(function(node, i){
    /*
    
    prep MusicSamples
    */
    var node = $(node);
    node.update("&nbsp;&nbsp;<span>" + node.innerHTML + "</span>");
    
    node.observe("click", function(event){
      var FlashObjName = "player" + i;
      
      /*
      
      
      if it's not playing yet, play it
      */
      if (!this.hasClassName("playing")){
        this.addClassName("playing");
        if (this.hasClassName("stopped")){
          this.removeClassName("stopped");
        }
        /* stop any existing plays */
        //if ($(FlashObjName)) $(FlashObjName).remove();
        stopSounds(node);
        /* if it's not embedded yet
        embed it, and it will automatically play */
        //cl('after stopSounds');
        if (!$(FlashObjName)){
          cl('embed and play flash');
          var path = this.href.substr(this.href.indexOf("#") + 1, this.href.length);
          new Insertion.Top(
            this,
            IEHacks.FlashHTML(FlashObjName, FlashObjName, 1, 1, "/flash/player.swf?path=../" + path, true)
          );
          //pageTracker._trackEvent('music', 'play');
          cl('after flash: iff');
        /* else play it */
        } else {
          cl('play existing flash');
          cl(FlashObjName);
          cl($Flash(FlashObjName));
          if ($Flash(FlashObjName)){
            cl('flash exists');
            $Flash(FlashObjName).playSound();
            //pageTracker._trackEvent('music', 'play');
          }
          cl('after flash: else');
        }
        cl('after Flash methods');
      /*
      
      
      else stop it from playing
      */
      } else {
        resetIcon(this);
        stopSound(i);
      }
      this.blur();
      Event.stop(event);
    }.bindAsEventListener(node));
  });




  /*
  
  
  
  Forms
  */
  $$("input", "textarea").each(c.addFocus);
  $$("input[type=text]").invoke("addClassName", "text");
  
  
  /*


  Simple form validation
  onsubmit, feed the ValidateForm() function an array containing id's of form inputs you wish to validate

  */
  $$(".pricingForm").each(function(node, i){
    node.observe(
      "submit",
      function(e){
        /* an array of elements that will always be validated */
        var ValidateMe = $$(".Validate");
        /* validate form, cancel submission if it vails validation */
        if(ValidateForm(ValidateMe) == false){
          this.blur;
          cl("validation vailed, cancelling form");
          Event.stop(e);
        }
      }.bindAsEventListener(node)
    );
  });
  
  musicSelectionForm();

}
// end init

function musicSelectionForm() {
  //show and hide sections based on selected radio button
  var sections = $('section1_1', 'section1_2').compact();
  var showHide = $('packages', 'manual-selections').compact();
  var flag;
  
  //make sure the dom elements are there
  if (sections.length != 2 || showHide.length != 2) return;
  
  //make sure these aren't checked when the page loads
  sections[0].checked = false;
  sections[1].checked = false;
  
  sections[0].observe('click', function(e){
    if (Prototype.Browser.IE) {showHide[0].show(); showHide[1].hide();}
    else {
      Effect.BlindDown(showHide[0], {queue: 'front'});
      Effect.BlindUp(showHide[1], {queue: 'end'});      
    }
  });
  
  sections[1].observe('click', function(e){
    if (Prototype.Browser.IE) {
      flag = showHide[0].visible();
      showHide[0].hide();
      showHide[1].show();
      if (flag) Effect.ScrollTo(sections[1]);
    }
    else {
      if (showHide[0].visible()) Effect.BlindUp(showHide[0], {queue: 'end'});
      Effect.BlindDown(showHide[1], {queue: 'end'});      
      if (showHide[0].visible()) Effect.ScrollTo(showHide[1]);
    }
  });
}



/*



Library of Custom Functions
*/
var IEHacks = {

  /*
  
  This function makes 32 bit PNG's with transparency work in PC IE6
  */
  MakePNGTransparent: function(node, i){
    if (!navigator.userAgent.include("MSIE ")){
      return false;
    } else {
      if(!node.src.include("png")){
        node.runtimeStyle.filter = "";
        return;
      }
      var oldSrc = node.src;
      node.src = "/images/transparent.gif";
      node.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + oldSrc + "',sizingMethod='scale')";
    }
  },
  /*
  
  
  
  This function is used to embed the Flash into the page
  
  Variables:
  
    Variable Name   : Laman        : Data Type
    
    EF_object       : id of object : String
    EF_width        : width        : String
    EF_height       : height       : String
    EF_filename     : filename     : String
    EF_transparency : transparency : Boolean
  
  */
  EmbedFlash: function(EF_object, EF_name, EF_width, EF_height, EF_filename, EF_transparency) {
    if($(EF_object)){
      $(EF_object).update(IEHacks.FlashHTML(EF_object, EF_name, EF_width, EF_height, EF_filename, EF_transparency));
    }
  },
  FlashHTML: function (EF_object, EF_name, EF_width, EF_height, EF_filename, EF_transparency){
    if (EF_transparency){
      var EF_transparency_ParamMarkup = new String('<param name="wmode" value="transparent" />');
      var EF_transparency_EmbedMarkup = new String('wmode="transparent"');
    } else {
      var EF_transparency_ParamMarkup = new String('');
      var EF_transparency_EmbedMarkup = new String('');
    }
    var markup = [
      '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="', EF_width, '" height="', EF_height, '" id="', EF_name, '" align="middle" style="height: ', EF_height, '; width: ', EF_width, ';">',
      '<param name="allowScriptAccess" value="sameDomain" />',
      EF_transparency_ParamMarkup,
      '<param name="movie" value="', EF_filename, '" />',
      '<param name="quality" value="high" />',
      '<embed src="', EF_filename, '" ', EF_transparency_EmbedMarkup, ' quality="high" width="', EF_width, '" height="', EF_height, '" name="', EF_name, '" align="middle" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />',
      '</object>'].join("");
    return markup;
  }
};
/*


Returns the Flash object existing on the DOM,
allowing you to use methods and functions from within the ActionScript itself
*/
function $Flash(movieName) {
  if (navigator.appName.include("Microsoft")) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}

/*


This function communicates with every Flash Music Sample and stop the sound
*/
function stopSounds(excludeme){
  cl(excludeme);
  // $$(".MusicSample").each(function(_n, _i){
  //   if (_n != excludeme){
  //     stopSound(_i);
  //     resetIcon(_n);
  //   }
  // });
  removeAllFlash(excludeme);
}

function stopSound(excludeme){
  //cl(i);
  // if ($Flash("player" + i)){
  //   $Flash("player" + i).stopSound();
  // }
  removeAllFlash(excludeme);
}

/*


*/
function resetIcon(node){
  if (node.hasClassName("playing")){
    node.removeClassName("playing");
  }
  node.addClassName("stopped");
}
function resetIcons(exclude){
  $$(".MusicSample.playing").each(function(_nx, i){
    if (exclude == _nx) return;
    _nx.removeClassName("playing").addClassName("stopped");
  });
}


/*


A Form Validation Function
That decorates the page with feedback
  <div>
    <label for="asdf">asdf</label>
    <input id="asdf" name="asdf" /><br />
  </div>
*/
function ValidateForm(vf_ValidateMe){
  ValidationError = $A();
  $A(vf_ValidateMe).each(function(node, i){
    /* If it's an actual node */
    if($(node)){
      node = $(node);
      parent = $(node.parentNode);
      /* if it's empty */
      if((node.value == null) || (node.value == "")){
        ValidationError[i] = true;
        parent.toggleClassName("fieldWithErrors");
        /* else it's not empty */
      } else {
        ValidationError[i] = false;
      }

      /* when the input is blurred, remove the ValidationError class if ... */
      node.observe(
        "blur",
        function(){
          /* if the input has something in it and parent has the "ValidationError" class, remove it */
          parent = $(node.parentNode);
          if (node.value.length > 0){
            if (parent.hasClassName("fieldWithErrors")) parent.removeClassName("fieldWithErrors");
          }
          node.toggleClassName("focus");
        }
      );
    }
  });

  /* if validation failed */
  if(ValidationError.any()){
    alert("Please fill out the required form fields.");
    this.blur();
    return false;
  }

}


/*


The start of the custom functions object
*/
var c = {
  /*
  
  
  Drop Down show's the first ul child
  */
  addDropDown: function(node, i){
    node.observe("mouseover", function(){node.addClassName("hover");});
    node.observe("mouseout", function(){node.removeClassName("hover");});
    if (node.down("ul")){
      var ul = node.down("ul");
      node.observe("mouseover", function(){ul.show();});
      node.observe("mouseout", function(){ul.hide();});
    }
  },
  addFocus: function(node, i){
    node.observe("focus", c.toggleFocus.bindAsEventListener(node));
    node.observe("blur", c.toggleFocus.bindAsEventListener(node));
  },
  toggleFocus: function(e){
    this.toggleClassName("focus");
  },
  addHover: function(node, i){
    node.observe("mousover", c.toggleHover.bindAsEventListener(node));
    node.observe("mouseout", c.toggleHover.bindAsEventListener(node));
  },
  toggleHover: function(e){
    this.toggleClassName("hover");
  }
};

function cl(str){if(debug){
  Try.these(
    function(){console.log(str);},
    function(){alert(str)}
  );
}}
