///////////////////////////////////////////////////////////////////////////////////////////////
//   PRODUCT PAGE RELATED  //
///////////////////////////////////////////////////////////////////////////////////////////////
      
//Also merged March4th changes to March18th 
// INITIAL VARIABLES
	 var counter=0;
	 var counterTest=0;
	 var maxAmt = 20;
	 var rtotAmt = 0;
	 var tempVal = 0;
	 var totalCountPh=1;
	 var totalCountVr=1;
	 var phPageNumber=1;
	 var  vrPageNumber=1;
	 var filterId=0;
	 var filterValueId=0;
	 var cardType=PHYSICAL;
	 var pageNumber=1;
	 var pageCount=1;
	 var pageNo=1;
	 var phTab=1;
	 var vrTab=1; 
	 var PHYSICAL='Physical';
	 var VIRTUAL='Virtual';
	 var PHYSICAL_CARD_PAGE='Physical Gift Cards';
	 var VIRTUAL_CARD_PAGE='Virtual Gift Cards';		
     var iebuffer = 0;
	 var GC_PAGE_NUMBER_ADD=0;
  
//ERROR/POPUP STATES

// imagePath variable must be set again for the pops.customAll.content in the image path because it was changed to relative path for testing purposes
var pops = {
	customAll: {
		title:		'Customize Each Card',
		width:		300,
		content:	'<p>By unchecking "Customize each card" you will lose any information you have entered in the editable fields.</p><p>Would you like to:</p><input type="image" src="'+imagePath+'img/btn/btn_cancel.gif" alt="cancel" class="cancel"/><input type="image" src="'+imagePath+'img/btn/continue_new.gif" alt="continue" class="continue"/>'
	},
	quickView: {
		title:		function(elm){ var ttl = $(elm).parents('.card').find('h2').html(); return  ttl},
		width:		510,
		imgsrc:		function(elm){ var src = $(elm).parents('.card').find('.smallCard').find('img').attr('src'); return src},
		content:	function(elm){ var ttl = $(elm).parents('.card').find('#smallCardDetail').html()+ '<div class="clear"></div>';  return  ttl}
	},
	maxError:  {
		title:		'Selecting Gift Cards',
		width:		225,
		content:	'<p>Only 20 gift cards & e-gift cards can be purchased at any one time.</p><input type="image" src="'+imagePath+'img/buttons/btn_ok_blue.gif" class="closepopup" alt="ok"/>'
	},
	epreview:  {
		title:		'E-Gift Card Preview',
		width:		600,
		imgsrc:		function(elm){ var src = $(elm).parents('.card').find('.smallCard').find('img').attr('src');  return src},
		content:	'<img src="" alt="gift card image" style="margin-bottom:20px; margin-right:10px;" align="left"/><h1 style="font-size:16px; margin-top:0;">A Gift For You!</h1><h2 style="color:#000; font-size:16px; font-weight:normal; margin-top:0;">$50 e-Gift Card at Sears</h2><p>To: Horatio</p><p>Hortie! A fan-tab-ulous gift for my gregarious fishing buddy. Pick up another pole to replace the one that the catfish "widow maker" stole from you!</p><p>From: Brutus</p><div style="border-top:1px solid #ccc; padding:15px 5px; font-size:14px; font-weight:bold; clear:both;">e-Gift Card #: XXXXXXXXXX  Pin: XXXX</div>'
	 
	},
	lowCustErr: {
		title:		'Gift Card Quantity',
		width:		400,
		content:	'<p>If you are lowering the ammount of customized cards, you must do so by clicking the "remove" button at the right of each card.</p>'
	}
}
	
$(function(){
  
 
   if(!$.boxModel){
		if($.browser.version >= 7){
			 
			$('link[@title="ie7sheet"]').attr('disabled','')
			iebuffer = 13;
		}
		if($.browser.version < 7){
			 
			$('link[@title="ie6sheet"]').attr('disabled','')
			iebuffer = 13;
		}
	}
	if(!$.browser.msie){
		 
		$('link[@title="ie7sheet"]').remove()
		$('link[@title="ie6sheet"]').remove()
	}
	if(!$.browser.safari){
		$('link[@title="saf3sheet"]').remove()
	}else{
	 
		$('link[@title="saf3sheet"]').attr('disabled','')
	}
		// SETUP THE SCROLL WIDGET
	  scrollWidget();
	
	 pageEvents();
	 TabEvents();
	

	//POPUP BOX RELATED:
	$('#popupbox .closepopup').click(function(){$(this).parents('#popupbox').fadeOut()});

	// SETUP THE SCROLLWIDGET FOR THE GIFTCARD SELECTION AREA
	 
	// DROPDOWNS FOR CARD FILTER
	$('.cardFilter div h3').click(function(){
		$(this).parent().css({position:'relative'});
		$('.cardFilter div ul').slideUp();
		var ul = $(this).parent().find('ul');
		var global = this;
		$(ul).slideDown();
		var t;
		$(global).mouseover(function(){clearTimeout(t)});
		$(ul).mouseover(function(){clearTimeout(t)});
		$(ul).mouseout(function(){t = setTimeout(function(){
			$(ul).slideUp(function(){$(this).parent().css({position: ''});});
		},500)});
	});
	$('.cardFilter div ul li').click(function(){
	var parent = $(this).parent().parent()
		if($(parent).hasClass('occasions') || $(parent).hasClass('recipients')){
	 if($(this).parents('.cardFilter').attr('id')=='physFilter'){
		$('#phyFilterTitle #filteredBy').text($(this).text());
	   }
	   if($(this).parents('.cardFilter').attr('id')=='egiftFilter'){
	 	$('#VirFilterTitle #filteredBy').text($(this).text());
	 	}
	 	
	 	}
		$(this).parent().slideUp(function(){$(this).parent().css({position: ''});})
		return false;
	});
	 
	$('input.a2c').click(function(){
        $('input.required').removeClass("errorfield");
         if(!checkErrors()){
            createFormForCart();
           
 	        var formElement = document.getElementById('giftCardForm');
            if (formElement && formElement.parentNode &&
                 formElement.parentNode.removeChild) {
                  formElement.parentNode.removeChild(formElement);
                 } 
                displayGCValues();
             trackCardTotal(rtotAmt);
 	        document.submitToCart.submit();
          };
	 
	});

 	caroselEvents();

});
///////////////////////////////////////////////////////////////////////////////////////////////
// 														                   GLOBAL FUNCTIONS  //
///////////////////////////////////////////////////////////////////////////////////////////////

function TabEvents(){
//TAB CLICK EVENTS
	$('.tabnav .tab1').click(function(){
	 
		$('.tabnav li').removeClass('current');
		$(this).addClass('current');
		$('#eGiftCards').add($('#eGiftCards').prev('.prevCard')).add($('#eGiftCards').next('.nextCard')).hide();
		$('#physicalCards').add($('#physicalCards').prev('.prevCard')).add($('#physicalCards').next('.nextCard')).show();
		$('#egiftFilter').hide();
		$('.nextCard').css('float','left');
		$('#physFilter').show(); 
		
		$('#phyFilterTitle').show();
	 	$('#VirFilterTitle').hide();
		$('#rightImage').removeClass('rightcrumbImg-2');
		$('#rightImage').addClass('rightcrumbImg');
	  
        if(phTab>1){
    		trackPageName(PHYSICAL_CARD_PAGE);
		}
		return false;
	});
	$('.tabnav .tab2').click(function(){
 
	 	$('.tabnav li').removeClass('current');
		$(this).addClass('current');									  
		$('#physicalCards').add($('#physicalCards').prev('.prevCard')).add($('#physicalCards').next('.nextCard')).hide();
		$('#eGiftCards').add($('#eGiftCards').prev('.prevCard')).add($('#eGiftCards').next('.nextCard')).show();
		$('#physFilter').hide();
		$('#egiftFilter').show(); 
		$('.nextCard').css('float','right');
		$('#phyFilterTitle').hide();
		$('#VirFilterTitle').show();
		$('#rightImage').removeClass('rightcrumbImg');
		$('#rightImage').addClass('rightcrumbImg-2');
	 	if(vrTab>1){
		   trackPageName(VIRTUAL_CARD_PAGE);
		}
		return false;
	});
	$('#physFilter .allcards').click(function(){$('#phyFilterTitle  #filteredBy').text('All Cards');});
	$('#egiftFilter .allcards').click(function(){$('#VirFilterTitle  #filteredBy').text('All Cards');});
 
};




function scrollWidget(){
		// SETUP THE SCROLLWIDGET FOR THE GIFTCARD SELECTION AREA
		$('.burrito').each(function(){
			var global = this;
			var totalGroups = Math.ceil($(this).children('.card').length/3);
			
			var groupCounter = 1;
			var size = Number($(this).parent().css('width').replace('px',''));
			var curPos = Number($(global).css('margin-left').replace('px',''));
			
            var image1=imagePath+'img/icons/giftcard_prevcard_arrow.gif';
	        var image2=imagePath+'img/icons/giftcard_nextcard_arrow.gif';
          
            var prevImg = "url("+image1+")";
            var nextImg =  "url("+image2+")";

			$(global).css({marginLeft:0});
			if(groupCounter == 1){
				$(this).parent().prev('.prevCard').css('background-image','none');	
			}
			if( $(global).children('.card').length <= 3){
				$(this).parent().next('.nextCard').css('background-image','none')
			}
			if( $(global).children('.card').length >= 4){
				$(this).parent().next('.nextCard').css('background-image',nextImg);
			}
			$(this).width(totalGroups*size > 0? totalGroups*size : 715);
			$(this).height('100%')
		/*	$(this).parent().prev('.prevCard').unbind().click(function(){
				groupCounter--;
				if(groupCounter < 1){groupCounter = 1}
				if(groupCounter == 1 || $(global).children('.card').length <= 3){$(this).css({backgroundImage:'none'})}else{$(this).css({backgroundImage:prevImg})}
				if(groupCounter == totalGroups || $(global).children('.card').length <= 3){$(this).next().next('.nextCard').css({backgroundImage:'none'})}else{$(this).next().next('.nextCard').css({backgroundImage:nextImg})}
				curPos = Number($(global).css('margin-left').replace('px',''));
				if( curPos < 0){
					if($.browser.msie){$('.card .newCard').hide()}
					$('.card .cardHover').hide();
					//$(global).animate({marginLeft: (curPos +size)}, function(){$('.card .newCard').show();});
					$(global).animate({marginLeft: (curPos +size)-iebuffer}, function(){$('.card .newCard').show();});
					
				}
			});
			$(this).parent().next('.nextCard').unbind().click(function(){
				groupCounter++;
				if(groupCounter >= totalGroups){groupCounter = totalGroups}
				if(groupCounter == totalGroups || $(global).children('.card').length <= 3){$(this).css({backgroundImage:'none'})}else{$(this).css({backgroundImage:nextImg})}
				if(groupCounter == 1 || $(global).children('.card').length <= 3){$(this).prev().prev('.prevCard').css({backgroundImage:'none'})}else{$(this).prev().prev('.prevCard').css({backgroundImage:prevImg})}
				curPos = Number($(global).css('margin-left').replace('px',''));
				//if( (Math.abs(curPos)+size) < $(global).width() ){
				if( (Math.abs(curPos)+size)+(groupCounter*iebuffer) < $(global).width() ){
					if($.browser.msie){$('.card .newCard').hide()}
					$('.card .cardHover').hide();
					//$(global).animate({marginLeft: (curPos -size)}, function(){$('.card .newCard').show();});
					$(global).animate({marginLeft: (curPos -size)+iebuffer}, function(){$('.card .newCard').show();});
					
				}
			});*/
			
			$(this).parent().prev('.prevCard').unbind().click(function(){
				if(!$(global).is(':animated')){
					groupCounter--;
					if(groupCounter < 1){groupCounter = 1}
					if(groupCounter == 1 || $(global).children('.card').length <= 3){$(this).css('background-image','none')}else{$(this).css('background-image',prevImg)}
					if(groupCounter == totalGroups || $(global).children('.card').length <= 3){$(this).next().next('.nextCard').css('background-image','none')}else{$(this).next().next('.nextCard').css('background-image',nextImg)}
					curPos = Number($(global).css('margin-left').replace('px',''));
					if( curPos < 0 ){
						if($.browser.msie){$('.card .newCard').hide()}
						$('.card .cardHover').hide();
						$(global).animate({marginLeft: (curPos +size)-iebuffer}, function(){$('.card .newCard').show();});
					}
				}
			});
			$(this).parent().next('.nextCard').unbind().click(function(){
				if(!$(global).is(':animated')){
					groupCounter++;
					if(groupCounter >= totalGroups){groupCounter = totalGroups}
					if(groupCounter == totalGroups || $(global).children('.card').length <= 3){$(this).css('background-image','none')}else{$(this).css('background-image',nextImg)}
					if(groupCounter == 1 || $(global).children().length <= 3){$(this).prev().prev('.prevCard').css('background-image','none')}else{$(this).prev().prev('.prevCard').css('background-image',prevImg);}
					curPos = Number($(global).css('margin-left').replace('px',''));
					if( (Math.abs(curPos)+size)+(groupCounter*iebuffer) < $(global).width()){
						if($.browser.msie){$('.card .newCard').hide()}
						$('.card .cardHover').hide();
						$(global).animate({marginLeft: (curPos -size)+iebuffer}, function(){$('.card .newCard').show();});
					}
				}
			});
			
		});
	/*		
		if(!window.XMLHttpRequest) 
			setTimeout("$(\".giftCards\").css(\"width\",\"82%\");", 500);
    	else 
			setTimeout("$(\".giftCards\").css(\"width\",\"715px\");", 500);

	
		setTimeout("$(\".giftCards\").css(\"width\",\"92%\")", 500);
		setTimeout("$(\".giftCards\").css(\"width\",\"82%\")", 500);*/
	}	



 function pageEvents(){
  $('select').fakeDD();
	 	$('.fakeDD ul li').click(function(){
		$(this).parents('.fakeDD').find('select').val($(this).html()).change();
		$(this).parents('.fakeDD').find('span').html($(this).parents('.fakeDD').find('select').val());
	  
		 
	});  
	  	$('#physFilter .right .fakeDD ul li').click(function(){
	    phPageNumber=parsePageNumber($(this).parents('.fakeDD').find('select').val());
	    getPageForCard(PHYSICAL,phPageNumber);
	});
	$('#egiftFilter .right .fakeDD ul li').click(function(){
	     vrPageNumber=parsePageNumber($(this).parents('.fakeDD').find('select').val());
	    
		getPageForCard(VIRTUAL,vrPageNumber);
	});
	
	
	$('.btnPrevious').unbind().click(function(){

     if($(this).parents('.cardFilter').attr('id')=='physFilter'){
   	 	phPageNumber--;
	 	getPageForCard(PHYSICAL,phPageNumber);
	  	
	 }
	 else{
	  	vrPageNumber--;
	    getPageForCard(VIRTUAL,vrPageNumber);
	 }
	}); 
    $('.btnNext').unbind().click(function(){
	
	 if($(this).parents('.cardFilter').attr('id')=='physFilter'){
	     phPageNumber++;
		   
	 	  getPageForCard(PHYSICAL,phPageNumber);
	 }
	 else{
	     vrPageNumber++;
		   
	     getPageForCard(VIRTUAL,vrPageNumber);
		
	 }
	
 
	});
  
  
  };

	
	
	
	
	// HOVER EVENT FOR DISPLAYING DESCRIPTION IN THE SELECTION AREA
	function caroselEvents(){
	  
		$('.burrito .card').hover(function(){
			//ONLY IF THERE ARE NO DROPDOWNS VISIBLE
			if ($('.cardFilter ul:visible').length == 0){cardHover(this,'on')}
		},function(){
			cardHover(this,'off')
		});
		
		// CLICK EVENTS FOR ADDING CARDS FROM THE CAROSEL
		$('.burrito .card').unbind().click(function(){
		   addCard(this);
		    
		});
	   
		$('a.select').unbind().click(function(){
	
		  
		   addCard($(this).parent());
		});
		
		$('.burrito .card').hover(function(){
			//ONLY IF THERE ARE NO DROPDOWNS VISIBLE
			if ($('.cardFilter ul:visible').length == 0){cardHover(this,'on')}
		},function(){
			cardHover(this,'off')
		});
	 
	};
	
	 
	
	// FUNCTION FOR SHOWING/HIDING HOVER STATE ON THE CARDS
	function cardHover( elm, eve ){
		if (eve == 'on'){
		
			$(elm).css({position:'relative'})
			$(elm).find('.cardHover')./*css({top: topPos, left:lftPos}).*/show();
			$(elm).find('.newCard').css({ opacity: 0.25 });
			$(elm).find('img').css({ opacity: 0.25 });
		}
		if (eve == 'off'){
			$(elm).css({position:''})
			$(elm).find('.cardHover').hide();
			$(elm).find('.newCard').css({opacity: 1});
			$(elm).find('img').css({opacity: 1});
		}
	};
	
	// FUNCTION FOR ADDING CARDS TO THE COSTOMIZING STAGE
	function addCard( element ){
	
 
         //Omniture tracking
          var partNumber=$(element).find("#partnum").html();
          omnitureTrackVariable(partNumber);
         //Omniture tracking 	 
		 var title=$(element).find("h3").html();
		 var desc=$(element).find("#shortDesc").html();
		 var ldesc=$(element).find("#longDesc").html();
		 var hdmessage=$(element).find("#hdMessage").html();
		 var catentryID=$(element).find("#catEnt").html();
		 var image=$(element).find("img:eq(1)").attr("src");
		 if (image==null)
		 {
		 image=$(element).find("img:eq(0)").attr("src");
		 
		 }
	 
		if(rtotAmt < maxAmt){
         	rtotAmt++;
		 	$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
			var new_card_code=''
			new_card_code+='<div class="card'
		if($(element).hasClass('egiftcard')){
				new_card_code+=' egiftcard">\n'
			}else{
				new_card_code+='">\n'
		}
		
		    new_card_code+='<input type="hidden" id="catentryID" name="catentryID_'+counter+'" value="'+catentryID+'">\n'
			new_card_code+='	<div class="smallCard">\n'
			new_card_code+='		<img src="'+image+'" alt="gift card 1">\n'
			new_card_code+='		<a class="details" href="javascript:void(null);">Card Details</a>\n'
		if($(element).hasClass('egiftcard')){
			new_card_code+='		<a class="preview" href="javascript:void(null);">Card Preview</a>\n'
		}
			new_card_code+='	</div>\n'
			new_card_code+='	<h2>'+title+'</h2>\n'
			new_card_code+='<div id="smallCardDetail" style="display: none;"><img src="" alt="gift card image" style="float:left;"/>'+desc+ldesc+hdmessage+'<input type="image" src="'+imagePath+'img/buttons/btn_closewindow_blue.gif" alt="close window" class="closepopup"/></div>';
	
			new_card_code+='	<div class="qty">\n'
			 
			new_card_code+='		<label>*Qty</label>\n'
		 
		new_card_code+='		<select class="required">\n'
            for (var x = 1; x <= quantityMax; x++){
                   new_card_code+='<option value="'+x+'">'+x+'</option>\n'
           }
		 	new_card_code+='		</select>\n'
			new_card_code+='	</div>\n'
/*			new_card_code+='	<div class="customAll"><label><input type="checkbox" id="customize_'+counter+'"  name="customize_'+counter+'" value="yes"> Customize each card</label></div>\n'*/
			new_card_code+='	<div class="customize">\n'
			new_card_code+='		<div class="amount">\n'
			new_card_code+='			<label>*Amount</label>\n'
			new_card_code+='		<select class="required" name="amount">\n'
			for(var y=0;y<denomArray.length;y++){
		 	 new_card_code+='<option value='+denomArray[y]+'>$'+denomArray[y]+'</option>\n';
			}
		 	new_card_code+='		</select>\n'
			new_card_code+='		</div>\n'
			new_card_code+='		<div class="tofrom">\n'
			new_card_code+='			<label for="from">From</label>\n'
			new_card_code+='			<div class="input">\n'
			new_card_code+='				<span></span>\n'
	 		new_card_code+='				<input name="from">\n'
			new_card_code+='			</div>\n'
			new_card_code+='			<label for="to">To</label>\n'
			new_card_code+='			<div class="input">\n'
			new_card_code+='				<span></span>\n'
	    	new_card_code+='				<input name="to">\n'
			new_card_code+='			</div>\n'
				if($(element).hasClass('egiftcard')){
				new_card_code+='			<label for="recEmail"> <span class="req">*</span>Recipient Email</label>\n'
				new_card_code+='			<div class="input">\n'
				new_card_code+='				<span></span>\n'
		 
				new_card_code+='				<input class="required" name="recEmail">\n'
				new_card_code+='			</div>\n'
				new_card_code+='			<label for="confEmail"> <span class="req">*</span>Confirm Email</label>\n'
				new_card_code+='			<div class="input">\n'
				new_card_code+='				<span></span>\n'
			 
				new_card_code+='				<input class="required" name="confEmail">\n'
				new_card_code+='			</div>\n'
		 }
			new_card_code+='		</div>\n'
			new_card_code+='		<div class="message">\n'
			new_card_code+='			<label for="message">Message</label>\n'
			new_card_code+='			<div class="input">\n'
			new_card_code+='				<span>120 characters left</span>\n'
			new_card_code+='				<textarea name="message"></textarea>\n'
			new_card_code+='			</div>\n'
			new_card_code+='		</div>\n'
			new_card_code+='		<div class="remove">\n'
			new_card_code+='			<a href="#">Remove</a>\n'
			new_card_code+='		</div>\n'
			new_card_code+='		<br clear="all">\n'
			new_card_code+='	</div>\n'
			new_card_code+='	<div class="customAll"><label><input type="checkbox" id="customize_'+counter+'"  name="customize_'+counter+'" value="yes"> Customize each card</label></div>\n'
			/*new_card_code+='	<br clear="all"><br clear="all">\n'*/
			new_card_code+='</div>\n'
          counter++;

			//Add an instance to the customizing stage
			$(new_card_code).appendTo('.cardCustomizer');
			cardCheck();
			$('select').fakeDD();
			wireEvents();
            id_form_fields();


		}else{
			$('#popupbox h2').html(pops.maxError.title);
			//$('#popupbox .content').html(pops.maxError.content);
			$('#popupbox .content').css({overflow:'hidden'}).html(pops.maxError.content);
			$('#popupbox').css({top: '20%', left: '50%', width: pops.maxError.width }).show();
			$('#popupbox .closepopup').click(function(){ $('#popupbox').fadeOut()});
		}
	};
	
	// FUNCTION REMOVE CARDS FROM THE CUSTOMIZING STAGE
	/*function removeCard( element ){
		if($(element).parents('.customize').hasClass('duplicate')){
			$(element).parents('.card').find('.qty select').val(($(element).parents('.card').find('.qty select').val()-1));

			//THIS BIT IS FOR THE FAKE DROPDOWNS
			var fakedrop = $(element).parents('.card').find('.qty select').parent();
			$(fakedrop).find('span').html($(element).parents('.card').find('.qty select').val());

			$(element).parents('.customize').remove();
			rtotAmt--;
			cardCheck();
			$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
		}else{
			rtotAmt -= Number($(element).parents('.card').find('.qty select').val());
			$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
			$(element).parents('.card').remove();
			cardCheck();
		}
	 
		if(rtotAmt==0){
		   $('#errorMessaging').html("");
		   $('#errorMessaging').hide();
		
		}
	id_form_fields();
	};
	*/
	
	function removeCard( element ){
		var parent = $(element).parents('.card');
		var qty = $(parent).find('.qty select').val();
		
		if($(element).parents('.customize').hasClass('duplicate') && qty > 1){
			//alert("duplicate");
			$(element).parents('.card').find('.qty select').val(($(element).parents('.card').find('.qty select').val()-1));

			//THIS BIT IS FOR THE FAKE DROPDOWNS
			var fakedrop = $(element).parents('.card').find('.qty select').parent();
			$(fakedrop).find('span').html($(element).parents('.card').find('.qty select').val());
			//STORE THE PARENT BEFORE REMOVING IT
			var parents = $(element).parents('.card');
			$(element).parents('.customize').remove();
			rtotAmt--;
			cardCheck();
			$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
			//HIDE THE CUSTOMIZE ALL BOX IF ONLY ONE IS PRESENT
			/*if($(parents).find('.duplicate').length < 1){
				$(parent).find('.customAll').removeAttr('checked');
			}*/
			if(qty == 2){
				$(parent).find('.customAll input').removeAttr('checked');	
				$(parent).find('.customAll').hide();
				$(parent).find('div.customize:first').removeClass('duplicate');
			}
		}else{
			rtotAmt -= Number($(element).parents('.card').find('.qty select').val());
			$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
			$(element).parents('.card').remove();
			cardCheck();
		}
			 
		
			 
		if(rtotAmt==0){
		   $('#errorMessaging').html("");
		   $('#errorMessaging').hide();
		
		}
	id_form_fields();

	};

	
		// FUNCTION FOR CHECKING THE QTY IS WITHIN THE MAX ALLOWED
	function updateQty(elm){
	 var currentValue=parseInt($(elm).val());
		if($(elm).parents('.card').find('.customAll input:checkbox').is(':checked') &&(currentValue<tempVal)){
	 
			$(elm).val(tempVal);
			$(elm).parents('.fakeDD').find('span').html(tempVal);
			$('#popupbox h2').html(pops.lowCustErr.title);
			//$('#popupbox .content').html(pops.lowCustErr.content);
			$('#popupbox .content').css({overflow:'hidden'}).html(pops.lowCustErr.content);
			$('#popupbox').css({top: $(elm).parents('.fakeDD').offset().top, left: $(elm).parents('.fakeDD').offset().left, width: pops.lowCustErr.width }).show();
			$('#popupbox .closepopup').click(function(){ $('#popupbox').fadeOut()});
		}else{
			rtotAmt = 0;
			$('.qty select').each(function(){
				rtotAmt += Number($(this).val());
			});
			if(rtotAmt <= maxAmt){
				if($(elm).parents('.card').find('.customAll input:checkbox').is(':checked') &&(currentValue>tempVal)){
						
						updateCustomAmt(elm, false, true, tempVal);
						
				}
				else{		
				updateCustomAmt(elm, false);
				}
				
				cardCheck();
				$('.addToCart span.remaining').html('Remaining Max: '+(maxAmt - rtotAmt)+' Cards');
				$(elm).parents('.fakeDD').find('span').html($(elm).val());
			}else{
				$(elm).val(tempVal);
				$(elm).parents('.fakeDD').find('span').html(tempVal);
				$('#popupbox h2').html(pops.maxError.title);
				//$('#popupbox .content').html(pops.maxError.content);
				$('#popupbox .content').css({overflow:'hidden'}).html(pops.maxError.content);
				$('#popupbox').css({top: $(elm).parent().offset().top, left: $(elm).parent().offset().left, width: pops.maxError.width }).show();
				$('#popupbox .closepopup').click(function(){ $('#popupbox').fadeOut()});
	
			}
		}
	}


	// FUNCTION FOR CUSTOMIZING INDIVIDUAL CARDS
	function updateCustomAmt( element, alertError, higherQ, prevQ ){
		
		var i = 1;
		var parent = $(element).parents('.card');
		
		var qty = $(parent).find('.qty select').val();
		
		if(qty > 1){
			$(element).parents('.card').find('.customAll').show();	
		}else{
			$(element).parents('.card').find('.customAll').hide();	
		}
		
		if($(parent).find('.customAll input:checkbox').is(':checked')){
			
			if(!higherQ)
			{
			$(parent).find('.duplicate').remove();
			
				for(i; i<qty; i++){
			 	 
				if ((i==1) && !($(parent).find('.customize').hasClass('duplicate'))){
					$(parent).find('.customize').addClass('duplicate');
				}
			 	 
					//var customSection = $(parent).find('div.customize:first');
					 var customSection = $(parent).find('.customize:eq(0)');
					 
				//$(customSection).clone(true).addClass('duplicate').appendTo($(parent));
				$(customSection).clone(true).addClass('duplicate').appendTo($(parent)).find('textarea[name^="message"]').val('').prev('span').html('120 characters left');

				 id_form_fields();
				}
				$('.duplicate select').fakeDD();
				wireEvents();
		 
			}else{
				 
				counterTest++;
				qty=qty-prevQ;
				for(i; i<=qty; i++){
					
					if ((i==1) && !($(parent).find('.customize').hasClass('duplicate'))){
						$(parent).find('.customize').addClass('duplicate');
			}
					
					//var customSection = $(parent).find('div.customize:first');
					 var customSection = $(parent).find('.customize:eq(0)');
					 
					//$(customSection).clone(true).addClass('duplicate').appendTo($(parent));
					$(customSection).clone(true).addClass('duplicate').appendTo($(parent)).find('textarea[name^="message"]').val('').prev('span').html('120 characters left');
					
					id_form_fields();
				}
			$('.duplicate select').fakeDD();
			}
			
		}else{
			if(alertError){
				$('#popupbox h2').html(pops.customAll.title);
				//$('#popupbox .content').html(pops.customAll.content);
				$('#popupbox .content').css({overflow:'auto'}).html(pops.customAll.content);
				$('#popupbox').css({top: $(element).offset().top, left:$(element).offset().left, width: pops.customAll.width}).show();
				$('#popupbox input.continue').click(function(){
					for(var i=1; i<qty; i++){
						$(parent).find('div.duplicate:last').remove();
					}
					$(parent).find('div.customize').removeClass('duplicate');
					
					$(parent).find('div.customize .tofrom .input input').each(function(){
						var tofromId = $(this).attr('id');
						tofromId = tofromId.substring(0,(tofromId.length -2));
						$(this).attr('id',tofromId);
					});
					
					$(parent).find('div.customize .amount .fakeDD select').each(function(){
						var amtId = $(this).attr('id');
						amtId = amtId.substring(0,(amtId.length -2));
						$(this).attr('id',amtId);
					});
					
					$(parent).find('div.customize .message .input textarea').each(function(){
						var msgId = $(this).attr('id');
						msgId = msgId.substring(0,(msgId.length -2));
						$(this).attr('id',msgId);
					});
					
					
					//$(parent).find('.duplicate').remove();
					//$(parent).find('br').remove();
					//$(parent).append('<br clear="all"><br clear="all">');
					$('#popupbox').fadeOut();
				});
				$('#popupbox input.cancel').click(function(){
					$(parent).find('.customAll input:checkbox').attr('checked','checked');
					$('#popupbox').fadeOut();
				});
			//	$('#popupbox .closepopup').click(function(){$(parent).find('.customAll input:checkbox').attr('checked','checked');})
			};
		};
	};

	// QUICK FUNCTION TO CHECK IF CARDS ARE ADDED
	function cardCheck(){
		if($('.cardCustomizer .card').length > 0){
			$('.cardCustomizer').find('.card').css('border-top','1px solid #ccc');
			$('.cardCustomizer').find('.card:first').css('border-top','none');
			$('.cardCustomizer').show();
		}else{
			$('.cardCustomizer').hide();
		}
	}

	// GIFT CARD TEXTAREA CHARACTER COUNTDOWN
	/*function countdown(thisValue){
		var count = $(thisValue).prev('span');
		var startNum = 120;
		var textAreaValue = $(thisValue).val().length;
		$(count).html((startNum - textAreaValue)+' characters left');
		if (textAreaValue >= 120){
			alert('You have reached the 120 character maximum');
			$(thisValue).val($(thisValue).val().substring(0, startNum));
			$(count).html('0 characters left');
		}
	}*/
	
	function countdown(field) {
		var counter = $(field).prev('span');
		var limitNum = 120;
		if (field.value.length > limitNum) {
			field.value = field.value.substring(0, limitNum);
		} else {
			$(counter).html((limitNum - field.value.length)+' characters left');
		}
	}
	
	
	// FUNCTION TO WIRE EVENTS TO DYNAMICALLY ADDED DOM ELEMENTS
	function wireEvents(){
		counterTest = 0

		//REMOVE CARD EVENT
		$('.remove a').unbind();
		$('.remove a').click(function(){removeCard(this);return false});

		//CUSTOMIZE ALL EVENT
		$('.qty select').unbind();
		$('.qty select').click(function(){tempVal = $(this).val();});
		$('.qty select').change(function(){
												if(counterTest==0)
										 			updateQty(this, true)
										 });
		$('.customAll').find('input:checkbox').unbind();
		$('.customAll').find('input:checkbox').click(function(){updateCustomAmt(this, true)});

		$('.message textarea').unbind();
		//$('.message textarea').keypress(function(){countdown(this)});
          $('.message textarea').keydown(function(){countdown(this)}).keyup(function(){countdown(this)});

		$('.fakeDD').click(function(){
			//tempVal = $(this).find('select').val();
			tempVal = $(this).find('select').find('option:selected').text();
			counterTest=0;
		});
		$('.fakeDD ul li').click(function(){
	 
		    $(this).parents('.fakeDD').find('select').val($(this).html()).change();
		   // $(this).parents('.fakeDD').find('span').html($(this).parents('.fakeDD').find('select').val());
		    $(this).parents('.fakeDD').find('span').html($(this).parents('.fakeDD').find('select').find('option:selected').text());
		 });
		$('.smallCard a').unbind();
		
		$('.smallCard a.preview').click(function(){
		var gcStoreName="Sears";
		if(storeId=='10151'){
		 gcStoreName="Kmart";
		}
		
		
		var amt=$(this).parents(".card").find("select[name^='amount']").val();
	    var from= $(this).parents(".card").find("input[name^='from']").val();
	    var to= $(this).parents(".card").find("input[name^='to']").val();
        var message=$(this).parents(".card").find("textarea[name^='message']").val();
        var textDisplayed='<img src="" alt="gift card image" style="margin-bottom:20px; margin-right:10px;" align="left"/><h1 style="font-size:16px; margin-top:0;">A Gift For You!</h1><h2 style="color:#000; font-size:16px; font-weight:normal; margin-top:0;">$'+amt+' e-Gift Card at '+gcStoreName+'</h2><p>To:'+to+'</p><p> '+message+'</p><p>From: '+from+'</p><div style="border-top:1px solid #ccc; padding:15px 5px; font-size:14px; font-weight:bold; clear:both;"> e-Gift Card #: XXXXXXXXXX  Pin: XXXX</div>';
			$('#popupbox h2').html(pops.epreview.title);
	 		$('#popupbox .content').css({overflow:'auto'}).html(textDisplayed);
			$('#popupbox .content img').attr('src',pops.epreview.imgsrc(this));
			$('#popupbox').css({top: $(this).parents('.card').offset().top, left: $(this).parents('.card').offset().left+30, width: pops.epreview.width }).show();
			$('#popupbox .closepopup').click(function(){ $('#popupbox').fadeOut()});
			return false;
		});
		 
		 $('.smallCard a.details').click(function(){
			$('#popupbox h2').html(pops.quickView.title(this));
	 		$('#popupbox .content').css({overflow:'auto'}).html(pops.quickView.content(this))
			 $('#popupbox .content img').attr('src',pops.quickView.imgsrc(this));
			$('#popupbox').css({top: $(this).parents('.card').offset().top, left: $(this).parents('.card').offset().left+30, width: pops.quickView.width }).show();
			$('#popupbox .closepopup').click(function(){ $('#popupbox').fadeOut()});
			return false;
		});
	};
	

///////////////////////////////////////////////////////////////////////////////////////////////
// 														  jQ PLUGIN TO MAKE FAKE DROP DOWNS  //
///////////////////////////////////////////////////////////////////////////////////////////////
jQuery.fn.fakeDD = function(settings) {
	settings = jQuery.extend({
		 ddclass:	'fakeDD',
		 optclass:	'dd'
	}, settings);
	
	var ddclass = settings.ddclass

	return this.each(function(i){

		if(this.tagName == 'SELECT' || this.tagName == 'select' ){

			if($(this).parent().hasClass(settings.ddclass)){
				$(this).parent().replaceWith($(this))
			};
			
			if($(this).width() <= 0){
				var newSize = 51
			}else{
				var newSize = $(this).width()
			}

			var global = this;
			$(global).hide();

			$(this).wrap('<div class="'+settings.ddclass+'"></div>');

			var fake = $(this).parent();
			//	$(fake).prepend('<span>'+$(global).val()+'</span>');
				$(fake).prepend('<span>'+$(global).find('option:selected').text()+'</span>');
				 
			$(fake).css({
				width:		newSize,
				height:		15,
				position:	''
			});
			$('<ul class="'+settings.optclass+'"></ul>').prependTo($(fake)).hide();
			var list = $(this).parent().find('ul.'+settings.optclass);
			var z = (i+1)*10;
			$(list).css({
				position:	'absolute',
				top:		0,
				left:		0,
				zIndex:		z
			})

			$(global).children().each(function(){
				$(list).append('<li>'+$(this).html()+'</li>');
			});
			
		
			$(list).css('overflow','auto')
			if($(list).height() > 100){$(list).height(110)};
			

			$(fake).click(function(){
				tempVal = $(fake).find('select').val();
				$(this).css({position:'relative'});
				if($(list).is(':hidden')){
					$(list).show(100);
				}
			});

			var t;
			$(list).mouseover(function(){clearTimeout(t)});
			$(list).mouseout(function(){t = setTimeout(function(){
				$(list).slideUp(function(){$(fake).css({position: ''});});
			},300)});

			$(list).children().hover(function(){$(this).css({backgroundColor:'#E4EBF3'})},function(){$(this).css({backgroundColor:'#fff'})})

			$(list).children().click(function(){

				$(list).slideUp(function(){$(fake).css({position: ''})});
				clearTimeout(t);

			});
			
		}

	});
}
 
function id_form_fields(){
 
            var a = 1;
            var b = 1;
          
            $('.cardCustomizer .card').each(function(a){

                        $(this).find('.qty:first select').attr('id','qty_select_'+a);

                        $(this).find('.amount:first select').attr('id','amount_select_'+a);

                        $(this).find('.tofrom:first input[name="to"]').attr('id', 'to_input_'+a);

                        $(this).find('.tofrom:first input[name="from"]').attr('id', 'from_input_'+a);

                        $(this).find('.tofrom:first input[name="recEmail"]').attr('id', 'email_input_'+a);

                        $(this).find('.tofrom:first input[name="confEmail"]').attr('id', 'confEmail_input_'+a);

                        $(this).find('.message:first textarea').attr('id', 'message_input_'+a);

                        $(this).find('.duplicate').each(function(b){
 
                                    $(this).find('.qty select').attr('id','qty_select_'+a+'_'+b);

                                    $(this).find('.amount select').attr('id','amount_select_'+a+'_'+b);

                                    $(this).find('.tofrom input[name="to"]').attr('id', 'to_input_'+a+'_'+b);

                                    $(this).find('.tofrom input[name="from"]').attr('id', 'from_input_'+a+'_'+b);

                                    $(this).find('.tofrom input[name="recEmail"]').attr('id', 'email_input_'+a+'_'+b);

                                    $(this).find('.tofrom input[name="confEmail"]').attr('id', 'confEmail_input_'+a+'_'+b);

                                    $(this).find('.message textarea').attr('id', 'message_input_'+a+'_'+b);

                        });

            });

            

}

 

function trackFilter(cardType,filterName,filterValue){
var propString="Gift Card > Filter > "+cardType+" > "+filterName+" > "+filterValue;
 omnitureTrackVariable(propString);
}

function trackCardTotal(cardTotal){
var propString="Gift Card > Add to Cart > "+cardTotal;
    omnitureTrackVariable(propString);
}

function omnitureTrackVariable(varValue){
if (typeof s != 'undefined') {
    s.prop25=varValue;
    s.tl();
    }
}

function trackPageName(pageName){
if (typeof omPrefix != 'undefined') {
		omPrefix=pageName;
	}
if (typeof s != 'undefined') {
    s.t();
}
}
function getFilters(cardType,pageNumberIndex) {
 
var queryString="storeId="+storeId+"&fromAJAX=yes&catalogId="+catalogId+"&cardType="+cardType+"&filterName="+filterId+"&filterValue="+filterValueId+"&startIndex="+pageNumberIndex;
 $.ajax({
  url: "/shc/s/BrowseGiftCardsCmd",
  data:queryString,
  success: function(msg){
     displayFilters(msg);
   }
 });
  


 
  
}
 


function postAjaxLoad(){
   scrollWidget();
   caroselEvents();
   pageEvents();
   TabEvents();
  
 
}
/*
 * Update shopping-cart area of page to reflect contents of cart
 * described in XML document.
 */
function displayFilters(value,cardType) {
 
 //alert('JSON =='+value);
 if(value!=null && value!=''&& value!=' '){


var myJSONObject= "(" + value + ")";
if (!_gc) {
	var _gc = new Object();
}  
_gc.prod = eval(myJSONObject);
   

var blank=" ";
 
if(cardType==null){
 
cardType= _gc.prod.type;
 
}
//$('#shade').next('.preload').add('#shade').remove();

var divElement='';
var classElement='';
      if(cardType==PHYSICAL){
            
            displayPageNumbers(PHYSICAL, _gc.prod.tCount,phPageNumber);
            divElement='physicalCards';
            classElement='card';
        }
   if(cardType!=PHYSICAL){
         classElement='card egiftcard';
         divElement='eGiftCards';
         displayPageNumbers(VIRTUAL,_gc.prod.tCount,vrPageNumber);
     }
 $("#"+divElement+" div.burrito").html(blank); 


for (var x = 0; x <  _gc.prod.giftcards.length ; x++)
 
   {               var filter_code=''
                    filter_code+='<div class="'+classElement+'" id="card'+x+'">\n'
				    if(_gc.prod.giftcards[x].nf=='true'){
				    filter_code+='<img class="newCard" src="'+imagePath+'img/icons/giftcard_newCard.gif" alt="New!">\n'
				    }
				  
				    if(_gc.prod.giftcards[x].image!=null &&_gc.prod.giftcards[x].image!="")
				 	filter_code+='<img src="'+_gc.prod.giftcards[x].image+'" alt="'+_gc.prod.giftcards[x].title+'" align="baseline"><br>\n'
				 	
				 	else{
				 		filter_code+='<img src="'+imagePath+'img/icons/no_image.jpg" width=208 height=208 alt="No image available" align="baseline"><br>\n'
				 	}
				 	
					filter_code+='<div class="cardHover">\n' 
					filter_code+='<a href="javascript:void(null);;">Select Card</a>\n'
				    filter_code+='<h3>'+ _gc.prod.giftcards[x].title+'</h3>\n'
                  	filter_code+='<div id="catEnt" style="display:none;">'+_gc.prod.giftcards[x].centid+'</div>\n';
                  	  filter_code+='<div id="partnum" style="display:none;">'+_gc.prod.giftcards[x].partnum+'</div>\n';
				 	filter_code+='<div id="shortDesc"><p>'+_gc.prod.giftcards[x].desc+'</p></div>\n'
				 	filter_code+='<div id="longDesc" style="display:none;"><p>'+_gc.prod.giftcards[x].ldesc+'</p></div>\n'
				 	filter_code+='<div id="hdMessage" style="display:none;"><p>'+_gc.prod.giftcards[x].hdmessage+'</p></div>\n'
					filter_code+= '<span>(customize below)</span>\n'
					filter_code+='</div>\n'
					filter_code+='</div>'
					$("#"+divElement+" div.burrito").append(filter_code);
				
   }
   
  postAjaxLoad();
  }
}

function getphyGCards(fnameId, fvalId,filterName,filterValue){
filterId=fnameId;
filterValueId=fvalId;
var cardType=PHYSICAL;
trackFilter(cardType,filterName,filterValue);
phPageNumber=1;
getFilters(cardType,phPageNumber);
}

function getVirGCards(fnameId, fvalId,filterName,filterValue){
filterId=fnameId;
filterValueId=fvalId;
var cardType=VIRTUAL;
trackFilter(cardType,filterName,filterValue);
vrPageNumber=1;
 
		 
getFilters(cardType,vrPageNumber);
 
}
 

	function checkErrors(){
	var objForm=document.getElementById('giftCardForm');
 
	   var hasError=false;
	   var thisRecEMail="";
       var thisRecEmailID="";
       var thisConEmail="";
       var thisConEmailID="";
  for (var i=0; i<objForm.elements.length; i++) {

       var element=objForm.elements[i];
       var elName=element.name;
       var elType=element.type;
       var elValue=element.value;
       var elID=element.id;
        var al="#"+elID;
      
       if(elName=='recEmail'){
            if(elValue==null || elValue=="" || !validateEmailAddr(elValue)){
		             $('#errorMessaging').html("Please enter a valid email address for your recipient.");
		             $('#errorMessaging').show();
		             $(al).addClass("errorfield");
		        		 hasError=true;
		           }
		          else{
		         
		          thisRecEMail=elValue;
		          thisRecEmailID=elID;
		               
		          }
		  }
		  if(elName=='confEmail'){
		          if(elValue==null || elValue=="" || !validateEmailAddr(elValue)){
		             $('#errorMessaging').html("Please enter a valid email address for your recipient.");
		             $('#errorMessaging').show();
		             $(al).addClass("errorfield");
		             hasError=true;
		        	 
		           }
		           else{
		             
		           thisConEmail=elValue;
		           thisConEmailID=elID;
		               
		            }
      }
        
   if( thisRecEMail!=null && thisRecEMail!="" && thisConEmail!=null && thisConEmail!=""){   
     
     if(thisRecEMail.toLowerCase()!=thisConEmail.toLowerCase()){

    
	$('#errorMessaging').html("Email Address did not match. Please try again.");
		        $('#errorMessaging').show();
		        thisRecEmailID="#"+thisRecEmailID;
		        thisConEmailID="#"+thisConEmailID;
		        $(thisRecEmailID).addClass("errorfield");
		        $(thisConEmailID).addClass("errorfield");
		         hasError=true;
		  }
	             thisRecEMail="";
       			thisRecEmailID="";
       			thisConEmail="";
       			thisConEmailID="";
      }
           
	} //Main for loop
  if(hasError==true){
     return true;
   }
  else{
  return false;
  }
 
	}
	
function createNamedElement(type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
      element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
   }
   if (!element || element.nodeName != type.toUpperCase()) {
      // Non-IE browser; use canonical method to create named element
      element = document.createElement(type);
      element.name = name;
   }
   return element;
}
 
 
	function addHiddenFormElement(formName,elemName,elemValue){
	     
	 var textField=createNamedElement('INPUT',elemName);
	     textField.type = 'hidden';
		 textField.setAttribute('value', elemValue);
		// textField.setAttribute('Name', elemName);
		 //textField.setAttribute('Id', elemName);
		 formName.appendChild(textField); 
	}
	

	
	function createFormForCart(){
 	var objForm=document.getElementById('giftCardForm');
 
	var cartForm=document.getElementById('submitToCart');
	var catEntCounter=0;
	var qtyCounter=0;
	var catEntArray=new Array();
	var quantityArray=new Array();
	
			       
	for (var i=0; i<objForm.elements.length; i++) {

			       var element=objForm.elements[i];
			       var elName=element.name;
			       var elType=element.type;
			       var elValue=element.value;
			       var elID=element.id;
			       if(elID=='catentryID'){
			        catEntArray[catEntCounter]=elValue;
			        catEntCounter++;
			       }
			       var test=elID.substr(0,11);
			        if('qty_select_'==test){
			        quantityArray[qtyCounter]=elValue;
			        qtyCounter++;
			       }
                 
       }
     
 var catentryCounter=1;
 for(i=0;i<catEntArray.length;i++){
       
       var checkboxID="#customize_"+i ;
         var quantity=quantityArray[i];
     
	   if ($(checkboxID).is(":checked")){
				        //if checkbox is checked add single line items with quantity one to the cart
				       // addHiddenFormElement(cartForm, "catentryId_"+catentryCounter, catEntArray[i]);
				        //addHiddenFormElement(cartForm, "quantity_"+catentryCounter, 1);
				        // var from=document.getElementById("from_input_"+i+"").value;
				      //  addHiddenFormElement(cartForm, "from_"+catentryCounter, from);
				       // var to=document.getElementById("to_input_"+i+"").value;
				       // addHiddenFormElement(cartForm, "to_"+catentryCounter, to );
				       // var amount=  document.getElementById("amount_select_"+i+"").value
				       // addHiddenFormElement(cartForm, "amount_"+catentryCounter, amount);
				       // var message=   document.getElementById("message_input_"+i+"").value;
				       // addHiddenFormElement(cartForm, "message_"+catentryCounter,  message);
				       // if( document.getElementById("email_input_"+i +"")!=null){
				        //var email=document.getElementById("email_input_"+i+"").value;
				       //   addHiddenFormElement(cartForm,"email_"+catentryCounter,email);
				       // } 
				     // catentryCounter++;
				 
			          for(j=0;j<(quantity);j++){
					            addHiddenFormElement(cartForm, "catentryId_"+catentryCounter, catEntArray[i]);
						        addHiddenFormElement(cartForm, "quantity_"+catentryCounter, 1);
						        var from=document.getElementById("from_input_"+i+"_"+j +"").value;
						        addHiddenFormElement(cartForm, "from_"+catentryCounter, from);
						        var to=document.getElementById("to_input_"+i+"_"+j +"").value;
						        addHiddenFormElement(cartForm, "to_"+catentryCounter,to);
						        var amount=document.getElementById("amount_select_"+i+"_"+j +"").value;
						        addHiddenFormElement(cartForm, "amount_"+catentryCounter,amount);
						        var message=document.getElementById("message_input_"+i+"_"+j +"").value;
						        addHiddenFormElement(cartForm, "message_"+catentryCounter,message);
						        if( document.getElementById("email_input_"+i +"")!=null){
						        var email=document.getElementById("email_input_"+i+"_"+j +"").value;
						         addHiddenFormElement(cartForm,"email_"+catentryCounter,email);
						        } 
						           catentryCounter++;
				   }
	           
	        }//if
	      else{
	      //alert('will only add single entries');
	      
	                   addHiddenFormElement(cartForm, "catentryId_"+catentryCounter, catEntArray[i]);
						addHiddenFormElement(cartForm, "quantity_"+catentryCounter, quantity);
						var from=document.getElementById("from_input_"+i+"").value;
				        addHiddenFormElement(cartForm, "from_"+catentryCounter, from);
				        var to=document.getElementById("to_input_"+i+"").value;
				        addHiddenFormElement(cartForm, "to_"+catentryCounter,to);
				        var amount=document.getElementById("amount_select_"+i+"").value;
				        addHiddenFormElement(cartForm, "amount_"+catentryCounter, amount );
				        var message=document.getElementById("message_input_"+i+"").value;
				        addHiddenFormElement(cartForm, "message_"+catentryCounter,   message);
				        if( document.getElementById("email_input_"+i +"")!=null){
				         var email=document.getElementById("email_input_"+i+"").value;
				          addHiddenFormElement(cartForm,"email_"+catentryCounter,email);
				        }
				       catentryCounter++;
				         
	        }//else
      
      
      
       }   // for loop for catentyArray
      
    }
 
	 function validateEmailAddr(email){
		    var regex1 = /^[^\s@]+@([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]\.|[A-Za-z0-9]\.)+([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]|[A-Za-z0-9])$/;
		    var regex2 = /^(root@|abuse@|spam@)/;
		    if(!email.match(regex1)){
		  	    return false;
		    } else if(email.match(regex2)){
		         return false;
		    }
		    return true;
		} 
		
		
		function displayGCValues(){
		var objForm=document.getElementById('submitToCart');
		var testString="";
					 for (var i=0; i<objForm.elements.length; i++) {
						       var element=objForm.elements[i];
						       var elName=element.name;
						       var elType=element.type;
						       var elValue=element.value;
						       var elID=element.id;
						       testString+= elName+'='+elValue+'::';
			                   
			        }
			     //   alert(testString);
		}
		
		/**
		*Function displays page numbers 
		*/
		function displayPageNumbers(cardType,pageCount,pageNo){
	 
		   var addPagination = "";
		   var pageNumberHTML="Page "+pageNo;
			
							  if(pageCount!=1) {
									  if(pageNo>1) {
								 	      addPagination += '<a href="javaScript:;" title="Go to previous page"><img class="btnPrevious" name="btnPrevious" src="'+imagePath+'img/btn/btn_pager_prev.gif" width="66" height="20" alt="last page"></a>';										
								       }	
								addPagination += '<div class="fakeDD" style="width: 62px; height: 15px;">';
	 							addPagination += '<ul class="dd" style="overflow: auto; position: absolute; top: 0pt; left: 0pt; z-index: 10;">';
	 									for(i=1;i<=pageCount;i++) {
	 											addPagination += '<li>Page '+i+'</li>';
	 							
								}
								addPagination += '</ul>';
								 
							 	addPagination += '<span>Page 1</span>';
								addPagination += '<select style="display: none;">';
								for(i=1;i<=pageCount;i++) {
								addPagination += '<option>Page '+i+'</option>';
							 
								}
								addPagination += '</select>';
								addPagination += '</div>';
							
							
				
							
							if(!(pageNo==pageCount)) { 
							  addPagination+='<a href="javaScript:;" title="Go to next page"><img class="btnNext" name="btnNext" src="'+imagePath+'img/btn/btn_pager_next.gif" width="66" height="20" alt="next page"></a>';
						    }
			
			
							  
							  if(cardType==PHYSICAL){
							   
							  	$('#physFilter .right').html(addPagination);
							 	$('#physFilter .right .fakeDD').find('select').val(pageNumberHTML) ;
							 	$('#physFilter .right .fakeDD').find('span').html(pageNumberHTML);
							   }
				               if(cardType!=PHYSICAL){
				             
				               $('#egiftFilter .right').html(addPagination);
				               $('#egiftFilter .right .fakeDD').find('select').val(pageNumberHTML) ;
				               $('#egiftFilter .right .fakeDD').find('span').html(pageNumberHTML);
				                }
		 
						    
							}  
						 if(pageCount==1) {
						// To remove previous page numbers if page count-1
						   if(cardType==PHYSICAL){
							 	$('#physFilter .right').html(addPagination);
							    }
				               if(cardType!=PHYSICAL){
				                $('#egiftFilter .right').html(addPagination);
				                }
	                   	}
		
		
		
		
		}
	/**
	*This function returns page Number
	*/
	function parsePageNumber(pageOptionValue){
	var splitArray   = pageOptionValue.split("Page ");
	return splitArray[1];
	}
	
 function getPageForCard(cardType,pageIndex){
 
  if(pageIndex > 1){
   
  pageIndex= Number(pageIndex);
  GC_PAGE_NUMBER_ADD= Number(GC_PAGE_NUMBER_ADD);
   pageIndex  =((pageIndex-1)*GC_PAGE_NUMBER_ADD)+1;
 
  }
 	getFilters(cardType,pageIndex);
	} 
 

	