	function Product (sformId){
		this._formId = sformId;
		this._primItem = "";
		this._flagPrim = false;
		this._secItems = "";
		this._secItemProd = "";
		this._message = "";
		this._roductDetail = null;
	}
Product.prototype={
	_isAllAttributeSelected : function(){
		var list = document.forms[this._formId].elements;
		var validateItem = true;
		for( var i=0; i<list.length; i++)
		{
			if(list[i].id.indexOf('attributesValue') !=-1)
			{
				if(list[i].value==''){
					validateItem = false;
					break;
				}else{
					var tmp = list[i].id.split('$');
					var tmpId = tmp[1];
					$('attr_'+tmpId).value = list[i].options[list[i].selectedIndex].text;
				}
			}
		}
		return validateItem;
	},
		  
	_checkMaxFreeProducts : function (statusIndex){
		if($('maxFreeProducts')!= null){
		var maxFree = $('maxFreeProducts').value;
		if(maxFree != 0)
		{
			var elels = document.forms['addToCartFrom'].elements;
			var selectedItems = 0;
			for(i=0;i<elels.length;i++){
				var elem = elels[i];
				if(elem.type == 'checkbox' && elem.id.indexOf('free') != -1 && elem.checked){
					selectedItems++;
				}
			}
			
			if(selectedItems == 0)
			{
				  alert('Please choose '+ maxFree + ' free products from the list given below');
				  this._clearOthers();
				  return false;
			}else if(selectedItems > maxFree){
				alert('Cannot add more free products than allowed');
				this._clearOthers();
				return false;
			}else {
				var obj = $('freeProductItems'+statusIndex);
				if(obj != null){
					try{
						this._setProductItemValues(obj,statusIndex);
					}catch(err){alert(err.message);}
				}
				return true;
			}
		}
		}
		return true;
	},

	  // TODO another method has to be written for collecting messages in the format
	  // MessageProvided1,ItemID1,AttributeID1:MessageProvided2,ItemID2,AttributeID2:  
	  
	_setProductItemValues :function(thisObj,setIndex){
		var index = thisObj.selectedIndex;
		
		$('freeItemId'+setIndex).value = $('freeItemId_'+index).title;
		$('freeItemMRPrc'+setIndex).value = $('freeItemMRPrc_'+index).title;
		$('freeItemOfferPrc'+setIndex).value = $('freeItemOfferPrc_'+index).title;
		$('freeItemDiscount'+setIndex).value = $('freeItemDiscount_'+index).title;
		$('freeItemImageURL'+setIndex).value = $('freeItemImageURL_'+index).title;
		$('freeItemTitle'+setIndex).value = $('freeItemTitle_'+index).title;
		$('freeItemAMTName'+setIndex).value = $('freeItemAMTName_'+index).title;
		$('freeItemAMTPOI'+setIndex).value = $('freeItemAMTPOI_'+index).title;

		$('multileMRP'+setIndex).update($('freeItemMRPrc_'+index).title);
		$('multileOffer'+setIndex).update($('freeItemOfferPrc_'+index).title);
		//$('multileDiscount').update($('freeItemDiscount_'+index).title);
		$('freePodImg'+setIndex).src = $('freeItemImageURL_'+index).title;
	},
	
	
	_clearOthers : function (){
		/*User can select the radio button after the selection of checkbox*/
		var formEles = document.forms[this._formId].elements;
		for(var i=0; i<  formEles.length;i++)
		{
			var element = formEles[i];
			if(element.type == "checkbox" && element.checked)
				element.checked = false;
		}
	},
	_isValidQty : function(){
		var qtyObj = $('itemqty');
		if(qtyObj !=null && qtyObj.value != ''){
			if(isNaN(qtyObj.value))
			{
				alert('Not a valid Number.');
				return false;
			}else if(parseInt(qtyObj.value) < 1 & parseInt(qtyObj.value) > 5){
					alert('Please enter value below to 6.');
				return false;
			}
		}else{
			alert('Please enter valid quantity.');
			return false;
		}
		return true;
	},

	isCheckout : function(){
		var isValid = false;
		var attrName = "";
		try{
				if($('pilrfnum') == null || $('pilrfnum').value == '' )
				{
					alert("This Item can not be added."); return false;
				}

				isValid = this._isAllAttributeSelected()
				if(!isValid){
					attrName = this.attributeName();
					alert('Please select '+attrName+' for this product.');
					return false;
				}

				isValid = this._checkMaxFreeProducts();
				if(isValid != true)
					return false;

				isValid = this._isValidQty();
				if(isValid != true)
					return false;
			  // This loop is for accumlating the items of the free products.
			  // The titles of the radio buttons will be 
			  // in the format -- PrimaryProductID$RelatedProductID$RelatedItemID --
			  // TO set the variables to no values for every method invocation.
			  //initializeVariables(formName);
			 
			  //this._addSecondaryRadioItems();
			 // this._addSecondaryNonRadioItems();
			  //this._getHiddenFieldValue();
			  //this._setMessageValues();
		  
	  }catch(exception){alert(exception.message)}
	  return isValid;
	},
	showFormId : function(){
		alert(this._formId);
	},
	openImages : function(){
	},	
	attributeName : function()
	{
		var list = document.forms[this._formId].elements;
			var attrName = "attribute";
			for( var i=0; i<list.length; i++)
			{
				if(list[i].id.indexOf('attributesValue') !=-1)
				{
					if(list[i].value==''){
						var attrTmp = list[i].id.split('$');
						attrName = attrTmp[1];
						break;
					}else{
						var tmp = list[i].id.split('$');
						var tmpId = tmp[1];
						$('attr_'+tmpId).value = list[i].options[list[i].selectedIndex].text;
					}
				}
			}
			return attrName;
	}
	
}// product Oject OO finished


	function updateProductPrice(){
		try{
		var allIsmpaoRfNum = '';
		var elems = document.forms['addToCartFrom'].elements;
		var attCnt = 0;
		for( var i=0; i<elems.length; i++)
		{
			if(elems[i].id.indexOf('attributesValue') !=-1 )
			{	if(elems[i].value != null && elems[i].value.length>0)
				{
					attCnt++;
					allIsmpaoRfNum   += elems[i].value + '#';
				}
			}
		}
		
		if(attCnt != $('attribCount').value )
			return false;
		
		var url = path+'/faces/tiles/components/product/itemPrice.jsp';
		
		var myAjax = new Ajax.Updater(
			'itemPriceDiv', 
			url, 
			{
				method: 'GET', 
				parameters: {'allAttribute':allIsmpaoRfNum,'catalogueId':$('mctrfnum').value},
				evalScripts : true,
				onFailure:handleFail
			});
		}catch(exception){alert(exception.message);return false;}
	}
	function handleImage(){
		if($('hideProdImg')){
		if($('hideProdImg').value != 'undefined' && $('hideProdImg').value!='')
				$("mainImg").src = $('hideProdImg').value ;
		}
	}
	function checkPNo(e,obj,flag)
	{
		var unicode= e.charCode? e.charCode : e.keyCode;
		if ( unicode !=8 && unicode !=9 ){ //if the key isn't the backspace key (which we should allow)
			if (flag=='isNumber' && (unicode < 48 || unicode > 57)) {
				obj.focus();
				return false;				
			}
			if (flag=='isValidQty' && (obj.value < 1 || obj.value > 5)){
				alert("Please Enter Product Quantity Between 1 to 50.");
				obj.value="1";
				obj.focus();
				return false; //disable key press
			}
		}
	}
	function updateCart(isCart){
		var prod = new Product('addToCartFrom');
		if(!prod.isCheckout()){
			return false;
		}
		var url = path+'/faces/tiles/components/product/miniShoppingCart.jsp';
		if(isCart != null && isCart.length>0){
			
			var isLoginUser = $('_isLogged').innerHTML;

			if(isCart=='Y' && isLoginUser=='false'){
				alert('Please Login First To Add Product In Wish List.');
				getLoginForm(path+'/faces/tiles/components/loginForm.jsp');
				return false;
			}
			else{
				$('isWishList').value= isCart;
				$('invoke:action').value = "BuyerMainNavigationActionBean.addToCartAction";
				var myAjax = new Ajax.Updater('minishoppingcart',url,
				{
					method: 'GET',	
					parameters: $('addToCartFrom').serialize(),
					onSuccess : updateErrorDiv,
					onFailure:handleFail
				});
			}	
		}
	}

	function handleFail(request){
		alert("Sorry. There was an error.");
	}
	
	function changeMiscInfo(sourceId){
		var o_targetDiv = "miscellaneous";
		$(o_targetDiv).innerHTML="";
		$(o_targetDiv).innerHTML = $(sourceId).innerHTML;
		footerBottom();
	}
	function openImages(productId,catalogueID,ctx)
	{
		//alert("productId-->"+productId+"catalogueID-->"+catalogueID)
		var page = ctx ;
		if(productId==null)
		{
			alert("Please select Item")
		}else
		{
			page += "/faces/tiles/productImages.jsp?productID="+productId+"&catalogueID="+catalogueID;
			var win_porp = "location=no, toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=no,height=450,width=500";
			window.open(page, "pImages",win_porp);
		}
	}
	function goToSimpleAddress(){
		var prod = new Product('addToCartFrom');
		if(!prod.isCheckout())
			return false;
		$('isWishList').value= "N";
		$('invoke:action').value = "NirlepBuyerCheckoutActionBean.checkoutAction";
		$('addToCartFrom').submit();
	}
	/**
	This will change the main image of the product when user click on the small images
	*/
	function changeMainImg(newImg,which)
	{	

		var form = document.forms[0];
		var ele =null;
		if(which=='main')
		{
			ele = document.getElementById("mainImg");
			ele.src = newImg;
			//document.getElementById('divImage').src=ele.src;
		}else{
		ele = document.getElementById("popupedLargeImg");
		ele.src = newImg;
		//document.getElementById('divImage').src=ele.src;
		}
	}
	function checkUserLoginForReview(){
		if($('_isLogged') != null && $('_isLogged').innerHTML == 'false'){
				alert('Please Login to write reviews.');
				getLoginForm(path + '/faces/tiles/components/loginForm.jsp');
				return false;
		}
		return true;
	}
	function processReview(ctx,reviewType,pid,sid,action) {
		var path = ctx ;
		var reviewPage = '';
		var params = '';
		var formName = '';
		if(reviewType == 'writeProductReviewFlag' && pid != null){
			/**
				Check Login For Write Product Review. 
				'chkLoginForReview' variable is the last hidden field on productDisplay.jsp
				Value to "chkLoginForReview" will get set as per "productDisplay_en.properties".
			*/
			if ($('chkLoginForReview').value == 'true' && !checkUserLoginForReview()) {
				return false;
			}
			if(action == 'showReviewForm'){
				params = {'pbirfnum':pid};	
			}
			if(action == 'saveReview'){
				if(!validateProductReview()){
					return false;
				}
			}
			path += "/faces/jsp/writeProductReview.jsp";
			formName = 'writeProductReview';
		}
		else if(reviewType == 'writeSellerReviewFlag' && sid != null){
			/**
				Guest User can never give review to the seller. 
				Because as per bussiness logic one user means ubirfnum can give one and only one review to the review.
			*/
			if (!checkUserLoginForReview()) {
				return false;
			}
			if(action == 'showReviewForm'){
				params = {'ssirfnum':sid};	
			}
			if(action == 'saveReview'){
				if(!validateSellerReview()){
					return false;
				}
			}
			path += "/faces/jsp/writeSellerReview.jsp";
			formName = 'writeSellerReview';
		}
		else if(reviewType == 'viewSellerReviewsFlag' && sid != null){
			path +="/faces/jsp/sellerInfo.jsp";
			params = {'ssirfnum':sid};	
		}	
		if(action == 'showReviewForm'){
			$('ratingFormDiv').innerHTML = '';
			var myAjax = new Ajax.Updater('ratingFormDiv',path, 
			{
				method: 'GET',
				parameters: params,
				onSuccess : showReviewFormResponse,
				onFailure:handleFail
			});
		}
		else if(action == 'saveReview'){
			var myAjax = new Ajax.Updater('ratingFormDiv',path, 
				{
					method: 'POST', 
					parameters: $(formName).serialize(),
					onSuccess : saveReviewResponse,
					onFailure : handleFail
				});
		}
		return false;
}

function showReviewFormResponse(transport){
	if(200 == transport.status){
		if(transport.responseText.indexOf('sellerReviewErrorDIV') != -1){
			alert("You have already reviewed this seller and can not submit any more review for this seller.");
		}
	}
}
function saveReviewResponse(transport){
	if(200 == transport.status){
		alert("Review published successfully.");
		window.location.reload();
	}
}
function validateProductReview(){
	if($('userName')){
		var name = $('userName').value;
		if(!alphaCharWithSpace(trimValue(name))){
			alert("Please Enter Valid User Name.");
			$('userName').focus();
			return false;
		}
	}
	if(!($('prtowneproductY').checked || $('prtowneproductN').checked)) {
		alert("Please select 'Have you purchased this product?' option.");
		$('prtowneproductY').focus();
		return false;
	}
	
	var count = 0;
	var paramCount = 0;
	var list = document.writeProductReview.elements;
	for(var i = 0 ; i < list.length ; i++){
		if(list[i].type=="radio" && list[i].name.indexOf('prtrating')!=-1){
			if(list[i].checked){
				count++;				
			}
			paramCount++;
		}
	}
	paramCount = paramCount/5;
	if(count != paramCount){
		if(paramCount == 1){
			alert("Please give rating.");	
		}
		else{
			alert("Please give rating for all attribute.");
		}
		return false;
	}
	var review = trimValue($('prtreviewpro').value);
	if(review == ''){
		alert('Please Enter Your review.');
		$('prtreviewpro').focus();
		return false;
	}
	else if(review.length > 1024){
		alert('Review Must Have Less Than 1024 Character.');
		$('prtreviewpro').focus();
		return false;
	}
	return true;
}


function validateSellerReview(){
	var name = $('userName').value;
	if(!alphaCharWithSpace(trimValue(name))){
		alert("Please Enter Valid User Name.");
		$('userName').focus();
		return false;
	}
	if(!($('srtboughtproductY').checked || $('srtboughtproductN').checked)) {
		alert("Please select 'Have you purchased this product?' option.");
		$('prtowneproductY').focus();
		return false;
	}
	var list = document.writeSellerReview.elements;
	var flag = true;
	for(var i = 0 ; i < list.length ; i++){
		if(list[i].type=="radio" && list[i].name.indexOf('srtrating1')!=-1){
			if(list[i].checked){
				flag = false;
				break;
			}
		}
	}
	if(flag) {
		alert("Please give rating.");
		$('srtrating1').focus();
		return false;
	}	
	var review = trimValue($('srtreviewpro').value);
	if(review == ''){
		alert('Please Enter Your review.');
		$('srtreviewpro').focus();
		return false;
	}
	else if(review.length > 1024){
		alert('Review Must Have Less Than 1024 Character.');
		$('srtreviewpro').focus();
		return false;
	}
	return true;
}


function setRankingStar(feed,hook,ratingFor)
{
	feed = feed/10;
	var star = Math.round(feed);
	var temp = star;
	var totalStar = 5;
	var fadStar = 0;
	var fullStar = 0;
	var halfStar = 0;
	star = star % 2;
	if(star == 0)
	{
		fullStar = feed / 2;
		halfStar = 0;
	}
	else
	{
		if(feed % 0.5 == 0){
			fullStar = Math.floor(feed / 2);
			halfStar = 1;
		}
		else if(feed < temp){
			fullStar = Math.floor(feed / 2);
		}
		else if(feed > temp){
			fullStar = Math.ceil(feed / 2);
		}

	}
	
	fadStar = totalStar - (fullStar + halfStar);
	
	var fargment = document.createDocumentFragment();
	fargment.appendChild(document.createTextNode(ratingFor))
	var image = null;
	
	for(var i = 1 ; i<= fullStar; i++)
	{
		image = document.createElement("IMG");
		image.src = "/media/images/OctaShop/star_1.gif";
		
		image.id=""+i
		fargment.appendChild(image);
		
	}
	
	if(halfStar > 0)
	{
		image = document.createElement("IMG");
		image.src = "/media/images/OctaShop/star_2.gif";
		image.id=""+i
		fargment.appendChild(image);
	}
	for(var i = 1 ; i<= fadStar; i++)
	{
		image = document.createElement("IMG");
		image.src = "/media/images/OctaShop/star_3.gif";
		image.id=""+i
		fargment.appendChild(image);
	}
	var starTag = document.getElementById(hook);
	starTag.appendChild(fargment);
}
function ajaxProductRating(id,val)
{
	var url = path+'/faces/tiles/components/latestUserRatings.jsp';
	var userRating = new Ajax.Updater('p_userRating', 
		url, 
		{
			method: 'GET', 
			parameters: {'productID':$F('pbirfnum'),'pn':val,'rpp':5,'invoke:action':'LatestUserRatingsActionBean.getLatestUserRatings'},
			onFailure:handleFail
		});
}


