/**
 * @author Narayan
 */

/*===========Vignette Logic================= */

var lifeStyleStatments = 
[ "You want your contact lenses to keep up with your nonstop schedule.",
  "You value comfort in a pair of contact lenses.",
  "You have sensitive eyes.",
  "You want contact lenses that can accommodate your many activities.",
  "You're seeking a better alternative to eyeglasses.",
  "You sometimes fall asleep in your contact lenses.",
  "You would like more information on contact lenses for astigmatism.",
  "You have trouble reading the fine print and/or may wear bifocals."
];

var lifeStyleElements = 
[ "I exercise or play sports several times a week.",
  "I wear contacts first thing in the morning until late at night.",
  "Sometimes my eyes feel irritated.",
  "My eyes feel as good at the end of the day as they do at the beginning.", 
  "My eyes feel terrible by the end of the day.",
  "My eyes feel drier with every passing hour of the day.",
  "I spend a lot of time outside.",
  "I have or have been told that I have astigmatism.",
  "Clear vision is absolutely essential to my job.",
  "My job is demanding on my eyes.",
  "I need contact lenses with stamina.",
  "I work on a computer all day.",
  "Sometimes I have trouble switching focus with clarity.",
  "I'm 40ish. Reading fine print is becoming a challenge.",
  "Reading glasses aren't the fashion statement I want to make.",
  "Outdoor elements irritate my eyes.",
  "I wear my contacts, morning, noon and into the night.",
  "I don't like how I look in glasses.",
  "I often sleep in my contacts - 3 to 6 nights per week.",
  "I want my eyes to feel their best while wearing contact lenses.",
  "I don't want to worry about falling asleep in my contact lenses",
  "I need contacts that can put in the same long hours I do.",
  "I often work in dimly lit workspaces.",
  "I find working on a computer takes its toll on my eyes.",
  "I live in my lenses and often go out straight from work.",
  "I tend to wear contacts while driving.",
  "Glasses hold me back when I'm on the move.",
  "I burn the midnight oil, both at work and socially.",
  "I want to be the center of attention, not my glasses.", /*Please fix the confusion, clarify with tribal*/
  "I'm definitely a late night person.", /*Please fix the confusion, clarify with tribal*/
  "There is a type of contact lens to fit virtually every kind of lifestyle.",
  "Contact lenses stay exceptionally comfortable for extended periods of time.",
  "Contact lenses offer uncompromisingly good vision",
  "Glasses don't suit me. I'm comfortable wearing eyeglasses in social situations.",
  "Glasses are bothersome. They fog up, slide down my nose and become uncomfortable to wear over extended periods.",
  "Glasses don't offer me peripheral vision.",
  "They are very convenient for every day situations.",
  "Bifocals make me look old."
];

// FOR GOOGLE EVENT TRACKING
var lifeStyleElementsGA = 
[ "V1_Lifestyle_Statement_1",
  "V1_Lifestyle_Statement_2",
  "V1_Lifestyle_Statement_3",
  "V2_Lifestyle_Statement_4",
  "V2_Lifestyle_Statement_5",
  "V2_Lifestyle_Statement_6",
  "V3_Lifestyle_Statement_7",
  "V3_Lifestyle_Statement_8",
  "V3_Lifestyle_Statement_9",
  "V4_Lifestyle_Statement_10",
  "V4_Lifestyle_Statement_11",
  "V4_Lifestyle_Statement_12",
  "V5_Lifestyle_Statement_13",
  "V5_Lifestyle_Statement_14",
  "V5_Lifestyle_Statement_15",
  "V6_Lifestyle_Statement_16",
  "V6_Lifestyle_Statement_17",
  "V6_Lifestyle_Statement_18",
  "V7_Lifestyle_Statement_19",
  "V7_Lifestyle_Statement_20",
  "V7_Lifestyle_Statement_21",
  "V8_Lifestyle_Statement_22",
  "V8_Lifestyle_Statement_23",
  "V8_Lifestyle_Statement_24",
  "V9_Lifestyle_Statement_25",
  "V9_Lifestyle_Statement_26",
  "V9_Lifestyle_Statement_27",
  "V10_Lifestyle_Statement_28",
  "V10_Lifestyle_Statement_29",
  "V10_Lifestyle_Statement_30", 
  "NewToContacts_CL_Benefits_Check_Box_31",
  "NewToContacts_CL_Benefits_Check_Box_32",
  "NewToContacts_CL_Benefits_Check_Box_33",
  "NewToContacts_Issues_w_Eyeglasses_Check_Box_34",
  "NewToContacts_Issues_w_Eyeglasses_Check_Box_35",
  "NewToContacts_Issues_w_Eyeglasses_Check_Box_36"
];

// FOR GOOGLE EVENT TRACKING
var infoBubblesGA = 
[ "Info_Bubble 1",
  "Info_Bubble 2",
  "Info_Bubble 3",
  "Info_Bubble 4",
  "Info_Bubble 5",
  "Info_Bubble 6",
  "Info_Bubble 7",
  "Info_Bubble 8",
  "Info_Bubble 9",
  "Info_Bubble 10",
  "Info_Bubble 11",
  "Info_Bubble 12",
  "Info_Bubble 13",
  "Info_Bubble 14",
  "Info_Bubble 15",
  "Info_Bubble 16",
  "Info_Bubble 17",
  "Info_Bubble 18",
  "Info_Bubble 19",
  "Info_Bubble 20",
  "Info_Bubble 21",
  "Info_Bubble 22",
  "Info_Bubble 23",
  "Info_Bubble 24",
  "Info_Bubble 25",
  "Info_Bubble 26",
  "Info_Bubble 27",
  "Info_Bubble 28",
  "Info_Bubble 29",
  "Info_Bubble 30",
  "Info_Bubble 31",
  "Info_Bubble 32",
  "Info_Bubble 33"
];

var vignette = {
	
	lifeStyleSt : '',
	lifeStyleObj : '',
	
	init : function(){
		
		$('#vignetteThumbnail li').append('<div class="vigBrdr"></div>').click( function() {
			window.location.href= $(this).children('a').attr('href');
		});
		
		this.rollOver();
		this.loadCheckedValues();
			
		vignette.lifeStyleSt = $.cookie('__LifeStyleSt')!=null?$.cookie('__LifeStyleSt'):"";
		vignette.lifeStyleObj = $.cookie('__LifeStyleElements')!=null?$.cookie('__LifeStyleElements'):"";
		
	},
	
	rollOver : function() {
		var file;
		var imagePath = "images/headlines/home_";
		$('#vignetteThumbnail li').hover( function() {
			var $this = $(this);
			$this.find('div').stop(true,true).fadeIn('fast');
			file = $this.find('img').stop(true,true).attr('id')
			$('#vigHeadLine').hide().attr('src', imagePath + file + '.gif').show();
		}, function() {
			$('.vigBrdr').fadeOut('slow');
			$('#vigHeadLine').attr('src', imagePath + 'h_0.gif');
		});
	},
	
	saveLifeStyleList : function() {
		 	
		//console.group("Cookie");	
		$('.lifeStyleEle:checked').each( function(){
			$this = $(this);
			var chkValue = $this.val();
			var checkedId = $this.attr('id');
		
			if( vignette.lifeStyleSt.indexOf(chkValue) == -1 ) { //check if the value is already stored in csv
				vignette.lifeStyleSt +=  chkValue + ',';
			}
			
			if( vignette.lifeStyleObj.indexOf(checkedId) == -1) {
				vignette.lifeStyleObj += $this.attr('id') + ',';
			}			
			//console.log(vignette.lifeStyleObj)
		});
		
		$('.lifeStyleEle:not(:checked)').each( function() {
			$this = $(this);
			var chkValue = $this.val();
			var chkId = $this.attr('id');
//			alert("Value to Replace : " + chkValue)
			vignette.lifeStyleSt = vignette.lifeStyleSt.replace(chkValue + ',',''); //Replace existing value using RegEx
			regex = new RegExp( chkId + ',' , "g");
			vignette.lifeStyleObj =  vignette.lifeStyleObj.replace( regex , '' );
		});
		//console.groupEnd();
		
		$.cookie('__LifeStyleSt', vignette.lifeStyleSt, {path:'/'} ); //store lifestyle statements in cookies
		$.cookie('__LifeStyleElements', vignette.lifeStyleObj, {path:'/'} ); //store lifestyle checked object in cookies		
		
	},
	
	loadCheckedValues : function() {
		var lifeStyleEle = $.cookie('__LifeStyleElements');
		
//		console.log("Saved Checked Values - " + lifeStyleEle);
		
		if(lifeStyleEle == null || lifeStyleEle=='') return;
		lifeStyleEle = lifeStyleEle.substr(0, lifeStyleEle.length-1); //remove the trailing comma(,)
		var lifeStyleEleArray = lifeStyleEle.split(',')
		$.each(lifeStyleEleArray, function(ind,obj){
			$('#'+obj).attr('checked','checked');
		});		
	},
	
	processSavedList : function(){
		var myStyleList = $.cookie('__LifeStyleSt');
		if (myStyleList == null || myStyleList == '') return 0;
		
//		console.group("Final List");
//		console.log("Before: " + myStyleList );
		myStyleList =  myStyleList.replace(/[0-9]+_/g, ""); //Remove the unique id from the actual values and the _(underscore)
		myStyleList = myStyleList.substr(0, myStyleList.length-1); //remove the trailing comma(,)
//		console.log("After: " + myStyleList );
		var myStyleListArray = myStyleList.split(',');
		myStyleListArray = myStyleListArray.unique();
//		console.log("Unique Array: " +  myStyleListArray) 

//		console.groupEnd();
		return myStyleListArray.sortNum();
	},
	
	displayLifeStyleList: function() {
		var lifeStyleListArray = this.processSavedList();
		if(lifeStyleListArray=='') return;
		var domList = '';
		$.each(lifeStyleListArray, function(ind,item){
			domList += '<li>' + lifeStyleStatments[item-1] + '</li>'; // item is reduced by 1 coz array index starts with zero
		});
		$('#roundedCorner').css({'visibility': 'visible'});
		$('.secondHead').css({'visibility': 'visible'});
		$('#lifeStylePoints').append(domList).fadeIn('slow');
	},	
	
	processCheckedList: function() {
		var myCheckList = $.cookie('__LifeStyleElements');
		if(myCheckList==null) return 0;
		var myCheckListArray = [];
		myCheckList = myCheckList.replace(/lse_/g, "");
		myCheckList = myCheckList.substr(0, myCheckList.length-1); 
		return myCheckList.split(',').unique().sortNum();		
	},
		
	displayCheckedList: function() {
		var checkedList = this.processCheckedList();
		if(checkedList=='') return ;
		var domList = '';
		$('.abtBox + .line').show();
		$('.abtBox').show();
		$.each(checkedList, function(ind,item){
			domList += '<li>' + lifeStyleElements[item-1] + '</li>'; // item is reduced by 1 coz array index starts with zero
		});	
		$('#lifeStylePoints').append(domList).fadeIn('slow');		
	},
	
	deleteCookies: function() {
		//delete the cookie values
		$.cookie('__LifeStyleSt', null );
		$.cookie('__LifeStyleElements', null ); 
	},
	
	preLoadImages : function() {
		$.preloadImages("home_h_1.gif", "home_h_2.gif", "home_h_3.gif", "home_h_4.gif", "home_h_5.gif", "home_h_6.gif", "home_h_7.gif", "home_h_8.gif", "home_h_9.gif" );
	}
};

//===Array prototype to return unique values from the array
Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}
Array.prototype.sortNum = function() {
   return this.sort( function (a,b) { return a-b; } );
}

$(document).ready(function() {
	
	vignette.init();
			
	$('#next-moment, #my-recom').click(function() {
		vignette.saveLifeStyleList();
	});
	
	/*
	$('#my-recom').click( function() {
		vignette.saveLifeStyleList(); 
	}); */
	
	$(".home #quiz-button").click( function () {
				
		var ans1 = $('input[name="question1"]:checked').val();
		var ans2 = $('input[name="question2"]:checked').val();
		var ans3 = $('input[name="question3"]:checked').val();
		
		if( ans1 == undefined || ans2 == undefined || ans3 == undefined) {
			$('#errDiag').fadeIn();
			var t= setTimeout( function() {
				$('#errDiag').fadeOut();
			},2500)
			return false;
		}
		
		LS_diagnostics(ans1, ans2, ans3);
		
	});
	
	$(".printIco").click( function() {
		var url= '/' + $(this).attr("id") + '.shtml'
		newwindow=window.open(url,'name','height=600,width=700,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=no,status=yes,menubar=yes');
		return false;
	});
	
	
	$('.map_rollover').hoverIntent( function(event) {
		contentId = $(this).attr('id');
		titleId = contentId.split('_');
		vignetteId = $(this).attr('rel');
		$.ajax({
        	type: "GET",
			url: "../xml/info-data.xml",
			dataType: "xml",
			success: function(xml) { 
				 $(xml).find(vignetteId).each(function(){
				 	var title = $(this).find('title_' + titleId[1]).text();
					$('#runningPopup .title').html(title);
				 	var text = $(this).find(contentId).text();
				 	$('#runningPopup #innerBottom').html(text);

				 });

			},
		  error: function(XMLHttpRequest, textStatus, errorThrown) {
		  	//alert(errorThrown)
		  }
		});
		if($('#runningPopup').css("display")=="none"){ //hopefully this way if user hovers over again while open, it won't track again
		   //GOOGLE TRACKING OF INFO BUBBLE
		      var elstr = $(this).attr("id")
		      var elstr2 = elstr.replace(/info_/,"");
		      var elid = parseInt(elstr2);
		      ga_trackEvent("AO_Website_Homepage_Interaction", "Video_Information_Bubbles", infoBubblesGA[elid-1]);
		}
		$('#runningPopup').css({left:event.pageX-150, top:event.pageY + 0} ).fadeIn('slow');
		return false;
	}, function() {

	});
	
	var timeoutId;
	$('#runningPopup').hover( function() {
		clearTimeout(timeoutId);
	}, function() {
		timeoutId = setTimeout( function() {
			$('#runningPopup').fadeOut('slow');
		},
		650);
	});
	
	$('#runningPopup .close').click( function() {
		$('#runningPopup').fadeOut('fast');
		return false;
	});
	
});

/**
 * Functions for Flash Interoperablity
 * @param {Object} answerArr
 */

function LS_statements(answerArr) {
	
	if(answerArr == 'null' )
		return;

	var sReplace = answerArr.replace(/\|/g,",");
	$.cookie('__LifeStyleSt', sReplace + ','); //store the lifestylestatements csv string
	
	var sRemLifeStyle = sReplace;
	var sRemLifeStyle = sRemLifeStyle.replace( /_[0-9]+/g , '' );
	var sArray = sRemLifeStyle.split(',');
	
	for(i=0; i<sArray.length; i++ ) 
		sArray[i]= 'lse_' + sArray[i];
	
	var aString = sArray.join(",")
	
	$.cookie('__LifeStyleElements', aString + ',' , {path:'/'} ); //store the lifestylelements csv string
}

function LS_diagnostics(ans1, ans2, ans3) {
	
	var folderPath = '/products/'
	
	if( ans1 == 0 || ans1 == 1 ){ //never
		if( ans2 == 0 ) { //no
			if( ans3 == 0 ) {
				window.location.href = folderPath + 'air-optix-aqua.shtml';
				
				ga_trackEvent("AO_Website_Decision_Tree", "DT1_AIR_OPTIX_AQUA");
			} else {
				window.location.href = folderPath + 'air-optix-aqua-multifocal.shtml';
				ga_trackEvent("AO_Website_Decision_Tree", "DT2_AIR_OPTIX_Multifocal");
			}
		} else { //yes
			if( ans3 == 0 ) {
				window.location.href = folderPath + 'air-optix-for-astigmatism.shtml'
				ga_trackEvent("AO_Website_Decision_Tree", "DT3_AIR_OPTIX_for_Astigmatism");
			} else {
				window.location.href = folderPath + 'air-optix-for-astigmatism.shtml'; 
				ga_trackEvent("AO_Website_Decision_Tree", "DT4_AIR_OPTIX_Multifocal");
			}
		}
	} else {
		if( ans2 == 0 ) {// no
			if( ans3 == 0 ) { //no
				window.location.href = folderPath + 'air-optix-night-and-day-aqua.shtml';
				ga_trackEvent("AO_Website_Decision_Tree", "DT5_AIR_OPTIX_Night&Day");
			} else {
				window.location.href = folderPath + 'air-optix-aqua-multifocal.shtml';
				ga_trackEvent("AO_Website_Decision_Tree", "DT6_AIR_OPTIX_Multifocal");
			}
		} else { //yes
			if(ans3==0) {
				window.location.href = folderPath + 'air-optix-for-astigmatism.shtml';
				ga_trackEvent("AO_Website_Decision_Tree", "DT7_AIR_OPTIX_for_Astigmatism");
			}else {
				window.location.href = folderPath + 'air-optix-for-astigmatism.shtml';
				ga_trackEvent("AO_Website_Decision_Tree", "DT8_AIR_OPTIX_Multifocal");
			}
		}
	}
}


/*EOF======================================= */

jQuery.preloadImages = function(){
  var path = '/images/headlines/';
  for(var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", path + arguments[i]);
  }
};