var addthis_config =
{
   "username":'dragonflydepot',
   "ui_click":false,
   "ui_cobrand":'',
   "data_track_clickback":true,
   "ui_508_compliant":true
}

// jQuery.noConflict();
// var $j = jQuery;

$j(function() {
  var delay = 400;

  function hideMenu() {
      if (!$j('.custom_button').data('in') && !$j('.hover_menu').data('in') && !$('.hover_menu').data('hidden')) {
          $j('.hover_menu').fadeOut('fast');
          $j('.custom_button').removeClass('active');
          $j('.hover_menu').data('hidden', true);
      }
  }

  $j('.custom_button, .hover_menu').mouseenter(function() {
      $j('.hover_menu').fadeIn('fast');
      $j('.custom_button').addClass('active');
      $j(this).data('in', true);
      $j('.hover_menu').data('hidden', false);
  }).mouseleave(function() {
      $j(this).data('in', false);
      setTimeout(hideMenu, delay);
  });    

});



if (typeof DFD == "undefined") {
    var DFD = {};
}

var silenceAjaxRequest = false;

(function() {
    DFD["dialogs"] = {};
    DFD["builder"] = {};
    DFD["cursor"] = {};
    DFD["effects"] = {};
})();

Ajax.Responders.register({

    onCreate: function(request){
        if (!silenceAjaxRequest && ($('loading') || $('ZoomSpin') && Ajax.activeRequestCount > 0)) {
            Element.show('loading');
            Element.show('loading-shadow');
        }
    },

    onComplete: function(request) {
        if ($('loading') && Ajax.activeRequestCount == 0) {
            Element.hide('loading');
            Element.hide('loading-shadow');
        }
    }
});

DFD.dialogs = {
  ajax: function(url, title, disable_title) {
		if (disable_title == undefined)
  			Modalbox.show(url, {title: title, center: true, transitions: false, width: 520});
		else
			Modalbox.show(url, {title: title, center: true, transitions: false, disableTitle: true});
  }
}

DFD.builder = {
  liveSearchKeypressHandler: function(event) {
    DFD.builder.disableAjaxThrobber();
    switch(event.keyCode) {
     case Event.KEY_RETURN:
       $('live-search-form').submit();
       return;
    }
  },
  
  disableAjaxThrobber: function() {
    silenceAjaxRequest = true;
  },
  
  enableAjaxThrobber: function() {
    silenceAjaxRequest = false;
  },
  
  highlight: function(element, default_text) {
    if (element.value == default_text) {
      new Effect.Morph(element, {style: 'color: #CCC', duration: 0.4});
    }
  },
  
  clearDefault: function(element, default_text) {
    if (element.value == default_text) {
      element.value = "";
    }
    element.setStyle({color: '#959595'});
  },
  
  setDefaultNoCart: function(element, default_text) {
    if (element.value == "") {
      element.value = default_text;
    }
    element.setStyle({color: '#959595'});    
  },
  
  setDefault: function(element, default_text) {
    if (element.value == "") {
      element.value = default_text;
    }
    element.setStyle({color: '#959595'});
    DFD.builder.copyCheckoutElements();
    DFD.builder.enableDisableCheckoutButton();
  },
  
  displayProperElements: function(cart_zip_code) {
    if($F('is_different_shipping') == "true") {
      $$('.same-shipping-address-link').each(function(s){
        s.show();
      });
      $$('.different-shipping-address-link').each(function(s){
        s.hide();
      });
      $('shipping-address').show();
    }
    
    if(cart_zip_code || DFD.builder.validateShippingInformation()) {
      $('shipping-options').setOpacity(1.0);
    }
    
    DFD.builder.enableDisableCityStateFields();
    DFD.builder.enableDisableCheckoutButton();
  },
  
  enableDisableCheckoutButton: function() {
    if(DFD.builder.validateCreditCardInformation() && DFD.builder.validateShippingInformation() && DFD.builder.validateUserInformation()) {
      $('checkout-submit').enable();
    } else {
      $('checkout-submit').disable();
    }
  },
  
  enableDisableCityStateFields: function() {
    var billingPostal = $('billing_address_postal_code');
    var shippingPostal = $('primary_address_postal_code');
    
    if(billingPostal.value != billingPostal.getAttribute('orig')) {
        $('billing_address_city').enable();
        $('billing_address_state_code').enable();
    }
    
    if(shippingPostal.value != shippingPostal.getAttribute('orig')) {
        $('primary_address_city').enable();
        $('primary_address_state_code').enable();        
    }
  },
  
  copyCheckoutElements: function() {
    $('billing_address_first_name_display').update($F('billing_address_first_name'));
    $('billing_address_last_name_display').update($F('billing_address_last_name'));
    $('billing_address_telephone1_display').update($F('billing_address_telephone1'));
    $('billing_address_email_display').update($F('billing_address_email'));
    $('billing_address_street1_display').update($F('billing_address_street1'));
    $('billing_address_street2_display').update($F('billing_address_street2'));
    $('billing_address_city_display').update($F('billing_address_city'));
    $('billing_address_state_code_display').update($F('billing_address_state_code'));
    $('billing_address_postal_code_display').update($F('billing_address_postal_code'));

    // Copy the information from billing to primary
    if($F('is_different_shipping') != "true") {
      $('primary_address_first_name').value = $F('billing_address_first_name');
      $('primary_address_last_name').value = $F('billing_address_last_name');
      $('primary_address_telephone1').value = $F('billing_address_telephone1');
      $('primary_address_email').value = $F('billing_address_email');
      $('primary_address_street1').value = $F('billing_address_street1');
      $('primary_address_street2').value = $F('billing_address_street2');
      $('primary_address_city').value = $F('billing_address_city');
      $('primary_address_state_code').value = $F('billing_address_state_code');
      $('primary_address_postal_code').value = $F('billing_address_postal_code'); 
    }    

    $('primary_address_first_name_display').update($F('primary_address_first_name'));
    $('primary_address_last_name_display').update($F('primary_address_last_name'));
    $('primary_address_telephone1_display').update($F('primary_address_telephone1'));
    $('primary_address_email_display').update($F('primary_address_email'));
    $('primary_address_street1_display').update($F('primary_address_street1'));
    $('primary_address_street2_display').update($F('primary_address_street2'));
    $('primary_address_city_display').update($F('billing_address_city'));
    $('primary_address_state_code_display').update($F('primary_address_state_code'));
    $('primary_address_postal_code_display').update($F('primary_address_postal_code'));

    if($F('billing_address_street2') == 'Apt, Suite, Building (Optional)') {
      $('billing_address_street2_display').up('div').hide();
    } else {
      $('billing_address_street2_display').up('div').show();
    }

    if($F('primary_address_street2') == 'Apt, Suite, Building (Optional)') {
      $('primary_address_street2_display').up('div').hide();
    } else {
      $('primary_address_street2_display').up('div').show();
    }
  },
  
  validateUserInformation: function() {
    var validUserInformation = true;

    firstName = $('billing_address_first_name');
    lastName = $('billing_address_last_name');
    phone = $('billing_address_telephone1');
    email = $('billing_address_email');

    if((firstName.value == firstName.getAttribute('orig') || firstName.value == '') ||
       (lastName.value == lastName.getAttribute('orig') || lastName.value == '') ||
       (phone.value == phone.getAttribute('orig') || phone.value == '') ||
       (email.value == email.getAttribute('orig') || email.value == '')) {
         validUserInformation = false;
    }
    
    if($F('is_different_shipping') == "true" && validUserInformation != false) {
      firstName = $('primary_address_first_name');
      lastName = $('primary_address_last_name');
      phone = $('primary_address_telephone1');
      email = $('primary_address_email');
      
      if((firstName.value == firstName.getAttribute('orig') || firstName.value == '') ||
         (lastName.value == lastName.getAttribute('orig') || lastName.value == '') ||
         (phone.value == phone.getAttribute('orig') || phone.value == '') ||
         (email.value == email.getAttribute('orig') || email.value == '')) {
           validUserInformation = false;
      }
    }
    
    return validUserInformation;
  },
  
  validateShippingInformation: function() {
    var validAddress = true;
    
    street1 = $('billing_address_street1');
    city = $('billing_address_city');
    state = $('billing_address_state_code');
    postal_code = $('billing_address_postal_code');
    
    if((street1.value == street1.getAttribute('orig') || street1.value == '') ||
       (city.value == city.getAttribute('orig') || city.value == '') ||
       (state.value == state.getAttribute('orig') || state.value == '') ||
       (postal_code.value == postal_code.getAttribute('orig') || postal_code.value == '')) {
         validAddress = false;
    }
    
    if($F('is_different_shipping') == "true" && validAddress != false) {
      street1 = $('primary_address_street1');
      city = $('primary_address_city');
      state = $('primary_address_state_code');
      postal_code = $('primary_address_postal_code');

      if((street1.value == street1.getAttribute('orig') || street1.value == '') ||
        (city.value == city.getAttribute('orig') || city.value == '') ||
        (state.value == state.getAttribute('orig') || state.value == '') ||
        (postal_code.value == postal_code.getAttribute('orig') || postal_code.value == '')) {
      }
    }
    
    return validAddress;
  },
  
  validateCreditCardInformation: function() {
    var validCreditCard = true;
    
    cardNumber = $('order_card_number');
    cardMonth = $('order_card_expiration_month');
    cardYear = $('order_card_expiration_year');
    cardCVC = $('order_card_cvc');
    
    if((cardNumber.value == cardNumber.getAttribute('orig') || cardNumber.value == '') ||
      (cardMonth.value == '') || (cardYear.value == '') ||
      (cardCVC.value == cardCVC.getAttribute('orig') || cardCVC.value == '')) {
        validCreditCard = false;
    }
    
    return validCreditCard;
  },
  
  validateCreditCardValidity: function(cart_id) {
    $("checkout-submit").disable();
    $('information-notice').hide();
    
    if (DFD.builder.validateCreditCardInformation() && DFD.builder.validateUserInformation()) {
      var params = '';
      params += 'first_name=' + $F('billing_address_first_name');
      params += '&last_name=' + $F('billing_address_last_name');
      params += '&cc_num=' + $F('order_card_number');
      params += '&cc_exp_m=' + $F('order_card_expiration_month');
      params += '&cc_exp_y=' + $F('order_card_expiration_year');
      params += '&cc_cvc=' + $F('order_card_cvc');
      
      new Ajax.Request('/validate-credit-card', {
        asynchronous: true,
        evalScripts: true,
        method: 'get',
        parameters: params,
        onSuccess: function(response) {
          $('creditCardError').hide();
          $('creditCardSuccess').show();
          $('checkout-submit').disable();
          $('formId_' + cart_id).submit();
          return;
        },
        onFailure: function(response) {
          $('creditCardSuccess').hide();          
          $('creditCardError').show();
          $('information-notice').show()
          new Effect.Shake('information-notice', {duration: 0.5, distance: 4});
          $$("#payment-information fieldset").each(function(s) {
            new Effect.Highlight(s, { startcolor: '#ffff99', endcolor: '#EBEBEB'});
          });
          $$("#payment-information div").each(function(s) {
            new Effect.Highlight(s, { startcolor: '#ffff99', endcolor: '#EBEBEB'});
          });
          new Effect.Shake('payment-information', {duration: 0.5, distance: 4});
          
          $('checkout-submit').enable();
        }
      });
    }
    
    window.setTimeout(function() {
      new Effect.Fade('information-notice');
    }, 5000);
  },
  
  enableBillingAddress: function() {
    $('is_different_shipping').value = "true";
    
    $$('.same-shipping-address-link').each(function(s){
      s.show();
    });
    $$('.different-shipping-address-link').each(function(s){
      s.hide();
    });
    
    new Effect.BlindDown('shipping-address');
  },
  
  disableBillingAddress: function() {
    $('is_different_shipping').value = "false";
    
    $$('.same-shipping-address-link').each(function(s){
      s.hide();
    });
    $$('.different-shipping-address-link').each(function(s){
      s.show();
    });
    
    if($('shipping-address').visible()) {
      new Effect.BlindUp('shipping-address');
    } else {
      new Effect.BlindUp('shipping-address-display');
    }

  },
  
  editShippingAddress: function() {
    new Effect.BlindUp('billing-address-display');
    new Effect.BlindDown('billing-address');
  },

  saveShippingAddress: function() {
    new Effect.BlindUp('billing-address');
    new Effect.BlindDown('billing-address-display');
  },

  editBillingAddress: function() {
    new Effect.BlindUp('shipping-address-display');
    new Effect.BlindDown('shipping-address');
  },

  saveBillingAddress: function() {
    new Effect.BlindUp('shipping-address');
    new Effect.BlindDown('shipping-address-display');
  },
  
  determineCardType: function() {
    var cc_type = '';
    var cc_number = $F('order_card_number');
    if((cc_number.length == 16 || cc_number.length == 13) && cc_number.charAt(0) == '4') {
      cc_type = "visa";
    }
    
    if(cc_number.length == 16) {
      if(cc_number.charAt(0) == '5') {
        cc_type = "mastercard";
      }
      
      if(cc_number.charAt(0) == '6' && cc_number.charAt(1) == '0' && cc_number.charAt(2) == '1' && cc_number.charAt(3) == '1') {
        cc_type = "discover";
      }
    }
    
    if(cc_number.length == 15) {
      if(cc_number.charAt(0) == '3') {
        if(cc_number.charAt(1) == '4' || cc_number.charAt(1) == '7') {
          cc_type = "amex";
        }
      }
    }
    
    if(cc_type != '') {
      $('mastercard').src = "/images/dragonfly/mastercard_grey.png";
      $('visa').src = "/images/dragonfly/visa_grey.png";
      $('amex').src = "/images/dragonfly/amex_grey.png";
      $('discover').src = "/images/dragonfly/discover_grey.png";
      
      $(cc_type).src = "/images/dragonfly/" + cc_type + ".png";
      $('order_card_type').value = cc_type;
    } else {
      $('mastercard').src = "/images/dragonfly/mastercard.png";
      $('visa').src = "/images/dragonfly/visa.png";
      $('amex').src = "/images/dragonfly/amex.png";
      $('discover').src = "/images/dragonfly/discover.png";
      $('order_card_type').value = '';
    }
  },
  
  requestShippingUpdate: function(shipping_request_path) {
    $('checkout-submit').disable();
    new Ajax.Request(shipping_request_path, {
      asynchronous: true,
      evalScripts: true,
      method: 'get'});
  },
  
  gatherShippingInformation: function(get_user_location_path) {
    var params = '';
    params += 'zip_code=' + $F('billing_address_postal_code') + '&address_type=billing';
    
    new Ajax.Request(get_user_location_path, {
      asynchronous: true,
      evalScripts: true,
      parameters: params,
      method: 'get'});    
  },
  
  updateGiftWrapInformation: function(product_id, qty, update_path) {
    var output = "";
    for(var i=1;i<qty+1;i++) {
      msg = $F('gift_[' + product_id + '][' + i + '][message]');
      if(msg != 'Enter a Gift Message')
        output += msg;
      output += "||";
      output += $('gift_[' + product_id + '][' + i + '][wrapped]').checked
      output += "::";
    }
    $('gift_[' + product_id + '][details]').value = output;
    
    silenceAjaxRequest = true;
    
    var params = 'id=' + product_id + '&details=' + output;
    new Ajax.Request(update_path, {
      asynchronous: true,
      evalScripts: true,
      parameters: params,
      method: 'post'});
      
    silenceAjaxRequest = false;
  }
}

// In this doesn't seem to work with tabbing, but Hans said
// that is fine, given most people will click.  Those that tab
// are probably tech savvy enough to not be concerned with the
// cursor position
DFD.cursor = {
    setCaretTo: function(obj, pos) { 
	    if(obj.createTextRange) { 
	        var range = obj.createTextRange(); 
	        range.move("character", pos); 
	        range.select(); 
	    } else if(obj.selectionStart) {
	        obj.focus(); 
	        obj.setSelectionRange(pos, pos); 
	    }
	}
}

DFD.effects = {
  blindUpDown: function(obj) {
    if($(obj).visible()) {
      new Effect.BlindUp(obj);
    } else {
      new Effect.BlindDown(obj);
    }
  }
}

document.observe("dom:loaded", function(){
  //Attach popup events to browse windows
  //Attach loading indicator to all click events on a tags
  
  $('loading-shadow').hide();
  var loading = $('loading');
  loading.hide();
  loading.style.zIndex=1000;
  loading.style.bottom='50%';
  loading.style.left='45%';
  loading.style.position='fixed';
  $$('.popuplink').each(function(link) { new PopupLink(link) });
  
  var container = $(document.body)
  if (container) {
    addCheckoutObservers();
    
    container.observe('click', function(e) {
      var el = e.element();
      if (el.match('.ajax_link a')) {
        this.MBoverlay = new Element("div", { id: "MB_overlay"}).setStyle({opacity: '0.6'});
        new Effect.Fade('main-products');
        new Ajax.Request(el.href, {
          asynchronous: true,
          evalScripts: true,
          onComplete: function(request) {new Effect.Appear('main-products');},
          method: 'get'});
        e.stop();
      }
    });
    
  }
});

function addCheckoutObservers() {
  $$(".checkoutField").each(function(s) {
    s.observe('focus', function() {
      if(s.value == s.getAttribute('orig')) {
        DFD.cursor.setCaretTo(s, 0);
      }
      DFD.builder.highlight(s, s.getAttribute('orig'));
    });
    
    s.observe('click', function() {
      if(s.value == s.getAttribute('orig')) {
        DFD.cursor.setCaretTo(s, 0);
      }                       
    });
    
    s.observe('keydown', function() {
      DFD.builder.clearDefault(s, s.getAttribute('orig'));
    });
    
    s.observe('keyup', function() {
      DFD.builder.enableDisableCheckoutButton();
    });
    
    s.observe('blur', function() {
      DFD.builder.setDefault(s, s.getAttribute('orig'));
    });
  });
}


// http://www.tizag.com/javascriptT/javascriptform.php

function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
        return true;
	}else{
		return false;
	}
}

// If the element's string matches the regular expression it is all numbers
function isNumeric(elem){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		return false;
	}
}

// If the element's string matches the regular expression it is all letters
function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}