/* HomeGoods ~ JAVASCRIPT Quiz

	Author: Joel Nagy | Quiz
	Last Modified: July 13th, 2009 11:30:51 AM EST

	Dependency: prototype 1.7 and scriptaculous 1.8 
	Dependency: scroller.js
*/

// NAMESPACE
if (Quiz == null) // check for existence of namespace
var Quiz = {};

Quiz.Results = [];

/* Scroller Modifications */
if (Scroller == null)
	var Scroller = {};
else {
	Scroller.autoScroll = false;
	clearTimeout(Scroller.timer);
	Scroller.timer = null;
}

document.observe('dom:loaded', function() {
	try {
		// Pre-load images
		var I = [
			'quiz8A_Classic.jpg', 'quiz8B_Classic.jpg', 'quiz8C_Classic.jpg', 'quiz8D_Classic.jpg',
			'quiz8A_Casual.jpg', 'quiz8B_Casual.jpg', 'quiz8C_Casual.jpg', 'quiz8D_Casual.jpg',
			'quiz8A_Modern.jpg', 'quiz8B_Modern.jpg', 'quiz8C_Modern.jpg', 'quiz8D_Modern.jpg',
			'quiz8A_Eclectic.jpg', 'quiz8B_Eclectic.jpg', 'quiz8C_Eclectic.jpg', 'quiz8D_Eclectic.jpg',
			'quiz2A.gif', 'quiz2B.gif', 'quiz2C.gif', 'quiz2D.gif',
			'quiz3A.jpg', 'quiz3B.jpg', 'quiz3C.jpg', 'quiz3D.jpg',
			'quiz7A.jpg', 'quiz7B.jpg', 'quiz7C.jpg', 'quiz7D.jpg'
		];
		
		
		//This is the problem
		/*for (var i = 0, l = I.length; i < l; i++) {
			var x = new Image();
			x.src = 'images/'+ I[i];
			Quiz.preLoadedImages.push(x);
		}*/
		//end of problem
		
		
				if ($('QuizForm'))
			$('QuizForm').reset();

		if ($('ScrollWrapper')) {
			if (window.opera || document.all) { // IE & Opera
				$$(".quizPic").each(function(o) {
					var l = o.descendants()[0];
					l.observe("click", function(e) {
						var F = this.form, FOR = '';
						// Acquire FORM ID
						if (F == null) {
							var A = this.ancestors();
							for (var j = 0, k = A.length; j < k; j++)
								if (A[j].tagName.toLowerCase() == 'form')
									F = A[j];
						}
						// Acquire ID for Radio Button
						if (this.getAttribute && this.getAttribute("for")) FOR = this.getAttribute("for");
							else if (this.readAttribute && this.readAttribute("for")) FOR = this.readAttribute("for");
								else FOR = this.next().id;
						$$("form#"+ F.id +" div.quizPic label a.select").each(function(o) { $(o).removeClassName('quizOn'); });
						$(this).childElements().each(function(o) { $(o).toggleClassName('quizOn'); });
						F[FOR].checked = true;
					});
				});
			} else {
				$$(".quizPic label").invoke("observe", "click", function(e) {
					$$("form#"+ this.form.id +" div.quizPic label a.select").each(function(o) { $(o).removeClassName('quizOn'); });
					$(this).childElements().each(function(o) { $(o).toggleClassName('quizOn'); });
					this.form[this.readAttribute("for")].checked = true;	
				});
			}
		}
		
		if (!document.all && $('QuizCover') && $('QuizCover').style) {
			$('QuizCover').style.opacity = '0.3';
			$('QuizCover').style.display = 'block';
		}
	} catch (e)  { }
}); //: dom:loaded

Quiz.noOp = function() {
	return;
}

Quiz.radioVal = function(rad) {
	for (var i = 0, l = rad.length; i < l; i++)
		if (rad[i].checked)
			return rad[i].value;
	return false;
}

Quiz.ZIP_REGEXP = new RegExp(/^[0-9]{5}$/); // US ZIP
Quiz.ZIP4_REGEXP = new RegExp(/^[0-9]{5}[ -_.x+|]?[0-9]{4}$/); // US ZIP+4
Quiz.CAPOSTAL_REGEXP = new RegExp(/^[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[0-9]{1}[ -_.x+|]?[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[ -_.x+|]?[0-9]{1}[ -_.x+|]?[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[0-9]{1}$/);
Quiz.STRING_REGEXP = new RegExp(/[\w\d\s\'\.\,]+/);

Quiz.validateZip = function(val, canada) {
	var zip = val.match(Quiz.ZIP_REGEXP);
	var postal = val.match(Quiz.CAPOSTAL_REGEXP);

	if ((zip != null && zip == val) || (canada != null && canada && postal != null && postal == val)) {
		return true;
	} else {
		return false;	
	}
}


// Added Cookie Handling for Store Locator Search
// By Ro Grossman 7/16/2009
Quiz.PATH = '/';

Quiz.setCookie = function( strName,
  strValue,
  dtExpires,
  strPath,
  strDomain,
  bSecure )
{
  document.cookie = strName + "=" + escape ( strValue )
    + ( ( dtExpires == null ) ? "" : ( "; expires=" + dtExpires.toGMTString() ) )
    + ( ( strPath == null ) ? "" : ( "; path=" + Quiz.PATH ) )
    + ( ( strDomain == null ) ? "" : ( "; domain=" + strDomain ) )
    + ( ( bSecure == true ) ? "; secure" : "" );
}

Quiz.getCookie = function( strName )
{
  var strArg = strName + "=";
  var iArgLength = strArg.length;
  var iCookieLength = document.cookie.length;
  var i = 0;

  while ( i < iCookieLength )
  {
    var j = i + iArgLength;

    if ( document.cookie.substring( i, j ) == strArg )
    {
      return Quiz.getCookieValue( j );
    }

    i = document.cookie.indexOf( " ", i ) + 1;

    if ( i == 0 )
    {
      break;
    }
  }
  return null;
}

Quiz.getCookieValue = function( iOffset )
{
  var iEndstr = document.cookie.indexOf ( ";", iOffset );

  if ( iEndstr == -1 )
  {
    iEndstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( iOffset, iEndstr ) );
}

Quiz.deleteCookie = function( strName )
{
  var dtExpiration = new Date();
  dtExpiration.setTime ( dtExpiration.getTime() - 1 );  // This cookie is history
  Quiz.setCookie( strName, "", dtExpiration, Quiz.PATH );
}


// End Cookie Handling

Quiz.showErrors = function(formID, errID, errs) {
	try {
		$(errID).style.visibility = 'hidden';
		if (errs.length > 0)
			$(errID).style.visibility = 'visible';

		$$('form#'+ formID +' input').each(function(o) { $(o).removeClassName('error'); });
		$$('form#'+ formID +' label').each(function(o) { $(o).removeClassName('error'); });
		for (var i = 0, l = errs.length; i < l; i++) {
			if (errs[i] != null) {
				$(errs[i]).addClassName('error');
				$(formID).getElementsBySelector("label[for='"+ errs[i] +"']").each(function(o) { $(o).addClassName('error'); });
			}
		}
	} catch (e) { }
}

Quiz.start = function(F) {
	// Vaidate Questions
	var errs = [];
	var v1 = $('q0name').value, v2 = $('q0zip').value;
	
	if (!Quiz.validateZip(v2))
		errs[errs.length] = 'q0zip';
	if (v1.match(Quiz.STRING_REGEXP) != v1)
		errs[errs.length] = 'q0name';
	if (errs.length <= 0) {
		Quiz.showErrors('QuizForm', 'Error_q0', []);
		//Scroller.goRight();
		// store zip value to cookie
		Quiz.setCookie('MyZip',v2);
		// submit form
		$('QuizForm').submit();
	} else {
		Quiz.showErrors('QuizForm', 'Error_q0', errs);
		if (F) return false;
	}
}

Quiz.answer = function(id, val, beforeNext, ondone) {
	if (val == '' || val == false) {
		Quiz.showErrors('q'+id, 'Error_q'+id, [null]);
		return;
	} else
		Quiz.showErrors('q'+id, 'Error_q'+id, []);
	
	Quiz.Results[id-1] = val;

	// omniture tracking by ro grossman 7/21/2009
	var s=s_gi('tjxhomegoods');
	s.linkTrackVars='prop6';
	s.prop6='q'+id+':';
	s.tl(this,'o','HOM_q'+id);
	// end omniture tracking
	
	if (beforeNext != null)
		beforeNext();

	if (ondone == null) {
		Quiz.count(id+1);
		Scroller.goRight();
	} else
		ondone();
}

Quiz.previous = function(id) {
	Quiz.count(id-1);
	  // omniture tracking by ro grossman 7/21/2009
	  var s=s_gi('tjxhomegoods');
	  s.linkTrackVars='prop6'; // tjxdev prop4
	  s.prop6='-q'+id+':';
	  s.tl(this,'o','HOM_q'+id+'-');
	  // end omniture tracking	
	Scroller.goLeft();
}

Quiz.count = function(id) {
	$('quizNumbers').innerHTML = id +' of 10';
}

Quiz.prepQuiz8 = function() {
	var six = {A: 'Modern', B: 'Classic', C: 'Eclectic', D: 'Casual'}; // q7
	var one = {A: 'Casual', B: 'Classic', C: 'Modern', D: 'Eclectic'}; // q2
	var tr3 = {A: 'Eclectic', B: 'Classic', C: 'Casual', D: 'Modern'}; // q4
	six = eval('six.'+ Quiz.Results[6]); // q7
	one = eval('one.'+ Quiz.Results[1]); // q2
	tr3 = eval('tr3.'+ Quiz.Results[3]); // q4

//	var x = six == one? six: (six == tr3? six: (one == tr3? one: six));
	var x = six == one? one: (six == tr3? tr3: (one == tr3? one: one)); // if any are same go, else q2

	// x: A, B, C, D
	$("q8Apic").src = 'images/quiz8A_'+ x +'.jpg';
	$("q8Bpic").src = 'images/quiz8B_'+ x +'.jpg';
	$("q8Cpic").src = 'images/quiz8C_'+ x +'.jpg';
	$("q8Dpic").src = 'images/quiz8D_'+ x +'.jpg';
}

Quiz.submit = function() {
	// go through all the quiz questions, get the answers, put into the QuizForm and supply the result string
	try {
		var Q = '';
		for (var i = 0, l = Quiz.Results.length; i < l; i++)
			Q+=Quiz.Results[i];
		Q+=Math.floor(Math.random() * (9999 - 1001 + 1)) + 1001;
		var res = Base64.encode(Q);
		if (res.slice(res.length-2) == '==') res = res.slice(0, res.length-2)+'$';
		if (res.slice(res.length-1) == '=') res = res.slice(0, res.length-1);
		$('QuizForm').action = './quiz.asp?q='+ res;
		
		// omniture trcking
		Quiz.completed();
		
		$('QuizForm').submit();
	} catch (e) { }
}

Quiz.completed = function() {
		// omniture tracking by ro grossman 7/21/2009
		var s=s_gi('tjxhomegoods');
		s.linkTrackVars='events';
		s.linkTrackEvents='event15';
		s.events='event15';
		s.tl(this,'o','HOM_Quiz_Completed');
		// end omniture tracking	
}

Quiz.pop = function(url, width, height) {
	width = width == null? 854: width;
	height = height == null? 600: height;
	window.open(url, 'hghq_pop', 'status=0,toolbar=0,location=0,menubar=0,resizable=1,scrollbars=1,width='+ width +',height='+ height);
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}