/*This js file is created for the TRUS Wishlist project and handles the functionality related to 
the "Low Inventory", "Select a Wishlist" and "Items Added" light box.
*/
	
var productId = null;	//product id of the main product.
var wlModalBox = null;	//light box modal obj.
var brModalBox = null;	//light box modal objfor baby registry .
var isOutOfStock = false;	//chek whether a product is out of stock.
var itemIDList = null;	//sku ids of the products the user wants to addto wl.
var itemQuantityList = null;  //Quantity of the products.
var pager = null;   //pagination obj.
var errorPageUrl ='/wishlist/error/index.jsp';  //Redirect URL in case of any error.
var wlCheckPidList = null; // pid list for inventory check
var wlPidsCatName = null; //names of category for the prods addd to wishlist
var prodLength = null; // number of products
var whichProducts = null; // main or related products

/*To hide the "Add to wl" button if the product is out of stock*/

function isOutofStock(flag){
	isOutOfStock = flag;		
}

/*Get the details of the product to be added to WishList*/

function addItemToWislhist(productLength, whichProducts){
	
	wlCheckPidList = {};
	wlPidsCatName = {};
	prodLength = productLength;
	whichProducts = whichProducts;
	itemIDList = new Array();
	itemQuantityList = new Array();
	var qtyBoxField = '';		 
	showAlertMessage = false;
	qtyBoxField = eval('document.orderForm.qty_1');

	if (qtyBoxField.value == 0){
	showAlertMessage = true;
	}			
	if (isNaN(parseInt(qtyBoxField.value))) {
	showAlertMessage = true;			
	}					
	if (!showAlertMessage){
		for (j=0; j < qtyBoxField.value.length; j++) {
			if( isNaN(parseInt(qtyBoxField.value.charAt(j))) )	{
			showAlertMessage = true;
			break;
			}
		}
	}	
	if(isOutOfStock)
	{
		showAlertMessage = true;
		qtyBoxField.value = "0";
	}
	
	var addRelatedProds = false;				

	// sku, qty of the related products

	 var pId = 0;
	 if (showAlertMessage == false)	{
	
	 var mainProd = document.getElementById("prod_1").value;
	 wlCheckPidList[pId] = mainProd;	
	 var mainProdCatName = document.getElementById("prodCatOmni_1").value;
	 wlPidsCatName[pId] = mainProdCatName;
	 var mainProdqty = document.orderForm.qty_1.value;	 
	 var pidSku = mainProd.split('|');
	 productId = pidSku[0];			
	 itemIDList[pId]=pidSku[1];
	 itemQuantityList[pId]=mainProdqty;
	 pId = pId+1;
	}
	 var count = 2;
	 if(whichProducts == 'related'){

		var relatedItem = document.getElementsByName("prod_"+count)[0];	

		while(relatedItem!=null){
			
			pidskuValue = document.getElementsByName("prod_"+count)[0].value;
			pidSkuCatName = document.getElementsByName("prodCatOmni_"+count)[0].value;
			
			var arry = pidskuValue.split('|');		

			if(document.getElementsByName("qty_"+count)[0].checked==true){	
				wlCheckPidList[pId] = pidskuValue;				
				wlPidsCatName[pId] = pidSkuCatName;
				relQty = document.getElementsByName("qty_"+count)[0].value;		
				itemIDList[pId]=arry[1];
				itemQuantityList[pId]=relQty;		
				pId = pId+1;
				addRelatedProds = true;
			}
		count = count +1;		
		relatedItem = document.getElementsByName("prod_"+count)[0];			
		}

	}
	
	if (showAlertMessage == true && addRelatedProds == false && whichProducts == 'related' )
	{
		alert("Please Select At least one Check Box. ");
	}
	else if (showAlertMessage == true && whichProducts == 'main')
	{
		alert(" Qty should be a number which is greater than or equal to '1'.");
	}
	else
	{	
		isUserLoggedIn();
		
	}		
}

/*Get the details of the product to be added to WishList*/

 function addCollectionItemToWL()
 {	
	productId = document.getElementsByName("prodId")[0].value;	
	wlCheckPidList = {};
	wlPidsCatName = {};
	itemIDList = new Array();
	itemQuantityList = new Array();
	var selected = false; 
	var count = 2;
	var pId = 0;
	var collectionItem =document.getElementsByName("prod_"+count)[0];	
	 
	while(collectionItem!=null){
			
		pidskuValue = document.getElementsByName("prod_"+count)[0].value;
		pidSkuCatName = document.getElementById("prodCatOmni_"+count).value;

		var arry = pidskuValue.split('|');	
		if(document.getElementsByName("qty_"+count)[0].value > 0){
			
			qty = document.getElementsByName("qty_"+count)[0].value;			
			itemIDList[pId]=arry[1];			
			itemQuantityList[pId]= qty;
			wlCheckPidList[pId] = pidskuValue;
			wlPidsCatName[pId] = pidSkuCatName;
			pId = pId+1;
			selected = true;
		}
		count = count +1;
		collectionItem = document.getElementsByName("prod_"+count)[0];				
	}

	if(selected == false)
	 {
		alert(" Qty should be a number which is greater than or equal to '1'.");
	 }
	 else
	 {		
		 isLoggedIn();
	 }		
 }

/*Collection page has no inventory check functionality
so a new function to check whether the user is logged.
This function does not call the inventory check functionality.
*/

function isLoggedIn(){

	var url = '/wishlist/login/check/index.jsp';	
	var pars = 'productId=' + productId;
	/*redirect to the Wishlst login page if the user is not logged in*/
	var redirectURL = '/wishlist/login/signIn/index.jsp?productId=' + productId; 

	new Ajax.Request(url,
		{
			method:'post',
			postBody:pars,
			onSuccess:function(transport){
			var validate = eval('('+ transport.responseText +')');
			if(validate.success==true){				
				selectWishlist();			
			}
			else{
				window.location =redirectURL;}
			}
		}
		);

}

/*Verifies whether the user is logged in or not. If the user is not logged
in, redirect to the generic login page. Else open the "Select a Wishlist" 
or "Add item success" lightbox.Before the "Select a wishlist" light box
is opened, the inventory of the selected items is checked. If low inventory
is found a light box is opened.
*/

function isUserLoggedIn(wishlidtId,givenName,eventType, passInvCheck){
	
	var url = '/wishlist/login/check/index.jsp';
	var wlId = wishlidtId;
	var pars = 'productId=' + productId;	
	var redirectURL = '/wishlist/login/signIn/index.jsp?productId=' + productId; 

	new Ajax.Request(url,
		{
			method:'post',
			postBody:pars,
			onSuccess:function(transport){
			var validate = eval('('+ transport.responseText +')');
			if(validate.success==true){			

				if(wlId == null || wlId.length == 0 && (!passInvCheck)){			
			
				var passWlInvCheck = doWishlistItemCheck(wlCheckPidList, whichProducts, prodLength);
					if(passWlInvCheck){
						selectWishlist();
					}					
		
				}
				else if (passInvCheck)
				{
					selectWishlist();
				}
				else{
					
					addItemToSelectedWishList(wishlidtId,givenName,eventType);
				}						

			}
			else{
				window.location =redirectURL;}
			}
		}
		);
}

/*Gets the individual wishlists of user. Displys the result in the LightBox*/

function selectWishlist(){	
	
	var url = '/wishlist/userWishlists/index.jsp';	

	var pars = 'itemQuantityList=' + itemQuantityList +'&itemIDList='+ itemIDList;		

	new Ajax.Request(url,
		{	
			method:'post',
			postBody:pars,				
			onSuccess:function(transport){
			document.getElementById('selectWL').innerHTML=transport.responseText;
			if(document.getElementById("wlCount").value==1)
				{
				addItemToSelectedWishList(document.getElementById("wishlistId").value,document.getElementById("wishlistGivenName").value,document.getElementById("wishlistEventTypeDesc").value);

				}
				else
				{
			showWishlistLayer();
			initPagination(document.getElementById("wlCount").value);
			document.getElementById("selectWL").style.display='block';
			document.getElementById("itemAdded").style.display='none';
				}
			}, 
			onFailure: function(){				
				window.location = errorPageUrl;
			}
		}
		);
}

/*Displays an Success page when an item is successfully added to wishlist*/

function addItemToSelectedWishList(wishlistId,givenName,eventType)	{

	var url = '/wishlist/addItem/index.jsp';		
	var pars = 'itemQuantityList=' + itemQuantityList +'&wishlistId=' + wishlistId +'&givenName='+ givenName +'&eventType='+ eventType +'&itemIDList='+ itemIDList;		

	new Ajax.Request(url,
		{
			method:'post',
			postBody:pars,
			onSuccess:function(transport){
			document.getElementById('itemAddedIH').innerHTML=transport.responseText;
			showWishlistLayer();			
			document.getElementById("selectWL").style.display='none';
			document.getElementById("itemAdded").style.display='block';
			Omniture_onClick_WishlistAdd(wishlistId);
			}, 
			onFailure: function(){

				window.location = errorPageUrl;
			}
		}
		);

}

/* Dynamic creation of modal and tool tip objects*/

function showWishlistLayer() {	
	
	if(wlModalBox != null){

	wlModalBox.setDomNode($$('.container')[0]);	
	wlModalBox.show();	
	}
	else {
		wlModalBox = new Df.Modal();	
	wlModalBox.pars.animateHolder = {
		time: 100,
		pause: 50,
		// *********************************************************
		// THIS NEEDS TO BE DYNAMICALLY CHANGED FOR TRU OR BRU STORE
		backgroundColor: '#42566D',   // FOR TRU ONLY
		//backgroundColor: '#656676',     // FOR BRU ONLY
		// THIS NEEDS TO BE DYNAMICALLY CHANGED FOR TRU OR BRU STORE
		// *********************************************************
		opacity: .5,
		selectors: ['opacity']
	}
	wlModalBox.pars.animateDialog = {
		time: 100,
		pause: 50,
		opacity: .99,
		selectors: ['opacity']
	}	

	wlModalBox.pars.minWidth= 'body'
	wlModalBox.pars.minHeight= 'body'	

	wlModalBox.set();
	wlModalBox.setDomNode($$('.container')[0]);	
	wlModalBox.show();
	}
	
}

function brshowWishlistLayer(){	
	
	if(brModalBox != null){

	brModalBox.setDomNode($$('.items-added')[0]);	
	brModalBox.show();	
	}
	else {
		brModalBox = new Df.Modal();	
	brModalBox.pars.animateHolder = {
		time: 100,
		pause: 50,
		// *********************************************************
		// THIS NEEDS TO BE DYNAMICALLY CHANGED FOR TRU OR BRU STORE
		backgroundColor: '#42566D',   // FOR TRU ONLY
		//backgroundColor: '#656676',     // FOR BRU ONLY
		// THIS NEEDS TO BE DYNAMICALLY CHANGED FOR TRU OR BRU STORE
		// *********************************************************
		opacity: .5,
		selectors: ['opacity']
	}
	brModalBox.pars.animateDialog = {
		time: 100,
		pause: 50,
		opacity: .99,
		selectors: ['opacity']
	}	

	brModalBox.pars.minWidth= 'body'
	brModalBox.pars.minHeight= 'body'	

	brModalBox.set();
	brModalBox.setDomNode($$('.items-added')[0]);	
	brModalBox.show();
	}
	
}

/*Pagination related stuff.Pagination is displayed on the "Select a 
wishlist" lightbox in case the user has more than 8 wishlists.
*/

function initPagination(wlCount){
	
	pager = new Pager(wlCount, 8); 
	pager.init(); 
	pager.showPageNav('pager', 'pagResultsSelect'); 
	pager.showPage(1);

}

function Pager(totalItems, itemsPerPage) {
	this.totalItems = totalItems;
	this.itemsPerPage = itemsPerPage;
	this.currentPage = 1;
	this.pages = 0;
	this.inited = false;

	this.showWishlists = function(from, to) {        
	var rows = totalItems;
		
	for (var i = 0; i < rows; i++) {			
		if (i < from || i > to || i == to)  
			document.getElementById("wlBox"+i).style.display = 'none';
		else
			document.getElementById("wlBox"+i).style.display = '';
		}
	}

	this.showPage = function(pageNumber) {
	if (! this.inited) {		
		return;
	}

	var oldPage = document.getElementById('pg'+this.currentPage);
	oldPage.className = 'pagOther';

	this.currentPage = pageNumber;
	
	var newPage = document.getElementById('pg'+this.currentPage);
	newPage.className = 'pagCircle';

	var from = (pageNumber - 1) * itemsPerPage;
	var to = from + itemsPerPage;
	this.showWishlists(from, to);
	}   

	
	this.init = function() {

	var rows = this.totalItems ;	
	var records = (rows); 	
	this.pages = Math.ceil(records / itemsPerPage);	
	this.inited = true;
	}

	this.showPageNav = function(pagerName, positionId) {
	if (! this.inited) {		
		return;
	}
	var element = document.getElementById(positionId);
	var pagerHtml = '';
	for (var page = 1; page <= this.pages; page++) 
		pagerHtml += '<span id="pg' + page + '" class="pagOther" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
		element.innerHTML = pagerHtml;
	}
}



