// Cookie, by Carlos Reche
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

/* Displays the element identified by id as a modal dialog */
function showDialog(element, width, height) {
  if (width == null) {
    width = 300;
  }
  if (height == null) {
    height = 400;
  }
  
  element = $(element);
  
  /* darken the screen */
  darkThing = new Element('div', {id: 'darkThing'});
  darkThing.setStyle({opacity: 0.6, backgroundColor: '#000', 
      position: 'fixed', top: 0, left: 0, 
      height: '100%',
      width: '100%',
      zIndex: 10});
  $$('body')[0].insert(darkThing);
  
  /* display the element centered in the viewport */
  outerDialog = new Element('div', {id: 'outerDialog'});
  outerDialog.setStyle({width: width + 'px', 
												marginLeft: 'auto', marginRight: 'auto',
      									background: "#fff", zIndex: 11, opacity: 1, 
												position: 'fixed', top: '100px',
												left: (document.viewport.getWidth() - width) / 2 + 'px'});
  $$('body')[0].insert(outerDialog);
  
  /* put an inner element in so we can pad it */
  dialog = new Element('div', {id: 'dialog'});
  dialog.setStyle({marginTop:"25px", padding: "0px 15px 15px 15px", overflow: 'auto', height: height + "px"});
  dialog.insert(element);
  dialog.show();
  element.show();
  outerDialog.insert(dialog);
  
  /* add a close link to the top of the dialog */
  controlBar = new Element('div');
  controlBar.setStyle({textAlign: "right", background: "#fff", marginBottom: "7px" });
  closeLink = new Element('a', {href: "#", id: "dialogClose"});
  Event.observe(closeLink, 'click', function(e) {
    hideDialog();
    Event.stop(e);
  });
  closeLink.insert("Close");
  controlBar.insert(closeLink);
  outerDialog.insert({top: controlBar});
  
  closeLink.show();
  outerDialog.show();
}

/* hides a dialog */
function hideDialog() {
  /* hide the content in the dialog */
  $('dialog').firstDescendant().hide();
  $$('body')[0].insert($('dialog').firstDescendant());
  
  /* ditch the dialog and the darkThing */
  $('darkThing').remove();
  $('outerDialog').remove();
}

function toggleLoginBar() {
  if ($('utility_bar').hasClassName('open')) {
		if (!$('message').empty()) {
			$('message').hide();
			$('utility_section').setStyle({visibility:'visible'});
		} else {
	    $('login_tab').removeClassName('cancel');
	    $('utility_bar').removeClassName('open');
		}
  }
  else {
    $('login_tab').addClassName('cancel');
	  $('utility_bar').addClassName('open');
	}
}


$(document).observe('dom:loaded', function() {
	findToggleInputs();
});

function findToggleInputs() {
	$$('input.toggle').each(function(elem) {
		var real_type = elem.type;
		var first_value = elem.getValue();
		var focus_target = elem;
		var blur = function() {if(this.value == '') { this.value = first_value; }};
		var focus = function() {if(this.value == first_value) { this.value = ''; }};
		
		if(real_type == 'password') {
			html = '<input type="text" id="' + elem.id + '_fake" class="' + elem.readAttribute('class') + '" value="' + elem.value + '" />';
			elem.insert({before: html});
			elem.hide();
			
			focus_target = $(elem.id + "_fake");
			focus = function() { if(this.value == first_value) {
				this.hide();elem.show();elem.value = '';elem.focus(); }
			};
			blur = function() { if(this.value == '') {
				this.hide();$(this.id + '_fake').show(); }
			};
		}
			
		focus_target.observe('focus', focus);
		elem.observe('blur', blur);
	});
}

function resetInquiry() {
	$('pleaseComplete').hide();
	$('name').removeClassName('error');
	$('email').removeClassName('error');
	$('phone').removeClassName('error');
	$('requestSuccess').hide();
	$('requestError').hide();
	$('inquiry').reset();
	$('inquiry').show();
}

function inquirySubmit() {
	action = $('inquiry').readAttribute('action');
	error = false;
	if ($F('name') == '' || $F('email') == '' || $F('phone') == '') {
		error = true;
		$('pleaseComplete').show();
		$('name').addClassName('error');
		$('email').addClassName('error');
		$('phone').addClassName('error');
	} else { 
		$('pleaseComplete').hide();
		$('name').removeClassName('error');
		$('email').removeClassName('error');
		$('phone').removeClassName('error');
	}
		
	if (!error) {
		new Ajax.Request(action, {
			asynchronous:true,
			evalScripts:true,
			parameters:Form.serialize('inquiry'),
			onSuccess: function(response) {
			  $('inquiry').hide();
			  $('requestError').hide();
				$('requestSuccess').show();
			},
			onFailure: function(response) {
				$('requestError').show();
			}
		});
	}
}
/* store page */

var added_products = [];
var sections = [];

function processProductChange(section) {
  sku = $(section + '_sku').getValue();
  if(sku != '') {
    quantity = parseInt($(section + '_quantity').getValue());
    
    if (!isNaN(quantity) && quantity > 0) {
      price = products[sku]["price"];
			addProduct(section, quantity, sku, price.toFixed(2));
    } else {
      price = 0;
      quantity = 0;
			removeProduct(section)
    }

    new_amount = quantity * price;
  } else {
		new_amount = 0;
		removeProduct(section);
	}
	$(section + '_subtotal').update(formatCurrency(new_amount));
}

function addProduct(section, quantity, sku, price) {
	/*
  <li id="complete_cart_item">
    <h4 id="complete_cart_description">NCover 3, Complete</h4>
    <table>
      <tr>
        <td>
          <span id="complete_cart_quantity">1</span> x $<span id="complete_cart_base">479.00</span> =
        </td>
        <td class="subtotal">
         $<span id="complete_cart_subtotal">479.00</span>
        </td>
      </tr>
    </table>
  </li>
  */
	var cart_items = $("cart_items");
	
	var desc = products[sku]["description"];
	
	if (!$(section + "_cart_item")) {
		var li = new Element('li', {id: section + '_cart_item', style: 'display: none;'});
		var h4 = new Element('h4', {id: section + '_cart_description'});
		li.insert(h4);
		var table = new Element('table');
		var tbody = new Element('tbody');
		var tr = new Element('tr', {id: section + '_cart_info_row'});
		var first_td = new Element('td');
		var item_quantity = new Element('span', {id: section + '_cart_quantity'});
		var base = new Element('span', {id: section + '_cart_base'});
		first_td.insert(item_quantity).insert('&nbsp;x $').insert(base).insert(' =');
		tr.insert(first_td);
		var subtotal_td = new Element('td', {'class':'subtotal'});
		var subtotal = new Element('span', {id:section + '_cart_subtotal'});
		subtotal_td.insert('$');
		subtotal_td.insert(subtotal);
		tr.insert(subtotal_td);
		tbody.insert(tr);
		table.insert(tbody);
		li.insert(table);
		cart_items.insert(li);
		added_products.push(section);
		attachProductClassNames();
		li.appear({duration:0.3});
	}
	$(section + '_cart_description').update(desc);
	$(section + '_cart_quantity').update(quantity);
	$(section + '_cart_base').update(formatCurrency(price));
	$(section + '_cart_subtotal').update(formatCurrency(quantity * price));
	$(section + '_cart_info_row').highlight({startcolor:'#fff3bc', duration:0.7, queue: {position: 'end', scope:section + '_cart_info_row', limit:1}});
	$('no_items').hide();
}
function removeProduct(section) {
	var cart_item = $(section + '_cart_item');
	if (cart_item) {
		cart_item.remove();
		added_products = added_products.without(section);
		attachProductClassNames();
	}
	if (added_products.length == 0) {
		$('no_items').show();
	}
}
function attachProductClassNames() {
	added_products.each(function(section, index) {
		if (index == (added_products.length - 1)) {
			$(section + '_cart_item').addClassName('last');
		} else {
			$(section + '_cart_item').removeClassName('last');
		}
	});
}
function fetchKeyCode() {
	key = $F('key_code');
	section_id = key + '_section'
	if (key != '' && key != 'Enter Your Key Code') {
		if (!$('keycode_message_area').visible()) {
			new Effect.BlindDown('keycode_message_area', {duration: 0.5});
		}
		if ($(section_id)) {
			$('keycode_fetch_text').update('Renewals and upgrades have already been fetched for that key code.');
			$('keycode_fetch_text').setStyle({color: "#14860B"});
		} else {
			new Ajax.Request('/quotes/fetch_keycode_upgrades', {
				method: 'get',
				parameters: { key_code: key },
				onCreate: function() {
					$('keycode_fetch_text').update('Fetching Key Code...');
					$('keycode_fetch_text').setStyle({color: "#215DA1"});
				},
				onSuccess: function(data) {
					response = data.transport.responseText;
				
					if (response == 'invalid_key') {
						$('keycode_fetch_text').update('The key code you entered is not valid.');
						$('keycode_fetch_text').setStyle({color: "#994800"});
					} else if (response == 'nothing_available') {
						$('keycode_fetch_text').update('The key code you entered does not have any renewals or upgrades available at this time.');
						$('keycode_fetch_text').setStyle({color: "#14860B"});
					} else {
						new Insertion.After('renew_upgrade_bar', response);
						$(section_id).appear();
						new Effect.BlindUp('keycode_message_area', {duration: 0.5});
					}
					$('key_code').value = 'Enter Your Key Code'
				}
			});
		}
	}
}
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}

var valid_pieces = ['dev-team', 'build-server', 'qa-team', 'qa-manager', 'dev-manager', 'vp-director'];

function handleNCoverFits() {
	$$('div.puzzle-nav a').each(function(elem) {
		var ref = elem.href.split('#')[1];
		elem.observe('click', function(e) {
			focusProductPiece(ref);
			e.stop();
		});
	});
	var split_location = document.location.toString().split('#');
	if(split_location.length == 2) {
		var focus = split_location.pop().split('?').shift();
		if(focusProductPiece(focus)) {
			new Effect.ScrollTo('ncover-fits');
		}
	}
}
function focusProductPiece(piece_id) {
	if (valid_pieces.indexOf(piece_id) != -1) {
		$$('.puzzle-piece').each(function(p){p.removeClassName('show');})
		$(piece_id).addClassName('show');
		$$('.arrow').each(function(a){a.removeClassName('show');});
		$$('.' + piece_id).each(function(a){a.addClassName('show');});
		$$('#ncover-fits-diagram .label').each(function(l){
			l.removeClassName('focus');
		});
		$(piece_id + '-label').addClassName('focus');
		return true;
	} else {
		return false;
	}
}

function registerValidateEmail() {
  var domains = $H({
    "mailinator.com": "bogus",
    "spamcorptastic.com": "bogus",
    "guerillamailblock.com": "bogus",
    "dodgit.com": "bogus",
    "mintemail.com": "bogus",
    "gmail.com": "personal",
    "yahoo.com": "personal",
    "hotmail.com": "personal",
    "bsnow.com": "bogus"
  });

  var parts = $('user_email').value.split("@", 2);
  var status = null;
  if(parts.length == 2) {
    var domain = parts[1];
    status = domains.get(domain)
  }
  
  if(status == "bogus") { 
    $('email_message').update("Don't be that person. Give us your real address.");
    $('email_message').show();
  }
  else if(status == "personal") {
    $('company_message').update("If this is for work, we'd love to know who you work for.");
    $('company_message').show();
  }
  else {
    $('email_message').update();
    $('email_message').hide();
    $('company_message').update();
    $('company_message').hide();
  }
}

/* shows the learn menu */
function showLearnMenu() {
  if ($('learnLink').hasClassName('learn')) {
    toggleLearnMenu();
  }
}

function toggleLearnMenu() {
  $('learnLink').toggleClassName('learn_clicked');
  $('learnLink').toggleClassName('learn');
  
  if ($('learnLink').hasClassName('learn_clicked')) {
    $('learnMenu').clonePosition($('learnLink'), { setWidth: false, 
        setHeight: false, offsetTop: 47 });
    $('learnMenu').show();
  }
  else {
    $('learnMenu').hide();
  }
}

Event.observe(document, 'mouseover', function(e) {
  var eventElement = Event.element(e);
  
  if (eventElement == $('learnLink') || eventElement.up("#learnLink") ||
      eventElement == $('learnMenu') || eventElement.up("#learnMenu")) {
    return;
  }
  
  if ($('learnLink').hasClassName('learn_clicked')) {
    toggleLearnMenu();
  }
})