
window.addEvent("domready", function(){
  if(!$('measure'))
    return false;

  var tables = $('measure').getElements('table');
  for (i=0; i<tables.length; i++) {
    if (tables[i].hasClass('lightup')) {
      var tableRows = tables[i].getElements('tr');
      for (j=0; j<tableRows.length; j++) {
        if (!tableRows[j].hasClass('nolink')){
          tableRows[j].addEvent('mouseover',function(){
            this.addClass('highlit');
          });
          tableRows[j].addEvent('mouseout',function(){
            this.removeClass('highlit');
          });
          if (!tableRows[j].getParent('table').hasClass('nolink')){
            tableRows[j].setStyle('cursor','pointer');
            tableRows[j].addEvent('click',function(){
              var tableRowsTd = this.getElements('td');
              var inserter = tableRowsTd.get('text')[0];
              if (this.getParent('table').hasClass('womens')){
                var gender = "/gender/%22womens%22";
               }
               else if (this.getParent('table').hasClass('mens')){
                var gender = "/gender/%22mens%22";
               }
               window.location = document.location.protocol + "//" + document.location.host + "/search/Shoes/filter/size/%22" + inserter + "%22/productTypeFacet/%22Shoes%22" + gender;
            });
          }
        }
      }
    }
  }
});

/*
window.addEvent('domready', function(){
    var brandsPopover = new ClickPop("#measurePop", "#measurePop", {'position': 'top', 'href': '/popovers/euroBrands.zml', 'close':'true' });    
});

window.addEvent('domready', function(){
  $('popwrapper').addEvent('click', function(e){
    $('measurePop').fireEvent('click', [e], 0);
    return false;
    });
});
*/

  /* Form Validation */
  (function(){
  //Attaching the onSubmit event to the login form
    var errors = "";
    var loginForm = document.getElementById('movieform');
    if (!loginForm){ return false; }
    loginForm.onsubmit = function () {
      return canSubmit(this);
    }


    function canSubmit(form) {
      var errors = "";
      //Hide error messeges if any are present
      var errorBefore = document.getElementById('movieform');
      var parentDiv = errorBefore.parentNode;
      var errorPlist = parentDiv.getElementsByTagName("p");
      for (i = 0; i < errorPlist.length; i++){
          if (errorPlist[i].className == "showError"){
            errorPlist[i].className = "hideError";
          }
        }       

      
      //count all form elements
      var elCount = document.movieform.elements.length;
      //all text elements are filled? 
      for (i=0;i<elCount;i++) {
        var formEl = document.movieform.elements[i];
        var type = formEl.type;
        var fieldName = formEl.name;

        // all text fields are filled
        if (type=="text" && !formEl.value) {
          var errors = "empty_txt";
        }
        var illegalChars = /^[\w ]*$/;
        // allow only letters, numbers, and underscores
        if (fieldName=="name" && !formEl.value.match(illegalChars)) {
          var errors = "illegal_namechar";
        } 
        var emailFilter=/^.+@.+\..{2,3}$/;
        if (fieldName=="email" && !(emailFilter.test(formEl.value))) { 
          var errors = "valid_email";
        }
        var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
        if (fieldName=="email" && formEl.value.match(illegalChars)) {
          var errors = "illegal_email";
        }
      }

      // email and verify email addy are the same
      if (document.movieform.email.value != document.movieform.email2.value) {
        var errors = "nomatch";
      }

      //terms are checked
      if (!document.movieform.terms.checked) {
        var errors = "terms";
      } 

      if (errors){
        showError();
        return false;
      }
      else{
        return true;
      }

      function showError() {
        //error arrays
        var errorMess = [];
        errorMess['empty_txt'] = 'Please provide your Name, Email and verify Email.';
        errorMess['terms'] = 'Please Accept the Terms and Agreements of this contest.';
        errorMess['nomatch'] = 'The email addresses do not match.';
        errorMess['illegal_namechar'] = 'Something seems to be wrong with your Name.';
        errorMess['illegal_email'] = 'Your email address contains illegal characters.';
        errorMess['valid_email'] = 'Pleae enter a valid email address.';


      var errorP = document.createElement("p");
      errorP.setAttribute("class", "showError");
      errorP.className = "showError";
      var errorPcontent = document.createTextNode(errorMess[errors]);
      errorP.appendChild(errorPcontent);

      var errorBefore = document.getElementById("movieform");
      var parentDiv = errorBefore.parentNode;
      
       parentDiv.insertBefore(errorP, errorBefore);

      }
    }
  })();


/* Clears text for input box */
var ClearInputs = new Class ({
	
  Implements: Options,
  options: {
    'showLabel':false,
		'inputValue':'title'
	},

	initialize: function(el, options) {
    this.setOptions(options);

    this.el = document.getElement(el);
		this.showLabel = this.options['showLabel'];
		inputValue = this.options['inputValue'];

		if (!this.el)
			return false;
		// Removes labels on input fields
		if (!this.showLabel)
			this.el.getElements('label').dispose();

		//Gather all elements we want for highlighting
		var formInput = this.el.getElements("input[type=text]");
		//Loop through elements and set value to selected attribute
		formInput.each(function(input){
			input.set('value', input.get(inputValue));
		});	

		// Clears text for input box 
		formInput.addEvent('focus', function() {
			if (this.get('value') == this.get(inputValue))
					this.set('value', '');		
		});

		// Sets text for input box 
		formInput.addEvent('blur', function() {  
			if (this.get('value') == '')
					this.set('value', this.get(inputValue));
		});
		formInput.fireEvent('blur');
	}
}); 

//Form Validation for Shameless Plug
window.addEvent('domready', function() {
	if (!document.getElement('#emailsignup'))
		return;
  new ClearInputs('#emailsignup');

  var myAsyncForm = new AsyncForm('#emailsignup',{
		'validations':[
			{'notequal':['shamelessplug-name', 'Name', 'Please enter your name.']},
			{'format':['shamelessplug-email', '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}', 'Please enter a valid email address.']}
		],
		'async': false,
		'onSuccess': function() {},
		'dispose': false 
  });
});

//Form Validation for Notify Me 
window.addEvent('domready', function() {
	if (!document.getElement('#emailnotifyme'))
		return;
  new ClearInputs('#emailnotifyme');

  var myAsyncForm = new AsyncForm('#emailnotifyme',{
		'validations':[
			{'format':['notifyme-email', '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}', 'Please enter a valid email address.']}
		],
		'async': false,
		'onSuccess': function() {},
		'dispose': false 
  });
});

//Product Slider
window.addEvent('domready', function() {
	window.slider = new Slider(".landing-page-promo #slider", {'width': 615});
});

//Landing Page Promo
var LandingPagePromo = new Class ({
	
  Implements: Options,
  options: {
		'futureDate':'2009,12,04',
		'title':'Hold Tight! The adidas Ball Becomes Available In:'
	},
	
	initialize: function(el, type, options) {
    this.setOptions(options);

    this.el = document.getElement(el);
		this.type = type;
		this.futureDate = this.options['futureDate'];
		var dateItems = this.futureDate.split(',');
		this.title = this.options['title'];

		if (!this.el)
			return false;

		switch(this.type) {
			case 'countdown':
				//Create countdown div and inject countdown div at the top of div
				var type  = new Element('div', {id: this.type});
				type.inject(this.el, 'top');

				//Create h4 and spans for countdown div 
				$(type).set('html', '<h4>' + this.title + '</h4><span id="countdays"></span><span id="counthours"></span><span id="countminutes"></span><span id="countseconds"></span>');

				//The future date
				this.timer(dateItems[0], dateItems[1], dateItems[2]);
				break;
		}
	},
	
	timer: function(yr, m, d) {
		var theyear = yr;
		var themonth = m;
		var theday = d;

		var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

		//Get Today's Date
		var today = new Date();
		var todayy = today.getYear();
		if (todayy < 1000)
			todayy+=1900;
		var todaym = today.getMonth();
		var todayd = today.getDate();
		var todayh = today.getHours();
		var todaymin = today.getMinutes();
		var todaysec = today.getSeconds();
		var todaystring = months[todaym] + ' ' + todayd + ', ' + todayy + ' ' + todayh + ':' + todaymin + ':' + todaysec;

		//Calculate Countdown Time
		var futurestring = months[m-1] + ' ' + d + ', ' + yr;
		var dd = Date.parse(futurestring) - Date.parse(todaystring);
		var dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
		var dhour = Math.floor((dd% (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
		var dmin = Math.floor(((dd% (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
		var dsec = Math.floor((((dd% (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);

		if ((dday <= 0) && (dhour <= 0) && (dmin <= 0) && (dsec <= 1)) {
			//Removes countdown after time is up
			$(this.type).dispose();
		} else {
			//Athis.eldds the time to the countdown
			$('countdays').set('html', '<strong>' + dday + '</strong> days');
			$('counthours').set('html', '<strong>' + dhour + '</strong> hours');
			$('countminutes').set('html', '<strong>' + dmin + '</strong> mins');
			$('countseconds').set('html', '<strong>' + dsec + '</strong> secs');
			setTimeout(this.timer.bind(this, [theyear, themonth, theday]), 1000);
		}
	}
}); 

