Event.observe(window, "load", function() {
  if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
    document.body.addClassName("safari")

  ContactForm.setup();
  
  // preload images not visible on page load
  var temp = new Image();
  [ "/images/shared/checkbox/on.png"].each(function(thisImage){temp.src = thisImage;});

});

// ActivityIndicator takes a single argument, the ID of a div
//  that you want to have covered by a div that blocks clicking
//  and shows a large "spinner" to indicate ajax in progress.
//  HTML generated:  <div class="activityIndicator"></div>
ActivityIndicator = Class.create();
ActivityIndicator.prototype = {

  initialize: function(targetId) {
    // store the HTML Element of the target for the indicator so
    // that we can destroy it in the future
    this.el = $(targetId);

    // give target fixed positionit if it has neither relative or absolute positioning
    if(Element.getStyle(this.el, "position") != "absolute" &&
       Element.getStyle(this.el, "position") != "relative") {

      Element.makePositioned(this.el);

      this.isPositioned = true

    }

    // build the HTML element for the indicator keep it storeds
    // in a class variable for future destruction
    this.ai_el = document.createElement("div");

    this.ai_el.className = "activityIndicator";

    this.ai_el.setAttribute("id", targetId + "_ActivityIndicator");

    this.ai_el.style.height = Element.getHeight(this.el) + "px";

    // attach the HTML element
    this.el.appendChild(this.ai_el);

  },

  destroy: function() {

    new Effect.Fade(this.ai_el,{duration:.4, afterFinish: function() {

      //Element.remove(this.ai_el);

      if(this.isPositioned)
        Element.undoPositioned(this.el)

    }});

  }

};

var ContactForm = {

  setup: function() {

    if (!$("ContactForm")) return

    setTimeout(function() {
      $("MessageTextarea").onfocus = function() {
        if ($("MessageTextarea").value == "Write your message here...")
          $("MessageTextarea").value = "";
      };
      $("EmailAddressInput").onfocus = function() {
        if ($("EmailAddressInput").value == "Enter your email (optional)")
          $("EmailAddressInput").value = "";
      };
    }, 100);

    var temp = new Image();
    [ "/images/shared/contact-form/contact-type-chooser-background.png",
      "/images/shared/contact-form/buttons/cancel.png",
      "/images/shared/contact-form/buttons/submit.png",
      "/images/vault/filter-stacks/menus/medium/label.png",
      "/images/vault/filter-stacks/menus/medium/handle.png"].each(function(thisImage){
      temp.src = thisImage;
    });


    ContactForm.reset();

  },

  toggle: function(typeName) {

    var el = $("ContactForm");

    if(Element.visible(el)) {
      ContactForm.closeAndReset()
    } else {
     
      new Effect.SlideDown(el, {queue: "end", duration: .5});
      new Effect.ScrollTo(el, {queue: "end", duration: .5});
    }
  },

  submit: function() {

    var params = Form.serialize("ContactForm");

    params += "&browser=" + encodeURIComponent(navigator.userAgent);
    if ($('VideoTable'))
      params += "&video_ids=" + encodeURIComponent(VideoInspector.selectedIds());

    contactFormAjax = new Ajax.Request("/contact_us/make_contact", {
      parameters: params
    });

  },

  messageBlank: function() {

    Warning.message("Oops, you didn't write a message!");

    $("MessageTextarea").value = "Write your message here...";

  },

  invalidEmail: function() {

    Warning.message("The email address has a typo!");

    $("EmailAddressInput").focus();

  },

  messageSent: function() {

    // top offset set to avoid the warning message being displayed below the content in IE
    setTimeout(function(){Warning.message("Message sent! Thank you.")}, 1000);

    ContactForm.closeAndReset();

  },

  closeAndReset: function() {

    new Effect.SlideUp("ContactForm", {afterFinish: function() {

      ContactForm.reset();

    }, duration: .5});

  },

  reset: function() {

    $("EmailAddressInput").value = "Enter your email (optional)";

    $("MessageTextarea").value = "Write your message here...";

  }

}


var SexyMenu = {
  update: function(selectEl) {
    sexyMenuEl = selectEl.parentNode;
    labelEl = document.getElementsByClassName("labelText", sexyMenuEl)[0];

    $A( selectEl.options ).each( function (option) {
      if (option.value == selectEl.value) labelEl.innerHTML = option.text;
    });
  }
}


var SexyCheckbox = {
  update: function(selectEl) {
    var sexyContainerEl = selectEl.parentNode;
    var checkEl = sexyContainerEl.getElementsByTagName("input")[0];

    if (checkEl.checked)
      Element.addClassName(sexyContainerEl, 'sexyCheckboxChecked');
    else
      Element.removeClassName(sexyContainerEl, 'sexyCheckboxChecked');
  }
}

var SexyRadioButton = {
  update: function() {

    $$('.sexyRadioButton').each(function(sexyContainerEl) {

      sexyContainerEl.getElementsByTagName("input")[0].checked ?
        Element.addClassName(sexyContainerEl, 'sexyRadioButtonChecked') :
        Element.removeClassName(sexyContainerEl, 'sexyRadioButtonChecked');

    })
    
  }
}


var Warning = {
  'message' : function(message, leftOffset, topOffset, dontHide) {
    if (dontHide)
      Element.show($('WarningClose'));
    else
      Element.hide($('WarningClose'));

    leftOffset  = leftOffset || 0;
    topOffset   = topOffset || 0;
    if (dontHide == undefined) dontHide = false;

    $$('#Warning span')[0].innerHTML = message;

    Position.prepare();

    var yOffset = -1 * Position.page(document.body)[1];

    var warning_top = yOffset + (document.documentElement.clientHeight / 2) - 75 + topOffset;
    var warning_left = ((document.body.offsetWidth / 2) - 200) + leftOffset;
    

    var warning_dim = Element.getDimensions('Warning');
    var warning_TRBL = [warning_top,
                        warning_left + warning_dim.width, 
                        warning_top + warning_dim.height, 
                        warning_left ];
    
    var overlap;
    $$('object, embed').each(function(el){
      var flash_dim = Element.getDimensions(el);
      var flash_pos = Position.cumulativeOffset(el);
      var flash_TRBL = [flash_pos[1], // TRBL
                        flash_pos[0] + flash_dim.width, 
                        flash_pos[1] + flash_dim.height, 
                        flash_pos[0] ];      
      
      if (warning_TRBL[0] > flash_TRBL[2] ||  // the top of box A lies below the bottom of box B
          warning_TRBL[2] < flash_TRBL[0] ||  // the bottom of box A lies above the top of box B
          warning_TRBL[3] > flash_TRBL[1] ||  // the left edge of A lies to the right of B's right edge
          warning_TRBL[1] < flash_TRBL[3] )   // the right edge of A lies to the left of B's left edge
        overlap = false;
      else
        overlap = true;
        
      if (overlap) throw $break;
      
    });

    $('Warning').style.top = warning_top+ 'px';
    if (overlap) warning_left += 195;
    $('Warning').style.left = warning_left + 'px';

    new Effect.Appear($('Warning'), {duration: 0.4, afterFinish:function() {
      if (!dontHide) window.setTimeout(function() {new Effect.Fade($('Warning'))}, 2500)
    }});
  }
}


Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7 = Prototype.Browser.IE && !Prototype.Browser.IE6;
Effect.Transitions.expo =  function(pos){
        return Math.pow(2, 8 * (pos - 1));
};


function cookiesAllowed() {
   setCookie('checkCookie', 'test', 1);
   if (getCookie('checkCookie')) {
      deleteCookie('checkCookie');
      return true;
   }
   return false;
}

function setCookie(name,value,expires, options) {
   if (options===undefined) { options = {}; }
   if ( expires ) {
      var expires_date = new Date();
      expires_date.setDate(expires_date.getDate() + expires)
   }
   document.cookie = name+'='+escape( value ) +
      ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
      ( ( options.path ) ? ';path=' + options.path : '' ) +
      ( ( options.domain ) ? ';domain=' + options.domain : '' ) +
      ( ( options.secure ) ? ';secure' : '' );
}

function getCookie( name ) {
   var start = document.cookie.indexOf( name + "=" );
   var len = start + name.length + 1;
   if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
      return null;
   }
   if ( start == -1 ) return null;
   var end = document.cookie.indexOf( ';', len );
   if ( end == -1 ) end = document.cookie.length;
   return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie( name, path, domain ) {
   if ( getCookie( name ) ) document.cookie = name + '=' +
      ( ( path ) ? ';path=' + path : '') +
      ( ( domain ) ? ';domain=' + domain : '' ) +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function toggleUploader(over_limit, over_cap) {
  $('OverLimitMessage').style.display = 'none';
  $('OverCapMessage').style.display = 'none';
  $('UploadButton').className = '';

  if(over_limit) {
    $('OverLimitMessage').style.display = 'block';
    $('UploadButton').className = 'disabled';
  } else if(over_cap) {
    $('OverCapMessage').style.display = 'block';
    $('UploadButton').className = 'disabled';
  }
}



//-----------------------------------------------------------
// Extend Prototype's Event Object to included custom events
//-----------------------------------------------------------

Object.extend(Event, {
    'Custom' : {
        'observers' : false,
        'allObservers' : false,


        // Fire an event on an element
        'fire' : function(element, name, data) {
            element = $(element);

            // Create event object
            if(document.createEvent) {
                var e = document.createEvent("HTMLEvents");
                e.initEvent("dataavailable", true, false);

            } else if(document.createEventObject) {
                var e = document.createEventObject( );

            } else return;

            // Store data
            if(!data) data = {};
            e.name = name;
            e.data = data;

            // Dispatch event to the element
            if(element.dispatchEvent) {
                element.dispatchEvent(e);

            } else if(element.fireEvent) {
                element.fireEvent("ondataavailable", e);
            }

            // Execute event listeners
            $A(Event.Custom.observers[name][element]).each(function(funct) {funct(e)});
            $A(Event.Custom.allObservers[e.name]).each(function(funct) {funct(e)});
        },


        // Observe an event on an element
        'observe' : function(element, name, observer) {
            element = $(element);

            if(!this.observers) this.observers = {};
            if(!this.observers[name]) this.observers[name] = {};
            if(!this.observers[name][element]) this.observers[name][element] = [];

            this.observers[name][element].push(observer);
        },


        // Observe all events with a given name
        'observeAll' : function(name, observer) {
            if(!this.allObservers) this.allObservers = {};
            if(!this.allObservers[name]) this.allObservers[name] = [];
            this.allObservers [name].push(observer);
        },


        // Stop observing an event on an element
        'stopObserving' : function(element, name, observer) {
            element = $(element);

            var i = 0;
             $A(this.observers[name][element]).each(function(funct) {
                if(''+funct == ''+observer) throw $break;
                i++;
            })

            this.observers[name][element].splice(i, 1);
        },


        // Stop a global observer
        'stopObservingAll' : function(name, observer) {
            var i = 0;
             $A(this.allObservers[name]).each(function(funct) {
                if(''+funct == ''+observer) throw $break;
                i++;
            })

             this.allObservers[name].splice(i, 1);
        },


        // Find all observers on a given element
        'observersOn' : function(target) {
            target = $(target);

            var results = $A();

            $H(this.observers).each(function(name) {
                $H(name.value).each(function(element) {
                    if(element.key == target) results.push(element.value);
                })
            });

            return results.flatten();
        }
    }
});

var TextFieldSexificationUnit = function() {

  // array of all the elements that need to be made sexy
  var textFields;

  var findFields = function() {
    textFields = $$("input.sexy").concat($$("textarea.sexy"));
    textFields = $A(textFields);
  };

  var goThroughFields = function() {
    textFields.each(function(field) {

      // wrapper with all the divs for corners and sides
      var wrapper = createWrapper();

      // modify the wrapper's height and width to accomodate the
      //  dimensions of the text field
      wrapper = adjustDimensions(wrapper, field);

      // copy the original field
      var clonedField = field.cloneNode(true)

      // make cloned field visible
      clonedField.style.visibility = "visible";

      // if the text field isn't visible then make sure the wrapper is as well
      if (!field.visible()) {
        wrapper.hide();
        clonedField.show();
      }

      // attach copied text field to the wrapper
      wrapper.appendChild(clonedField);


      // insert the wrapper to the document, just before the original node
      field.parentNode.insertBefore(wrapper, field);

      // remove the original
      field.remove();

    })
  };

  var removeClassFromField = function() {
    $$(".sexy").invoke("removeClassName", "sexy");
  };

  var createWrapper = function() {
    var divNames = $A(["□", "┌", "┬", "┐", "┤", "┘", "┴", "└", "├"]);

    var wrapper;
    divNames.each(function(divName, index) {
      var div = document.createElement("div");
      Element.addClassName(div, divName);
      if (index == 0) wrapper = div
        else wrapper.appendChild(div)
    });

    return wrapper;
  };

  var adjustDimensions = function(thisWrapper, thisField) {

    if(thisField.style.width != "" && thisField.tagName == "TEXTAREA" && Prototype.Browser.WebKit)
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 5;
    else if(thisField.style.width != "" && thisField.tagName == "TEXTAREA" && Prototype.Browser.IE7)
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 4;
    else if(thisField.style.width != "" && thisField.tagName == "INPUT" && Prototype.Browser.IE7)
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 7;
    else if(thisField.style.width != "" && thisField.tagName == "TEXTAREA")
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 7;
    else if(thisField.style.width != "" && thisField.tagName == "INPUT" && Prototype.Browser.WebKit)
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 8;
    else if(thisField.style.width != "")
      var newWidth = parseInt(thisField.style.width.split("px")[0]) + 7;
    else if(Prototype.Browser.WebKit)
      var newWidth = thisField.getWidth() + 2;
    else
      var newWidth = thisField.getWidth() + 3;

    if(thisField.style.height != "" && thisField.tagName == "TEXTAREA" && Prototype.Browser.WebKit)
      var newHeight = parseInt(thisField.style.height.split("px")[0]) + 6;
    else if(thisField.style.height != "" && thisField.tagName == "TEXTAREA" && Prototype.Browser.IE7)
        var newHeight = parseInt(thisField.style.height.split("px")[0]) + 6;
    else if(thisField.style.height != "" && thisField.tagName == "TEXTAREA")
      var newHeight = parseInt(thisField.style.height.split("px")[0]) + 8;
    else if(thisField.style.height != "")
      var newHeight = parseInt(thisField.style.height.split("px")[0]) + 8;
    else if(window.navigator.userAgent.indexOf('rv:1.9') != -1)
      var newHeight = thisField.getHeight();
    else
      var newHeight = thisField.getHeight() + 2;


    if (Prototype.Browser.WebKit && thisField.tagName == "TEXTAREA") {
      newWidth += 2;
      newHeight += 2;
    }

    if (Prototype.Browser.IE) {
      thisWrapper.style.padding = 0;
      thisField.style.top = "3px";
    }

    if (Prototype.Browser.IE && thisField.tagName == "TEXTAREA")
      thisField.style.left = "0"

    if (!Prototype.Browser.IE6)
      thisWrapper.setStyle({
        width: newWidth + "px",
        height: newHeight + "px"
      })

    return thisWrapper;
  };

  var obj = {
    go: function() {
      if (isOldSafari()) {
        removeClassFromField();
        return
      }
      findFields();
      goThroughFields();
      removeClassFromField();
    }
  };

  Event.observe(window, "load", obj.go);

  return obj;

}();


var SignupButton = function() {

  var signup;
  var glow;
  var mouseIsOver = false;
  var effectIsRunning = false;

  var obj = {
    prepare: function() {

      if (!$("SignUp")) return
      signup = $("SignUp");
      glow = signup.getElementsByTagName("img")[0];

      signup.onmouseover = function() {
        mouseIsOver = true;
        obj.over();
      };
      signup.onmouseout = function() {
        mouseIsOver = false;
      };
      obj.over();

    },
    over: function() {
      if (effectIsRunning) return
      effectIsRunning = true;
      new Effect.Opacity(glow, {from: 0, to: 1, duration: .3,
        transition: Effect.Transitions.expo,
        afterFinish: function() {
        new Effect.Opacity(glow, {from: 1, to: 0, duration: 1, afterFinish: function() {
          effectIsRunning = false;
          if (mouseIsOver) obj.over()
        }});
      }});
    }
  }

  Event.observe(window, "load", obj.prepare);

  return obj

}();

function changeContact(menu) {
  $$(".emailAddress").invoke("hide");
  $(menu.value + "Contact").show();
  new Effect.Highlight(menu.value + "Contact", {duration: 2, startcolor: "#666666", endcolor: "#4D4E50"});
  SexyMenu.update(menu);
}

function isOldSafari() {
  var webKitFields = RegExp("( AppleWebKit/)([^ ]+)").exec(navigator.userAgent);
  if (!webKitFields || webKitFields.length < 3) return false
  var versionString = webKitFields[2];

  // Remove '+' or any other stray characters
  var invalidCharacter = RegExp("[^\\.0-9]").exec(versionString);
  if (invalidCharacter)
      versionString = versionString.slice(0, invalidCharacter.index);

  var version = versionString.split(".")[0];

  if (version < 522)
    return true
  else
    return false
};


Object.extend(Element, {
  disable: function(element, options) {
    element = $(element);

    var disableThese = [];
    $A(['input', 'textarea', 'select', 'a', 'button']).each(function(type) {
      $A(element.getElementsByTagName(type)).each(function(elem) {elem.disabled = true;});
    });

    Effect.Fade(element, options);
  },

  enable: function(element, options) {
    element = $(element);

    var enableThese = [];
    $A(['input', 'textarea', 'select', 'a', 'button']).each(function(type) {
      $A(element.getElementsByTagName(type)).each(function(elem) {elem.disabled = false;});
    });

    Effect.Appear(element, options);
  }
})

Element.Methods.clone = function(element) {
  element = $(element);
  var cloned_element = element.cloneNode(true);
  
  // make sure select values are set
  var values = $A(element.getElementsByTagName('select')).map(function(elem) {return elem.value});
  $A(cloned_element.getElementsByTagName('select')).each(function(elem, i) {elem.value = values[i]});
  
  // FIXME: Do this for other input elements as well
  
  return cloned_element;
}

Hash.toQueryString = function(obj){
    var pairs = $H(obj).findAll(function(pair){ return pair.value !== undefined; });
    if(!pairs) return '';
    return pairs.collect(function(pair,index){
        return Hash._toQueryString(pair.key, pair.value);
    }).findAll(function(arg){ return !!arg; }).join('&');
};
Hash._toQueryString = function(key,value){
    if(value === null) value = '';
    if(typeof value != 'object'){
        return key+'='+encodeURIComponent(value.toString());
    }
    if(value.constructor == Array){
        var items = value.findAll(function(arg){ return arg !== undefined; });
        if(!items.length) return Hash._toQueryString(key, '');
        var result = items.collect(function(val,index){
            //
            //            return Hash._toQueryString(key+'['+index+']',val);
            return Hash._toQueryString(key+'[]',val);
        });
    }else{
      var pairs = $H(value).findAll(function(pair){ return pair.value !== undefined; });
      if(!pairs.length) return Hash._toQueryString(key, '');
      var result = pairs.collect(function(pair,index){
            return Hash._toQueryString(key+'['+pair.key+']',pair.value);
        });
    }
    return result.join('&');
};

function SesameVaultError() {
  message  = "There was an error processing your request. <br /><br />If this problem persists, please send us an email to <a href=\"mailto:support@sesamevault.com?subject=SesameVault: API Contact Email\">support@sesamevault.com</a>";
  Warning.message(message, 0, 0, true);
}
