var processpath = '/shop/processprofile';
var showMissing = true;
var missing = [];

$(document).ready(function() {
	disableFormFailover();
	initializePage();
	attachEvents();
	initTapeRequest();
});

function disableFormFailover() {
	$('input#js-status').val('enabled');
}

function initializePage() {
	$('body').addClass('js');
	freetext.setDisplay('hear-about', 8);
	freetext.setDisplay('occupation', 7);
	setupStylePopups();
	setupPalettePopup();
}

function attachEvents() {
	attachCheckBoxEvents();
	attachSimpleEvents();
	attachMeasurementEvents(); 
	attachConverterEvent();
	attachAgeEvent();
	attachStyleAgeEvent();
	attachHearAboutEvent();
	attachOccupationEvent();
	attachIseamPopup();
}

function toggleOptIn(){
	 if (document.getElementById('subscribe').checked){
		document.getElementById('reg-optout-text').style.display='none';
		document.getElementById('reg-optin-text').style.display='';
	 }
	 else{
		document.getElementById('reg-optin-text').style.display='none';
		document.getElementById('reg-optout-text').style.display='';
	 }
}

function attachCheckBoxEvents() {

	$('#profile input[type=checkbox]').change(function() {
		if (this.checked) {
			sendValue('set', this);
		}
		else {
			sendValue('unset', this);
		}
	});
}

function sendValue(action, element) {
	var url = processpath;
	var parameters = {
			'value': element.value
		, 'attribute': element.name
		, 'action' : action
	}
	$.post(url, parameters, null);
}

function attachSimpleEvents() {
	$('#profile input[type=radio]')
		.add('#profile select')
		.not('#converter input')
		.change(function() {
		sendValue('update', this);
	});
}

function attachMeasurementEvents() {

	$('.measurements input[type=text]').each(function() {
		this.model = new Measurement(this);
		this.defaultVal = $(this).val();
	});

	$('.measurements input[type=text]').focus(function() {
		this.defaultVal = $(this).val();
		this.model.displayDiagram();
		this.model.displayInstructions();
	});
	$('.measurements input[type=text]').blur(function() {
		if(this.defaultVal != $(this).val()){
			this.model.save();
		}
		this.model.hideDiagram();
		this.model.hideInstructions();
	});

	$('.measurements input[type=text]').keypress(function(ev){
		if(ev.keyCode == 13){
			$(this).blur();
			return false;
		}
	});
}

function Measurement(element) {
	this.element = element;
	this.key = 'attribute_' + element.alt;
	this.error = "";

	var path = imgpath;
	var source = measurementData[this.key]['diagram'];

	this.diagram = path + source;
	this.defaultDiagram = path + 'default.gif';

	this.min = measurementData[this.key]['range']['min'];
	this.max = measurementData[this.key]['range']['max'];
	this.inches = element.value;
	this.cm = this.getCM(this.inches);
	if ( showMissing && this.isMissing() ) {
		this.highlight();
	}
}

Measurement.prototype.isMissing = function() {
	var isMissing = false;
	for (var i = 0; i < missing.length; i++) {
		var matches = ('attribute_' + missing[i]) == this.key;
		if (matches) {
			isMissing = true;
		}
	}
	return isMissing;
}

Measurement.prototype.highlight = function() {
	$(this.element).parent().addClass('missing');
}

Measurement.prototype.getCM = function(value) {
	if ( value == "" ) {
		return "";
	}
	var cm = new Number(value * 2.54);
	return cm.toFixed(1);
}

Measurement.prototype.getInches = function(value) {
	var inches = new Number(value / 2.54);
	return inches.toFixed(1);
}

Measurement.prototype.save = function() {
	this.clearErrorMessage();
	this.validate();
	if (this.isValid()) {
		this.storeValue();
		this.replicateValue();
		this.send();
		this.setNotMissing();
	}
	else {
		this.showErrorMessage();
	}
}

Measurement.prototype.setNotMissing = function() {
	$(this.element).parent().removeClass('missing');
}

Measurement.prototype.storeValue = function() {
	if (isCM()) {
		this.saveCM();
	}
	else {
		this.saveInches();
	}
}

Measurement.prototype.replicateValue = function() {
	var selector = "." + this.element.className;
	$(selector).val(this.element.value);
}

Measurement.prototype.saveCM = function() {
	this.cm = this.element.value;
	this.inches = this.getInches(this.cm);
}

Measurement.prototype.saveInches = function() {
	this.inches = this.element.value;
	this.cm = this.getCM(this.inches);
}

Measurement.prototype.send = function() {
	var url = processpath;
	var parameters = {
			'value': this.inches
		, 'attribute': this.element.name
		, 'action' : 'update'
	}
	$.post(url, parameters, null);
}

Measurement.prototype.validate = function() {
	this.validateNumeric();
	this.validateRange();
}

Measurement.prototype.validateNumeric = function() {
	if (isNaN(this.element.value)) {
		this.error += "Please enter a number. ";
	}
}

Measurement.prototype.validateRange = function() {
	var min = this.min;
	var max = this.max;
	if (isCM()) {
		min = Math.floor(this.getCM(min));
		max = Math.ceil(this.getCM(max));
	}
	var tooSmall = this.element.value < min;
	var tooBig = this.element.value > max;
	if (tooSmall || tooBig) {
		this.error += "Please enter a number between " + min + " and " + max + ". ";
	}
}

Measurement.prototype.isValid = function() {
	if (this.error == "") {
		return true;
	}
	return false;
}

Measurement.prototype.clearErrorMessage = function() {
	this.error = "";
	$(this.element).parent().find('span').remove();
}

Measurement.prototype.showErrorMessage = function() {
	var message = $("<span>" + this.error + "</span>");
	$(this.element).parent().append(message);
}

Measurement.prototype.displayInstructions = function() {
	var instructions = $(this.element).parents('li').children('.instructions').addClass('show');
}

Measurement.prototype.hideInstructions = function() {
	var instructions = $(this.element).parents('li').children('.instructions').removeClass('show');
}

Measurement.prototype.displayDiagram = function() {
	this.swapDiagram(this.diagram);
}

Measurement.prototype.hideDiagram = function() {
	this.swapDiagram(this.defaultDiagram);
}

Measurement.prototype.swapDiagram = function(source) {
	$('#' + this.getZone()).css('backgroundImage', 'url(' + source + ')');
}

Measurement.prototype.getZone = function() {
	return $(this.element).parents('ul').attr('class');
}

function attachConverterEvent() {
	$('#converter input').change(function() {
		if (isCM()) {
			convertToCM();
		}
		else {
			convertToInches();
		}
	});
}

function isCM() {
	var isCM = false;
	$('#converter #cm').each(function() {
		if (this.checked) {
			isCM = true;
		}
	});
	return isCM;
}

function convertToCM() {
	$('.measurements input[type=text]').each(function() {
		$(this).val(this.model.cm);
	});
}

function convertToInches() {
	$('.measurements input[type=text]').each(function() {
		this.value = this.model.inches;
	});
}


function attachAgeEvent() {
	$('#year-of-birth input').change(function() {
		var age = getAge();
		if (age >= 10 && age <= 105) {
			sendValue('dob', this);
		}
	});
}

function getAge() {
	var yearOfBirth = $('#year-of-birth input').val();
	var currentYear = new Date().getUTCFullYear();
	return currentYear - yearOfBirth;
}

function attachStyleAgeEvent() {
	$('#style-age input').change(function() {
			var styleAge = $(this).clone();
			styleAge.name = 'attribute_235';
			var decade = (getAge() / 10) | 0;
			var lowest = getLowestStyleAge();
			if (decade > lowest) {
				styleAge.value = 1;
			}
			else if (decade == lowest) {
				styleAge.value = 2;
			}
			else {
				styleAge.value = 3;
			}
			sendValue('update', styleAge);
	});
}

function getLowestStyleAge() {
	var inputs = $('#style-age input');
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].checked) {
			lowest = inputs[i].value;
			break;
		}
	}
	return lowest;
}

function setupStylePopups() {
	// KO - fancy footwork to keep the popup open
	// if you hover over the popup rather than the link
	$('#styles a').each(function() {
		var target = this.href;

		var on = function() {
			hold();
			showPopup(target);
		}

		var off = function() {
			timer = setTimeout(function() { hidePopup() }, 50);
		};

		var hold = function() {
			if (typeof(timer) != 'undefined') {
				clearTimeout(timer);
			}
		}

		$(this).hover(on, off);
		// delay turning the popup off
		$('#popups').hover(hold, off);
		$('#popups').click(off);
	}).click(function() { return false; });
}

(function($) {
	$.fn.clearClasses = function() {
		return this.each(function() {
			this.className = '';
		});
	}
}) (jQuery);

function showPopup(url) {
	var startTarget = url.indexOf('#');
	var target = url.substring(startTarget);
	var startClass = target.indexOf('-') + 1;
	var newClass = target.substring(startClass);
	var popup = $(target + ' img').clone();
	$('#popups').html(popup).clearClasses().addClass(newClass);
};


function hidePopup() {
	$('#popups').html('').clearClasses().addClass('hidden');
}

function setupPalettePopup() {
	var popup = $('#palette-popup img').clone().addClass('hide');
	$('#palette p').append(popup);
	var showPopup = function() {
		$('#palette p img').removeClass('hide').addClass('show');
	}
	var hidePopup = function() {
		$('#palette p img').removeClass('show').addClass('hide');
	}
	$('#palette p a').hover(showPopup, hidePopup).click(function() { return false; });
}

var freetext = {
	hideFreetext : function(container) {
		$('#' + container + ' .other').removeClass('show').addClass('hide');
	}
	,
	showFreetext : function(container) {
		$('#' + container + ' .other').removeClass('hide').addClass('show');
	}
	,
	setDisplay : function(element, other) {
		if ($('#' + element + ' select').val() == other) {
			this.showFreetext(element);
		}
		else {
			this.hideFreetext(element);
		}
	}
}

function attachHearAboutEvent() {
	$('#hear-about select').change(function() {
		freetext.setDisplay('hear-about', 8);
	});
	$('#hear-about input').change(function() {
			sendValue('hear', this);
	});
}

function attachOccupationEvent() {
	$('#occupation select').change(function() {
		freetext.setDisplay('occupation', 7);
	});
	$('#occupation input').change(function() {
			sendValue('update', this);
	});
}

var timeout = null;

function attachIseamPopup(){

	$('#inseam').mouseover( function(){
			
	 timeout = setTimeout( function(){
		
		 $('#inseam-popup').fadeIn( 'slow' );  if( detectIE() ){  hideElements() }

		}, 100);	

	 } );

	
	$('#inseam').mouseout( function(){

		setTimeout( function(){ clearTimeout( timeout ); 
			
		 $('#inseam-popup').fadeOut( 'slow' );  if( detectIE() ){  showElements() }

		 } , 10 ); 	
		
	 }  );
}


function hideElements(){

	$('#jeans-hips').css( 'visibility' , 'hidden' );
	$('#fit-waist').css( 'visibility' , 'hidden' );
	$('#fit-shoulder').css( 'visibility' , 'hidden' );
}


function detectIE(){

	var IE6 = (navigator.userAgent.indexOf("MSIE 6")>=0) ? true : false;
	return IE6;

}


function showElements (){

        $('#jeans-hips').css( 'visibility' , 'visible' );
        $('#fit-waist').css( 'visibility' , 'visible' );
        $('#fit-shoulder').css( 'visibility' , 'visible' );
}



function initTapeRequest() {
	$('.tapemeasure a.request-tapemeasure').click( function() {
		dimBackground();
		loadTapeRequest();
		return false;
	});
}

function dimBackground() {

//	$('<div id="overlay" />').css( 'opacity' , '.65' ).appendTo('#header');
	//document.getElementById( 'overlay' ).style.filter = 'alpha( opacity= "65" )';

//	$('#overlay').animate({ opacity : 0.65 , visibility : 'visible'  }, 500 );
	
	//setTimeout( function() { loadTapeRequest(); } , 500 );

}


function loadTapeRequest() {
	var url = tapemeasureLayer;

	$('#request').load(url, null, function(response) { initCloseTape(); }).addClass('active');
}
function initCloseTape() {
	var closeLayer = function() {
		$('#overlay').remove();
		$('#request').html('').removeClass('active');
	}

	$('#request a, #request input[type=submit]').click( function() {
		timer = setTimeout(function() { closeLayer() }, 500);
	});

	var options = {
		url : tapemeasureLayer
	};
	$('#request form').ajaxForm(options);

}
