/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (checkIt('mozilla')) browser    = "firefox"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}


function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

var firstTimeLoad;
var lockPopMsg;

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		this.id = ctrl.id;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},

	// Turn everything on - mainly the IE fixes
	activate: function(){

		if(this.id!="" && (this.id=='personalize' || this.id.search(/WC_Personalize_Link/) > -1 || this.id.search(/quick/) > -1)) { //this is specific for Personalization
			var qty = 1;
			var linkById = document.getElementById(this.id);
			if (linkById == null) {
				//we seem to be getting two simultaneous requests from the listing page, which is
				// particularly a problem if the first request nulls out the contents of the link.
				// We can detect this condition if linkById is null, and we'll just return.
				return;
			}
			var storeId = (document.getElementById('storeId')) ? document.getElementById('storeId').value : linkById.attributes.storeId.value;
			var catentryId = (document.getElementById('catEntryId')) ? document.getElementById('catEntryId').value : linkById.attributes.catentryId.value;
			
			if (document.OrderItemUpdateForm && document.OrderItemUpdateForm.productId) {
				catentryId = document.OrderItemUpdateForm.productId.value;
				//alert('this :' + catentryId );
			} else if (linkById.attributes && linkById.attributes.productId) {
				catentryId = linkById.attributes.productId.value;
			}
			
			var errorFieldName = null;
			try {
				if(linkById.attributes.errorField!=null){
				  errorFieldName = linkById.attributes.errorField.value;
				  }
			} catch (err) {
			}
			
			var select_element_1 = document.getElementById('attribute_select_1');
			var select_element_2 = document.getElementById('attribute_select_2');
			
			//alert("errorFieldName :" + errorFieldName);
		
			if(select_element_1)
			{
				if(select_element_2 && !select_element_2.selectedIndex)
				{
					showError('Please make all selections');
					return;
				}		

				if(select_element_1.style.display != "none" && select_element_1.selectedIndex == 0)
				{
					
					showError('Please make all selections');
					return;
				}
			}

			// Start - Added for the check for stone selections for Birthstone Configurator project - Anu 3/17 
			// This block is to make sure all the birthstone select boxes are selected. 
			// If they all selected it converts the selections into a URL params string. 
			if(document.OrderItemUpdateForm){
				var fetch = document.OrderItemUpdateForm.fetchConfigData ;
				if(fetch && fetch.value == 'true'){ 
					if(select_element_2){
						var numStones = select_element_2.value ; 
						if(productInfo != null){
							numStones = productInfo.options.length;
						}
						var sParams = '' ;
						for( i = 0; i<numStones ; i++ ){
							var id = 'slotCatentryId_'+ i ;
							var stoneSelect = document.getElementById(id);
							var selectedIndex = stoneSelect.selectedIndex; 
							if (stoneSelect.selectedIndex > 0)
							{
								var myValue = stoneSelect.value; 
								if(i>0){
									sParams += '&';	
								}
								sParams += id+'='+myValue;
							}
							else
							{
								showError('Please make all selections');
								return;						
							}
						}
					}
				}
			}
			// End - Added for the check for stone selections for Birthstone Configurator project  - Anu 3/17
			
			if (document.getElementById('quantity')) {
			  if (document.getElementById('quantity').value == 0) {
				document.getElementById('quantity').value = 1;
				return;
			  } else {
			    qty = document.getElementById('quantity').value;
			  }
			}
/*
			var r = ajaxInventoryCheck(catentryId, storeId, qty,catentryId,'addProduct');
			if (!r.available) {
				checkValues(qty, r.quantity, errorFieldName);
				return;
			}
*/

			var baseProdId = catentryId;
			var reg999Sku = /999/;
			var matchPos1 = baseProdId.search(reg999Sku);
			if(matchPos1 == 0){ // if first 3 digits are 999 remove them
				baseProdId	= baseProdId.substr(3,baseProdId.length);	
			}

//Lavanya
			if(document.OrderItemUpdateForm){
				var fetch = document.OrderItemUpdateForm.fetchConfigData ;
				//alert("fetch");
				if(fetch && fetch.value == 'true'){ 
					//alert("sparams in new onv check : " +sParams + "----" + catentryId);
					//var metal = select_element_1.value;
					//var stones = select_element_2.value;			
					//var configCmdParams = sParams + '&occasionId=10200&tabNum=0&pageNum=1&selectedMetal='+metal+'&numberOfSlots='+stones;
					// occasionId=10200 is used for stones as it is a required parameter for the table : XORDITEMPHR or XORDITEMTXT -- 10200 = 'No Choice'. 
	              	var slotParams = prepareBirthStonesUrlParamsForInvcall();
	              	var inv = ajaxConfigProductsInvCheck(slotParams,catentryId, storeId, qty,baseProdId,'addProduct');
					if (!inv.available) {
						//alert("unavailable SKU : " + inv.sku + "--" + catentryId);
						checkValues(qty, inv.quantity, inv.sku, catentryId);
						return;
					}
				}
				else{
					var r = ajaxInventoryCheck(baseProdId, storeId, qty,baseProdId,'addProduct');
					if (!r.available) {
						checkValues(qty, r.quantity, errorFieldName);
						return;
					}
				}
				
				// Start - Added for the check for stone selections for Birthstone Configurator project - Anu 3/17 
				// This block is to make sure all the birthstone select boxes are selected. 
				// If they all selected it converts the selections into a URL params string. 
				var fetch = document.OrderItemUpdateForm.fetchConfigData ;
				if(fetch && fetch.value == 'true'){ 
					//alert(sParams);
					if(select_element_1.style.display == "none")
					{
						var metal = document.getElementById('attribute_select_1')[1].value;
					}
					else
					{
						var metal = select_element_1.value;
					}
					var stones = select_element_2.value;			
					var configCmdParams = sParams + '&occasionId=10200&tabNum=0&pageNum=1&selectedMetal='+metal+'&numberOfSlots='+stones;
					var saveConfig = ajaxSaveConfigCmd(configCmdParams,storeId,catentryId,catentryId,qty);
					if(!saveConfig.status == 'Success'){
						return ;
					}
				}
			}
			else{
					var r = ajaxInventoryCheck(baseProdId, storeId, qty,baseProdId,'addProduct');
					if (!r.available) {
						checkValues(qty, r.quantity, errorFieldName);
						return;
					}
				}
		}
	
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', '');
		    //this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		//Added to fix the jumping of the quick view window in firefox
		if (browser == 'firefox'){
			this.getScroll();
			this.prepareIE('100%', '');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
		
		if ((screen.width<=1024) && (screen.height<=768)) {
			$('lightbox').style.position = 'absolute';		
			$('lightbox').style.top = '250px';
		}
		firstTimeLoad = 0;
		lockPopMsg = 0;
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		if (browser == 'Internet Explorer'){
		bod.style.overflow = "hidden";
		}
		else
		{
			bod.style.overflow = overflow;
		}
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},

	hideLBSelects: function(ctrl){
		if (browser == "Internet Explorer" && version == "6") {
			selects = document.getElementById('lbContent');
			if(selects)
			{
				selects = selects.getElementsByTagName('select');
				for(i = 0; i < selects.length; i++) {
					selects[i].style.visibility = "hidden";
				}
			}
		}
		if (ctrl != null) {
			if (ctrl.currentTarget) {
				eval(ctrl.currentTarget.href);
				// code to hide the top x button when the help layer is up
				
				if (ctrl.currentTarget.id == 'help')
				{
					closeBtn = document.getElementById('lbContent').getElementsByTagName('img');
					for(i = 0; i < closeBtn.length; i++) {
						if (closeBtn[i].id == 'close')
						{
							closeBtn[i].style.visibility = "hidden";
						}
					}
				}				
			} else {
				if (ctrl.srcElement.nodeName == 'IMG') {
					//if the anchor is around an image, the click seems to be coming for the image in IE6, so go to the parent element
				    eval(ctrl.srcElement.parentNode.href);
				} else {
					eval(ctrl.srcElement.href);
					// code to hide the top x button when the help layer is up
					
					if (ctrl.srcElement.id == 'help' )
					{
						closeBtn = document.getElementById('lbContent').getElementsByTagName('img');
						for(i = 0; i < closeBtn.length; i++) {
							if (closeBtn[i].id == 'close')
							{
								closeBtn[i].style.visibility = "hidden";
							}
						}
					}
				}
			}
		}
	},
	showLBSelects: function(ctrl){
		if (browser == "Internet Explorer" && version == "6") {
			selects = document.getElementById('lbContent');
			if(selects)
			{
				selects = selects.getElementsByTagName('select');
				for(i = 0; i < selects.length; i++) {
					selects[i].style.visibility = "visible";
				}
			}
		}
		if (ctrl != null) {
			if (ctrl.currentTarget) {
				eval(ctrl.currentTarget.href);
				//code to show the top x button when the help layer is closed
				if (ctrl.currentTarget.id == 'helpclose' )
				{
					closeBtn = document.getElementById('lbContent').getElementsByTagName('img');
					for(i = 0; i < closeBtn.length; i++) {
						if (closeBtn[i].id == 'close')
						{
							closeBtn[i].style.visibility = "visible";
						}
					}
				}
			} else {
				if (ctrl.srcElement.nodeName == 'IMG') {
					//if the anchor is around an image, the click seems to be coming for the image in IE6, so go to the parent element
				    eval(ctrl.srcElement.parentNode.href);
					if (ctrl.srcElement.parentNode.id == 'helpclose' )
					{
						closeBtn = document.getElementById('lbContent').getElementsByTagName('img');
						for(i = 0; i < closeBtn.length; i++) {
							if (closeBtn[i].id == 'close')
							{
								closeBtn[i].style.visibility = "visible";
							}
						}
					}					
				} else {
					eval(ctrl.srcElement.href);
				}
			}
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},
	
	displayLightboxWarning: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		if(this.id!="" && this.id=='personalize') { //this is specific for Personalization
			var vURL = document.getElementById(this.id).href +"&quantity="+document.getElementById('quantity').value;
			if (vURL.indexOf("productId") == -1) {
				vURL = vURL + "&productId=" + document.getElementById('catEntryId').value;
			}
			if (document.domain == 'www.thingsremembered.com')
			var suite="thremmain"
			else
			var suite="devthrem"
			s_linkTrackVars="s_pageName,s_products";			
			s_pageName="PersonalizeItem";
			s_prop7="PersonalizeItem";
			s_products =  document.getElementById('catEntryId').value;
			s_code=s_dc(suite);if(s_code)s_d.write(s_code);
			this.content = vURL;	
		}
		//alert(this.content);
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},
	
	// Display Ajax response
	processInfo: function(response){
	
		this.setScroll(0, 0);
		if(document.getElementById('lbContent')){
			document.getElementById('lbContent').innerHTML = '';
			document.getElementById('lbContent').id='';
		}
	
	
		if (browser == "Internet Explorer" && version == '6') {
			info = "<div id='lbContent' style=\"float:right; position:relative; _margin-left: " + ((document.body.clientWidth/1024)*200) + "px;\">" + response.responseText + "</div>";
		} else {
			info = "<div id='lbContent' style=\"float:right; position:relative; \">" + response.responseText + "</div>";
		}
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";	
		this.actions();
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = $$('.lbAction');
		for(i = 0; i < lbActions.length; i++) {
		  try {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		  } catch (err) {
		    //console.log(err);
		  }
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
		//alert("this is called ...");
	   link = Event.element(e).parentNode;
		vURL = link.href;
		if(link.id!="" && link.id=='personalize') { //this is specific for Personalization

			var storeId = document.getElementById('storeId').value;
			var catentryId = document.getElementById('catEntryId').value;
			var qty = 1;
		    if (document.getElementById('quantity')) {
			  if (document.getElementById('quantity').value == 0) {
				document.getElementById('quantity').value = 1;
			  } else {
			    qty = document.getElementById('quantity').value;
			  }
			}
			/*
			var r = ajaxInventoryCheck(catentryId, storeId, qty);

			if (!r.available) {
				checkValues(qty, r.quantity);
				return;
			}
			*/
			vURL = document.getElementById(link.id).href +"&quantity="+document.getElementById('quantity').value;
			if (vURL.indexOf("productId") == -1) {
				vURL = vURL + "&productId=" + document.getElementById('catEntryId').value;
			}
			
		}
	   
	   var myAjax = new Ajax.Request(
			  vURL,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},
	
	// custom function for personalization once lightbox is initiated
	insertCustom: function(e){
	   //link = Event.element(e).parentNode;
	   //Element.remove($('lbContent'));

	   if(buildAjaxMessage()) {
		   showCon('pConfirmation');
		   document.getElementById("showMenu").value=true;
		   vURL = document.getElementById("personalizeForm").action;
		   var pars = Form.serialize('personalizeForm');
		   var myAjax = new Ajax.Request(
				  vURL,
				  {method: 'POST', parameters: pars, onComplete: this.processInfo.bindAsEventListener(this)}
		   );
	   }
	 
	},
	// custom function for personalization once lightbox is initiated
	insertSwitchTabs: function(e){
	   link = Event.element(e).parentNode;
	   if( buildAjaxMessage(link.href)) {
		   document.getElementById("showMenu").value=false;
		   document.getElementById("save").value=false;	   
		   document.getElementById("URL").value=link.href;
	   	   document.personalizeForm.URL.value=link.href; //fix for IE 7
		   vURL = document.getElementById("personalizeForm").action;
		   var pars = Form.serialize('personalizeForm');
		   var myAjax = new Ajax.Request(
				  vURL,
				  {method: 'POST', parameters: pars, onComplete: this.processInfo.bindAsEventListener(this)}
		   );
	   }
	 
	},
	// custom function for personalization once lightbox is initiated
	forceInsertSwitchTabs: function(e){
		link = Event.element(e).parentNode;
		if (link.href == "javascript:void(0)") {
			changeForSubmit();
			submitUnpersonalized();
		} else {
	
			setDoNotPersonalize();
			if (isPackage || baseQty > 1) {
				document.getElementById("showMenu").value=false;
				document.getElementById("save").value=false;
				document.getElementById("URL").value=link.href;
				document.personalizeForm.URL.value=link.href; //fix for IE 7
				
				vURL = document.getElementById("personalizeForm").action;
				var pars = Form.serialize('personalizeForm');
				var myAjax = new Ajax.Request(
					vURL,
					{method: 'POST', parameters: pars, onComplete: this.processInfo.bindAsEventListener(this)}
				);
				
			} else {
				document.getElementById("personalizeForm").submit();
			}
		}
	},
	// custom function for personalization once lightbox is initiated
	insertPersonalizeAll: function(e){
	   document.getElementById("save").value=true;	   
   	   document.getElementById("URL").value = "OrderCalculate?URL=OrderPrepare?URL=OrderItemDisplay";
	   document.getElementById("itemQuantity").value=document.getElementById("personalizeForm").quantity.value;	
	   document.personalizeForm.URL.value="OrderCalculate?URL=OrderPrepare?URL=OrderItemDisplay";
	  document.personalizeForm.save.value = true;
	  buildMessage();
	},	
	// custom function for personalization once lightbox is initiated
	deactivateConfirm: function(){
	
		if (confirm("A personalized gift, is a remembered gift. Are you sure that you do NOT want to give a personalized gift?")) {
			Element.remove($('lbContent'));
			
			if (browser == "Internet Explorer"){
				this.setScroll(0,this.yPos);
				this.prepareIE("auto", "auto");
				this.hideSelects("visible");
			}
			
			//Added to fix the jumping of the quick view window in firefox
			if (browser == "firefox"){
				this.setScroll(0,this.yPos);
				this.prepareIE("auto", "auto");
				this.hideSelects("visible");
			}
			this.displayLightbox("none");
			history.go(-1);
		}
	},	
	// custom function - personalization page - display light box
	attribute_select_activate: function()
	{
		this.hideSelects("hidden");			
		this.displayLightboxWarning("block");
	},	
	// custom function - personalization page - display light box deactivate
	attribute_select_deactivate: function()
	{
		this.hideSelects("visible");
		this.displayLightboxWarning("none");
	},	
	attribute_select_deactivate_quickView: function()
	{
		document.getElementById("attribute_select_1").style.visibility = 'visible';
		document.getElementById("attribute_select_2").style.visibility = 'visible';
	},	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		if (browser =="firefox"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
	},
	resetPassword: function(e){
	    var form = document.ResetPasswordForm;
		if (form.logonId.value == '' || form.logonId.value.indexOf('@') <= 0 || form.logonId.value.lastIndexOf('.') <= 2 
			|| form.logonId.value.lastIndexOf('.') - form.logonId.value.indexOf('@') <= 1 
			|| form.logonId.value.length - form.logonId.value.lastIndexOf('.') <= 1)
		{
		    showError("Type an e-mail address in the E-mail address field. ", 'pwdResetErrorField');
		    return;
		}
		form.logonId.value = form.logonId.value.toUpperCase();

		vURL = document.ResetPasswordForm.action;
		var pars = Form.serialize('ResetPasswordForm');
		vURL = vURL + "?" + pars;
		var myAjax = new Ajax.Request(
		  vURL,
		  {method: 'GET', onComplete: this.processInfo.bindAsEventListener(this)}
		);

	},
	closeLayer: function(e) {

		Element.remove($('lbContent'));
	
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
	
		//Added to fix the jumping of the quick view window in firefox
		if (browser == "firefox"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		this.displayLightbox("none");
		history.go(-1);
	}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = $$('.lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
  try {
    if (document.getElementById('overlay')==null) {
		bod 				= document.getElementsByTagName('body')[0];
		overlay 			= document.createElement('div');
		overlay.id		= 'overlay';
		lb					= document.createElement('div');
		lb.id				= 'lightbox';
		lb.className 	= 'loading';
		lb.innerHTML	= '<div id="lbLoadMessage">' +
							  '</div>';
		bod.appendChild(overlay);
		bod.appendChild(lb);
    }
  } catch (e) {
  }
}

function clickPersonalizeButton() {
	if (document.getElementById('personalize').click) {
		//alert("clicked");
		document.getElementById('personalize').click();
	} else {
		//'valid' is the lightbox variable, on form submit (hitting the enter button) 
		//explicitly call the lightbox activate for the link. This could be used for both browers,
		//but since IE allows you to 'click' a link programmatically, we'll leverage that if it is
		//available.
		//alert("valid.activate");
		valid.activate(document.getElementById("personalize"));
	} 
	return false;
}
