// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function loadAndPlayCard(id) {
  try {
     var pageTracker = _gat._getTracker("UA-3129250-1"); 
     pageTracker._initData(); 
     pageTracker._trackPageview("/playing/card/"+id);
  }catch(err){
  }
  setTimeout("loadAndPlayVideoItem("+id+", 'card')",1000); // induced lag time prevents caching error with flah player latency
}

function loadAndPlayCommercial(id) {
  try{
     var pageTracker = _gat._getTracker("UA-3129250-1"); 
     pageTracker._initData(); 
     pageTracker._trackPageview("/playing/commercial/"+id);
  }catch(err){
  }
  setTimeout("loadAndPlayVideoItem("+id+", 'commercial')",1000); // induced lag time prevents caching error with flash player latency
  setTimeout("forceSharedInstance()",50000);
}

function forceSharedInstance() {
   if($('create_step_share')) {
      $('create_step_share').onsubmit();
   }
}

function checkForPersonalizedMessage(e) {
   Event.stop(e);
   var messages = $$("textarea");
   var promptThis = false;
   var culprit = null;
   for (var index = 0, len = messages.length; index < len; ++index) {
       if(messages[index].value == "Your personal message here." || messages[index].value == "") {
           promptThis = true;
           culprit = $(messages[index]);
       }
   }
   if(promptThis) {
       var confirmation = confirm("Hey you forgot to enter your own personalized message! Hit OK to continue or cancel to enter a message before generating your card.");
       if(confirmation) {
           new Ajax.Request('/instances/preview_instance', { asynchronous:true, evalScripts:true, parameters:Form.serialize(this) });
       } else {
          new Effect.Highlight(culprit);
          culprit.focus();
       }
   } else {
      $("preview-button").disable(); 
      new Ajax.Request('/instances/preview_instance', { asynchronous:true, evalScripts:true, parameters:Form.serialize(this) });
   }
}

function loadAndPlayInstance(id) {
  try{
     var pageTracker = _gat._getTracker("UA-3129250-1"); 
     pageTracker._initData(); 
     pageTracker._trackPageview("/playing/instance/"+id);
  }catch(err){
  }
  setTimeout("loadAndPlayVideoItem("+id+", 'instance')",1000);  // induced lag time prevents caching error with flash player latency
}

function loadAndPlayUserGenerated(id) {
   try{
      var pageTracker = _gat._getTracker("UA-3129250-1"); 
      pageTracker._initData(); 
      pageTracker._trackPageview("/playing/usergenerated/"+id);
   }catch(err){
   }
   setTimeout("loadAndPlayVideoItem("+id+", 'user_generated')",1000);  // induced lag time prevents caching error with flah player latency
}

function loadAndPlayUserGeneratedNoTracking(id) {
  setTimeout("loadAndPlayVideoItem("+id+", 'user_generated')",1000);  // induced lag time prevents caching error with flah player latency
}

function loadAndPlayVideoItem(id, type) {

  // Inform the flash viewer of the change and play the new card
  var viewer = $('viewer_swf');
  if (viewer && viewer.loadAndPlayCard) {
    viewer.loadAndPlayCard('service/' + type + '/' + id);
  }

  // Scroll to the top of the window to view the player for the change
  if (window.scrollTo) {
    window.scrollTo(0, 0);
  }
}

function executeViewerCommand(command, args) {
  // Inform the flash viewer of the change and play the new card
  var viewer = $('viewer_swf');
  if (viewer && viewer.execute) {
    var f = viewer.execute(command, args);
  }
}

function onVideoReady() {
  // Raised when a video begins playing
}

function onVideoComplete() {
  // Raised when a video completes playing
}

function previewCard(id) {

  // Inform the flash viewer of the change and play the new card
  var viewer = $('viewer_swf');
  if (viewer && viewer.loadAndPlayCard) {
    viewer.loadAndPlayCard('service/card/' + id);
  }
  
  // Update the hidden field value for creation of instances
  var hidden = $('card[id]');
  if (hidden) {
    hidden.value = id;
  }
  
  // Update the messages dynamically to support the new card
  new Ajax.Request('/ecard/update_messages_for_card/' + id, {asynchronous:true, evalScripts:true});
}

var videoListsHidden = false;
function toggleMainVideoLists() {
  if (videoListsHidden) {
    $('topten').show();
    $('seasonal').show();
  } else {
    $('topten').hide();
    $('seasonal').hide();
  }
  videoListsHidden = !videoListsHidden;
}


var HintClass = "hintTextbox";

// define a custom method on the string class to trim leading and training spaces
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function initHintTextboxes() {
  var inputs = document.getElementsByTagName('input');
  for (i=0; i<inputs.length; i++) {
    var input = inputs[i];
    if (input.type!= "text")
      continue;
  
    if (input.className.indexOf(HintClass)!= -1) {
        input.hintText  = input.title;
        input.className = HintClass;
        input.onfocus   = onHintTextboxFocus;
        input.onblur    = onHintTextboxBlur;
      
      if (input.value.trim().length == 0) {
        input.value = input.hintText;
      }
    }
  }
  initHintTextareas();
}

function initHintTextareas() {
  var inputs = document.getElementsByTagName('textarea');
  for (i=0; i<inputs.length; i++) {
    var input = inputs[i];

    if (input.className.indexOf(HintClass)!= -1) {
        input.hintText  = input.title;
        //input.className = HintClass;
        //input.onfocus   = onHintTextboxFocus;
        input.onblur    = onHintTextboxBlur;
      
      if (input.value.trim().length == 0) {
        input.value = input.hintText;
      }
    }
  }
}

function onHintTextboxFocus() {
  var input = this;
  if (input.value.trim() == input.hintText) {
    input.value = "";
    //input.className = HintActiveClass;
  }
}

function onHintTextboxBlur() {
  var input = this;
  if (input.value.trim().length == 0) {
  // By client request we no longer replace the hint
  //input.value = input.hintText;
  //input.className = HintClass;
  }
}

function copy(text2copy) {
  if (window.clipboardData) {
    window.clipboardData.setData("Text",text2copy);
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
  // document.getElementById('clipboard-copy').innerHTML = 'Copied to clipboard!';
}

function fbs_click(u) {
  t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}

function replaceContactInfo(info){
  $('contact_info').innerHTML = info
}

function updateContactAutoCompleteFields(element, value){
  id = element.id.split('_').last();

  values = element.value.split(', ')
  $('contact_name_'+ id).value = values[0].split(' ').first(); 
  $('contact_email_'+ id).value = values[1]; 
}

function prepareCreateStep() {
  initHintTextboxes();
  if ($('create_steps_notification')) {
    Element.hide('create_steps_notification');
  }
  if ($('recipient_spinner')) {
    Element.hide('recipient_spinner');
  }
}

function trackAjax(id, step) {
  try {
     var pageTracker = _gat._getTracker("UA-3129250-1"); 
     pageTracker._initData(); 
     pageTracker._trackPageview("/card/"+id+"/"+step); 
  }catch(err){
  }
}

function showCalendar() { 
   cal = new fcp.Calendar(document.getElementById("cal_placeholder"));   
}

function processScheduled() {
    $('submit-button').click();
}

// Shows and hides the label for the search field.
var SearchObserver = Class.create();
SearchObserver.prototype = {
  initialize: function() {
    this.search = $('search_phrase');
    this.searchlabel = $('search_label');
	
	if(this.search.value == '') {
      this.searchlabel.show();
    } else {
	  this.searchlabel.hide();
	}
	
    Event.observe(this.search, 'focus', this.hideLabel.bindAsEventListener(this));
    Event.observe(this.search, 'blur', this.showLabel.bindAsEventListener(this));
  },

  showLabel: function(e) {
    var element = Event.element(e);
    if(element.value == '') {
      this.searchlabel.show();
    }
  },
  
  hideLabel: function(e) {
    this.searchlabel.hide();
  }
};

// Controls the subnavigation elements on the page.
var DropdownMenu = Class.create();
DropdownMenu.prototype = {
  initialize: function(element) {
    this.element = element;
    this.openDelayTime = 250;
    this.closeDelayTime = 250;
    
    // 1.5.1 workaround for getting the subnavigation.
    var subNavigation = null;
    // Loop through the child elements, check for the class name.
    this.element.childElements().each(function(child) {
      if(child.hasClassName('nested_category_navigation')) {
        subNavigation = child;
      }
    });
    
    // Set the proper element to the class.
    this.subNavigation = subNavigation;
    
    // If we got a subnavigation element let's hide it and add observers.  We'll also add an ID if it doesn't exist on the element.
    if(this.subNavigation) {
      if (!this.subNavigation.id) {
        var name = null;
        this.subNavigation.id = this.element.childElements().each(function(child) {
          if(child.match('a')) name = "nested_menu_"+child.innerHTML.substring(0,6);
        });
        this.subNavigation.id = name;
      }
      
      // Here we build a call out so that we can hide and deactivate the menu item from a global call.
      this.hideCallOut = "$('"+name+"').hide(); $('"+name+"').up().removeClassName('active'); if($$('.active').length == 0){ if ($('viewer')) {$('viewer').removeClassName('low-priority');}}";
      this.showCallOut = "$('"+name+"').show();";
      this.subNavigation.hide();
    }   
    Event.observe(this.element, 'mouseover', this.showMenu.bindAsEventListener(this));
    Event.observe(this.element, 'mouseout', this.closeMenu.bindAsEventListener(this));
  },
  
  showMenu: function(e) {
    this.activate();
    $$('ul.nested_category_navigation').invoke('hide');
    if ($('viewer')) {
      $('viewer').addClassName('low-priority');
    }
    if(this.subNavigation) {
      if (this.closeDelayTimer) window.clearTimeout(this.closeDelayTimer);
      this.subNavigation.show();
      //if (!this.subNavigation.visible()) this.openDelayTimer = window.setTimeout(this.showCallOut, this.openDelayTime);
    }
  },
  
  closeMenu: function(e) {
    if(this.subNavigation) {
      if (this.subNavigation.visible()) this.closeDelayTimer = window.setTimeout(this.hideCallOut, this.closeDelayTime);
    }
  },
  
  hideMenu: function(e) {
    this.subNavigation.hide();
    this.element.removeClassName('active');
  },
  
  activate: function() {
    this.element.siblings().each(function(sibling) {
      if(sibling.hasClassName('active')) sibling.removeClassName('active');
    });
    if (this.subNavigation) this.element.addClassName('active');
  }
};


// Extending all elements to support special interactive functionality.
var InteractiveExtensions = {  
    applyDropdown: function(element){  
        element = $(element);
        element.dropdown = new DropdownMenu(element);  
        return element;  
    }  
}  

Element.addMethods(InteractiveExtensions);

// Controls the word counters on the message boxes.
var CharacterCounter = Class.create();
CharacterCounter.prototype = {
  initialize: function(index, limit, lines) {
    this.textarea = $('message['+index+']');
    this.counter = $('counter['+index+']');
    this.countervalue = this.counter.down();
    this.limit = limit;
    this.lines = lines;
    this.countervalue = this.limit;
    this.updateCounter(this.textarea);
    this.textarea.addClassName('hasCounter');
    Event.observe(this.textarea, 'focus', this.clearTextArea.bindAsEventListener(this));
    Event.observe(this.textarea, 'change', this.updateCounter.bindAsEventListener(this));
    Event.observe(this.textarea, 'keydown', this.updateCounter.bindAsEventListener(this));
    Event.observe(this.textarea, 'keyup', this.updateCounter.bindAsEventListener(this));
  },
  
  updateCounter: function(e) {
    if(this.textarea.value.split('\n').length > this.lines && this.lines > 0) {
      this.textarea.value = this.textarea.value.truncate(this.textarea.value.length-1, '');
    }
    if(this.textarea.value.length > this.limit) {
      this.textarea.value = this.textarea.value.truncate(this.limit, '');
    }
    this.counter.down().innerHTML = this.limit - this.textarea.value.length;
  },
  
  clearTextArea: function(e) {
    var element = Event.element(e);
    if(element.value == 'Your personal message here.') {
      this.textarea.value = "";
    }
  }
}

// Checks for spelling errors on user input.
var SpellChecker = Class.create();
SpellChecker.prototype = {
  initialize: function(element) {
    this.textfield = element;
    Event.observe(this.textfield, 'blur', this.checkTextArea.bindAsEventListener(this));
  },
  
  checkTextArea: function(e) {
    var element = Event.element(e);
    var url = '/instances/spelling?term=' + encodeURIComponent(element.value);

    new Ajax.Request(url, {
      method: 'get',
      onSuccess: function(transport) {
        if(transport.responseText != element.value){
         var c = confirm("You entered '"+element.value+"' are you sure you didn't mean '"+transport.responseText+"'");
         if(c == true){
           element.value = transport.responseText;
         } 
        }
      }
    });
  }
}

function determineInitialWidth(e) {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
   }
   if(myWidth < 1020) {
      $('wrapper').addClassName('left_align');
   }
   Event.observe(window, 'resize', resizeHandler);
}

function resizeHandler(e) {
   if($('wrapper')) {
      if(window.innerWidth < 1020 && !$('wrapper').hasClassName('left_align')) {
         $('wrapper').addClassName('left_align');
      } else if(window.innerWidth > 1020 && $('wrapper').hasClassName('left_align')) {
         $('wrapper').removeClassName('left_align');
      }
   }
}

function validateEmails(form)
{
  error = false;
  $$('.hintTextbox').each(function(el){
    reg = /email/; 
    var email_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(el.id))
    {
      var value = $F(el).strip();
      if (value != 'Recipient Email Address' && value != '') {
        if (!email_reg.test(value)) {
          alert(el.value + " is not a valid email address");
          error = true;
        }
      }
    }
  });
  
  if(error)
  {
    return false;
  }
  return true;
}

Event.observe(window, 'load', determineInitialWidth);
