var box = {};
var resultList;
var totalResultsLength;
var nextIndex = 0;
var currentIndex = 0;
var offset = 5;
var defOffSet = 5;
var cStart;
function initializeOverlay() {
	box = new MultiBox('mb', {
		'descClassName': 'multiBoxDesc',
		'initialWidth': 313,
		'useOverlay': true,
		'showControls': true,
		'colour': '#333',
		'bgImg': '/images/utility/bg-overlay-gradient.png', // for Mac FireFox
		'useTemplate': false,
		'zIndex': 10
	});
}

function closeOverlay() {
	box.close();
}

function initializePrescriptionRefil() {
	var pn_default = $('prescription-number').get('value');
	
	$('prescription-number').addEvents({
		'focus': function(){
			if(this.get('value') == pn_default) this.set('value','');
		}
	});	
}

function initializeLogin() {
	var usernameLabel = new Element("input", {'type':"text", 'id':"username-label", 'value':"Username", 'alt':"username", 'class':"mock"}).injectBefore($("username"));
	var passwordLabel = new Element("input", {'type':"text", 'id':"password-label", 'value':"Password", 'alt':"password", 'class':"mock"}).injectBefore($("password"));
	
	$('username-label').removeClass('hide');
	$('username').addClass('hide');
	
	$('password-label').removeClass('hide');
	$('password').addClass('hide');
	
	$('username-label').addEvents({
		'focus': function(){
			$('username-label').destroy();
			$('username').removeClass('hide').focus();
		}
	});
	
	$('username').addEvents({
		'blur': function(){
			if(this.get('value') == '')
			{
				new Element("input", {'type':"text", 'id':"username-label", 'value':"Username", 'alt':"username", 'class':"mock"}).injectBefore($("username")).addEvents({
					'focus': function(){
						$('username-label').destroy();
						$('username').removeClass('hide').focus();
					}
				});
				$('username').addClass('hide');
			}
		}
	});
	
	
	$('password-label').addEvents({
		'focus': function(){
			$('password-label').destroy();
			$('password').removeClass('hide').focus();
		}
	});

	$('password').addEvents({
		'blur': function(){
			if(this.get('value') == '')
			{
				new Element("input", {'type':"text", 'id':"password-label", 'value':"Password", 'alt':"password", 'class':"mock"}).injectBefore($("password")).addEvents({
					'focus': function(){
						$('password-label').destroy();
						$('password').removeClass('hide').focus();
					}
				});
				$('password').addClass('hide');
			}
		}
	});
}

function initializeEmailSignup() {
	var email_default = $('email').get('value');
	
	$('email').addEvents({
		'focus': function(){
			if(this.get('value') == email_default) this.set('value','');
		},
		'blur': function(){
			if(this.get('value') == '') this.set('value',email_default);
		}
	});
}

/**
 * added for the home page body email Sign up  
 * 
 */
function initializeBodyEmailSignup() {
    var email_default = $('offersemail').get('value');
    
    $('offersemail').addEvents({
          'focus': function(){
                if(this.get('value') == email_default) this.set('value','');
          },
          'blur': function(){
                if(this.get('value') == '') this.set('value',email_default);
          }
    });
}

function initializePhoneField() {
	if($('txtPhoneNumber')) {
		var phone_default = $('txtPhoneNumber').get('value');
		$('txtPhoneNumber').addEvents({
			'focus': function(){
				if(this.get('value') == phone_default) this.set('value','');
			},
			'blur': function(){
				if(this.get('value') == '') this.set('value',phone_default);
			}
		});
	}
	
	if($('phone')) {
		var phone_default = $('phone').get('value');
		$('phone').addEvents({
			'focus': function(){
				if(this.get('value') == phone_default) this.set('value','');
			},
			'blur': function(){
				if(this.get('value') == '') this.set('value',phone_default);
			}
		});
	}
	
	if($('fax')) {
		var phone_default = $('fax').get('value');
		$('fax').addEvents({
			'focus': function(){
				if(this.get('value') == phone_default) this.set('value','');
			},
			'blur': function(){
				if(this.get('value') == '') this.set('value',phone_default);
			}
		});
	}
}

function initializeBirthDate() {
	var birthdate_default = $('txtBirthDate').get('value');
	$('txtBirthDate').addEvents({
		'focus': function(){
			if(this.get('value') == birthdate_default) this.set('value','');
		},
		'blur': function(){
			if(this.get('value') == '') this.set('value',birthdate_default);
		}
	});
}

function initializePromoCode() {
	var promocode_default = $('txtPromoCode').get('value');
	$('txtPromoCode').addEvents({
		'focus': function(){
			if(this.get('value') == promocode_default) this.set('value','');
		},
		'blur': function(){
			if(this.get('value') == '') this.set('value',promocode_default);
		}
	});
}

function initializeZIP() {
	var zipCode = $('zipCode').get('value');
	$('zipCode').addEvents({
		'focus': function(){
			if(this.get('value') == zipCode) {
				this.set('value','');
			}
		},
		'blur': function(){
			if(this.get('value') == '') this.set('value',zipCode);
		}
	});
}

/**
 * Preload all mouseover images on the page and define a mouseover and mouseout
 * event for those images. All that is required is that the image has a class
 * name consisting of mouseover_* with the * being the rollover key to
 * apply to the mouseover image.
 *
 * i.e. look at the following examples to see how the class name is parsed
 *      <img class="mouseover_r" src="myimage.gif" alt=""/>
 *      out image = myimage.gif
 *      over image = myimage_r.gif
 *
 * @important! this function must be called by the onload event
 *
 * @param image(id string) - id of element to apply mouseover functionality.
 *		if undefined, the script will check and apply to all img elements.
 * @return void
 *
 * @author Toby Miller <tmiller@resource.com>
 * @author Josh Zeigler <jzeigler@resource.com>
*/
var _SPACER_IMAGE = "/images/utility/spacer.gif";
function mouseover(image)
{
    // set internal vars
    var extlist = ['gif', 'jpg', 'jpeg', 'png'];
    var ext = null;
    var re = null;
    var klass = null;
    var key = null;
    var src = null;
    var oversrc = null;

    var init = function(el) {
    	
    	// get image source and class name
        src = el.src;
        klass = el.className;

        if (klass.contains('mouseover_')) {
            // strip out additional classes (if they exist)
            re = new RegExp('.*(mouseover_[a-zA-Z0-9-]+).*');
            klass = klass.replace(re, '$1');

            // find the supported extension
            extlist.each(function(x) {
                re = new RegExp('\\.' + x + '$');
                if (src.match(re)) {
                    ext = x;
                }
            });
	    
            if (ext != null) {
                // get this mouseover key
                re = new RegExp('mouseover(_[a-zA-Z0-9-]+)');
                key = klass.replace(re, '$1');

                if ((ext == 'png') && (document.all) && (navigator.userAgent.toUpperCase().indexOf('OPERA') < 0) && (navigator.userAgent.indexOf('MSIE 7') < 0)) {
                    // get this mouseovers over src
                    re = new RegExp('\\.' + ext + '$');
                    oversrc = src.replace(re, key + '.' + ext);

                    // get the dimensions
                    width = el.getProperty('width');
                    height = el.getProperty('height');

                    // force the spacer for transparent backgrounds
                    el.setProperty('src', _SPACER_IMAGE);

                    // setup the new properties (replace mouseovers)
                    el.overFilter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + oversrc + '\', sizingMethod=scale)';
                    el.outFilter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=scale)';

                    // apply the defaults
                    el.style.filter = el.outFilter;
                    el.style.width = width + 'px';
                    el.style.height = height + 'px';

                    // setup onmouseover event
                    el.addEvent('mouseenter', function(){
                        this.setStyle('filter', this.overFilter);
                    });

                    // setup onmouseout event
                    el.addEvent('mouseleave', function(){
                        this.setStyle('filter', this.outFilter);
                    });
                }
                else {
                    // get this mouseovers over src
                    re = new RegExp('\\.' + ext + '$');
                    oversrc = src.replace(re, key + '.' + ext);

                    // preload both over and out images
                    el.overImage = new Image();
                    el.overImage.src = oversrc;
                    el.outImage = new Image();
                    el.outImage.src = src;
		    
                    // setup onmouseover event
                    el.addEvent('mouseenter', function(){
                        this.setProperty('src', this.overImage.src);
                    });

                    // setup onmouseout event
                    el.addEvent('mouseleave', function(){
                        this.setProperty('src', this.outImage.src);
                    });
		    
                }
            }
        }

        // reset vars
        ext = null;
        re = null;
        klass = null;
        key = null;
        src = null;
        oversrc = null;
    };

    if(image != undefined) {
	if($type(image) == "element") init(image);
	else if($(image)) init($(image));
    }
    else {
        $$('img').each(init);
    }
}

//on DOMReady, load up the mouse over events
window.addEvent('domready', mouseover);
window.addEvent('domready',function() {
	
	var storenet_check = Cookie.read('mwb_store_nbr');
	
	if (!storenet_check) {
		// grab all anchors with rel="_blank"
		$$('a[rel^=_blank]').addEvent('click',function(e){
			new Event(e).stop(); // stops the click action
			window.open(this.get('href')); // open it in a new window
		});
		
		     if($('findStore')) {
		        if($('commentErro')){
		           $('commentErro').innerHTML='';
		           $('commentErro').style.visibility='hidden';
		        }
		        
		        
		      $('findStore').addEvent('click', function(event) {
		      event.stop();
			 var searchOption=new Array;
			 if($('open-24-hours').checked){
			    searchOption.push($('open-24-hours').get('value'));;
			 }
			 if($('drive-thru').checked){
				 searchOption.push($('drive-thru').get('value'));;
			 }
	
		         var req = new Request({  
		             method: 'post',  
		             url: '/marketing/storelocator/handleSearch.html',
		             data: {'searchOptions=':searchOption,
						 'combCriteria' : $('combCriteria').get('value'), 
						 'storeOverlay' : $('storeOverlay').get('value'),
						 'requestType':$('requestType').get('value'),
						 'source':$('source').get('value'),
						 'successView':$('successview').get('value'),
						 'errorView':$('errorview').get('value'), 
						 'multipleView':$('multipleview').get('value'), 
						 'address':''
					 },  
		             onRequest: function() { 
		                 //alert('Request made. Please wait...Any logic before request is made can be placed here');
			       },  
		         onComplete: function(response) { 
		         	var Data;
				       //get the parent document and the multiboxcontainer for enlarging.
				       //the size of enlarging can be controlled by the number of records returned
				       var doc=parent.document;
				       //alert(response);
				       response=eval( '(' + response + ')' );
	
				       var errFound = 'false';
				       var errString = '';
				       
					       switch(response.storeDetails[0].searchStatus){
							case 'session':
								errString='<strong>Session Expired:</strong> Your session has expired due to a time lapse. Please search again.';
								errFound = 'true';
								break;
							case 'general':
								errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'noStoreFound':
								errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'address':
								errString='<strong>ddress Match:</strong> This address shows no results. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'all':
								errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'zip':
								errString='<strong>ZIP Code Match:</strong> This ZIP code shows no results. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'wagError':
								errString='<strong>Temporarily Unavailable:</strong> The Store Locator Utility is temporarily unavailable. Please try again later.';
								errFound = 'true';
								break;
							case 'mqError':
								errString='<strong>Temporarily Unavailable:</strong> The Store Locator is temporarily unavailable. Please try again later.';
								errFound = 'true';
								break;
							case 'missingCriteria':
								errString='<strong>Missing or Invalid Info:</strong> The city, state or ZIP code entered is missing or invalid. Please modify your search and try again.';
								errFound = 'true';
								break;
							case 'invalidSearchCriteria':
								errString='<strong>Missing or Invalid Info:</strong> The city, state or ZIP code entered is missing or invalid. Please modify your search and try again.';
								errFound = 'true';
								break;
						}
		                      
		                      
		           if (errFound == 'true' || !response.storeDetails[0].results) {
		                if(!response.storeDetails[0].results){
		                    errString = 'The city, state or ZIP code entered is invalid';
		                }
		           	var commentErrorDiv = $('commentErro');
		           	commentErrorDiv.innerHTML=errString;
		           	commentErrorDiv.style.visibility='visible';
				commentErrorDiv.style.display='block';
				errFound = 'false';		
				errString = '';
				Data='';
				$('resultsContainer').innerHTML=Data;
				if(doc.getElementsByClassName){
					doc.getElementsByClassName('MultiBoxContainer')[0].set('styles' , { 'height':'180px'});
					doc.getElementsByClassName('MultiBoxContent')[0].set('styles' , { 'height':'180px'});
				} else {
					i = 0;
		               	a = doc.getElementsByTagName("div");
				            while (element = a[i++]) {
	  				           if (element.className == "MultiBoxContainer") {
	    			         	     var boxes=element;
	    			            }
	  			          }
						  var cc=boxes.firstChild;
				  	        //alert(mbcc);
				  	        var mbcc=cc.firstChild;
				   	        //alert(mbcc);
				   			    var ifram=mbcc.firstChild;
				  			    //alert(ifram);
				   			    
				   	                //resize the multibox
	
						   boxes.set('styles' , { 'height':'180px'});
						   cc.set('styles',{  'height': '180px'});
				   			    mbcc.set('styles', { 'height':'180px'});		    
		                       ifram.set('styles', { 'height':'180px'});	
		                       ifram.set('height','180px');
				}
				return;
		           }
		           
		           if(doc.getElementsByClassName){        
		           	var boxes=doc.getElementsByClassName('MultiBoxContainer');
				            var cc=doc.getElementsByClassName('MultiBoxContent');
				    
				    			  cc[0].set('styles',{ 'width': '633px', 'height': '600px'});
				    	      //mbcc is MultiBoxContentContainer 
				    	      var mbcc=cc[0].childNodes;
				    	                
				    		  	var ifram=mbcc[0].childNodes;
				    			    
				    	      //resize the multibox
				    	      if(response.storeDetails[0]){
				    		    boxes[0].set('styles' , {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});
				    		    cc[0].set('styles',{ 'width': '633px', 'height': '770px'});
		                        ifram[0].set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});		    
		                      }
		            }  else {
		                i = 0;
		               	a = doc.getElementsByTagName("div");
				            while (element = a[i++]) {
	  				           if (element.className == "MultiBoxContainer") {
	    			         	     var boxes=element;
	    			            }
	  			          }
	  			   
				   			    //cc.set('styles',{ 'width': '633px', 'height': '658px'});
				   	        //mbcc is MultiBoxContentContainer 
				 	          var cc=boxes.firstChild;
				  	        //alert(mbcc);
				  	        var mbcc=cc.firstChild;
				   	        //alert(mbcc);
				   			    var ifram=mbcc.firstChild;
				  			    //alert(ifram);
				   			    
				   	                //resize the multibox
				   	   if(response.storeDetails[0]){
				   			    boxes.set('styles' , {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});
				   			    cc.set('styles',{ 'width': '633px', 'height': '770px'});
				   			    mbcc.set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});		    
				   			    
		                       ifram.set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'100px', 'left':'200px'});	
		                       ifram.set('height','770px');
		                       ifram.set('width','633px');
		               }
	  		        }
							    
		              //write inital static ontent to the page
				        var clear=$('findAWalgreensForm');
				        var table = new Element( 'div' , { 'id':'resultsContainer'}) ;
		            table.inject(clear);
		             var table1 = new Element( 'div' , { 'id':'paginationLinks'}) ;
		            table1.inject(clear);
				    
		            //var colGroup = new Element( 'colgroup' , { }) ;
				        //colGroup.injectInside(table);
		            //var col1 = new Element( 'col' , {'width':'35' }) ;
				        //col1.injectInside(colGroup);
			
		            
		            Data='<table id="results-container" cellpadding="0" cellspacing="0" border="0"><colgroup><col width="35" /><col width="250" /><col width="200" /><col width="115" /></colgroup><tr><th>&nbsp;</th><th>Store Location</th><th>Pharmacy Hours</th><th>&nbsp;</th></tr>';
				            //Data=Data+'<tr><td><strong></strong></td><td>Store<br/><br/><br/><br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" alt="Choose This Store" class="pickStore" value="1234"/></td></tr>';	
		                //$('results-container').innerHTML=Data;
		                //alert(response);
		            var result;
		            var length=response.storeDetails[0].results.length;
						    totalResultsLength = length;
						    resultList = response.storeDetails[0].results;
			    if (totalResultsLength < defOffSet) {
			    	offset = totalResultsLength;
			    } else {
			    	offset = defOffSet;
			    }
		            for(i=0;i<offset;i++){
		               result =response.storeDetails[0].results[i];
		               
						       var x= i+1;
							 var sNumber =  result.storeNumber;
							 if(result.storeInfoBean){
	
					         Data=Data+'<tr><td><strong>'+x+'</strong></td><td>Store '+result.storeNumber+'<br/>'+result.address+'<br/>'+result.city+','+result.state+' '+result.zipcode+'<br/>'+'('+result.storeInfoBean.storeAreaCd + ')'+result.storeInfoBean.storePhoneNum.substring(0,3) + '-' +result.storeInfoBean.storePhoneNum.substring(3.7)+'<br/>'+result.storeInfoBean.intersection+'<br/></td>'
							 Data=Data+ storeHours(result);
							 Data=Data+'<td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore"  onclick="selectstore('+sNumber+');" alt="Choose This Store" class="pickStore" value="'+sNumber+'"/></td></tr>';
							 } else {
	                         Data=Data+'<tr><td><strong>'+x+'</strong></td><td>Store '+result.storeNumber+'<br/>'+result.address+'<br/>'+result.city+','+result.state+' '+result.zipcode+'<br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore"  onclick="selectstore('+sNumber+');" alt="Choose This Store" class="pickStore" value="'+sNumber+'"/></td></tr>';
							 }
	
					         
			        
				        }
	
					      nextIndex = currentIndex + offset;
					      $('resultsContainer').innerHTML=Data;
					     Data='';
					     Data='<table cellpadding="0" cellspacing="0" border="0">';
						  Data=Data+'<tr>';
						  Data=Data+'<td width="98%"></td>';
						  if(response.prevDataURL)
					           Data = Data +'<td width="1%"><a href="#" class="pagination" title="prev" id="'+response.prevDataURL+'"><img src="/images/buttons/prev-btn.gif" alt="Previous Page" width="18" height="18" class="vertical-middle"  /></a>&nbsp;&nbsp;</td>';
						  if(response.nextDataURL)
						       Data=  Data +'<td width="1%"><a href="#" class="pagination" title="next" id="'+response.nextDataURL+'"><img src="/images/buttons/next-btn.gif" alt="Next Page" width="18" height="18" class="vertical-middle" /></a></td>';
						  Data=Data+'</tr>';
						  $('paginationLinks').innerHTML=Data;  // store locator common function for pagination.
	                                          // this will call next and previous functions.
						  if(response.prevDataURL || response.nextDataURL)
							  initializePagination();
		            //initializePickStore();
				        return(false);	
		             }  
		         }).send();	          
		       });
		      }     
		
		if($('prescription-number')) {
			initializePrescriptionRefil();
		}
	
		if($('username')) {
			initializeLogin();
		}
	
		if($('email')) {
			initializeEmailSignup();
		}
		
		if ($('txtPhoneNumber')) {
			initializePhoneField();
		}
		
		if ($('txtBirthDate')) {
			initializeBirthDate();
		}
		
		if ($('txtPromoCode')) {
			initializePromoCode();
		}
		
		if ($('zipCode')) {
			initializeZIP();
		}
		// added for the Homepage Body email Sign up
		if($('offersemail')) {
		      initializeBodyEmailSignup();
		}
		initializeOverlay();
	} else {
		// alert('storenet cookie found');
	}
});
function get_search_string(url,targetvar) 
{ 

	var param=(url.slice(1)) 
	var pairs = param.split("&") 

		for(var i = 0; i < pairs.length; i++) 
		{ 
			var pos = pairs[i].indexOf('=') 
			if (pos == -1) continue 
			var argname = pairs[i].substring(0,pos) 
			var value = pairs[i].substring(pos+1) 
			if (argname == targetvar) 
			{ 
				var searchstring = value 
				{break} 
			} 
		} 

	return searchstring 
} 
function initializePagination(){
	$$('.pagination').each(function(el){
		el.addEvent('click', function(event) {
	         event.stop(); 

	
	         var req = new Request({  
	             method: 'post',  
	          	 url: '/marketing/storelocator/handleNextPrevResult.html',
	             data: { 
	                  'url' : this.get('title'),
					  'storeOverlay':'true',
					  'requestType':'overlay',
					  'actionURL':this.get('id')
	             },  
	             onRequest: function() { 
	                 //alert('Request made. Please wait...Any logic before request is made can be placed here');
		         },  
	            onComplete: function(response) { 
	         	  	var Data;
			       //get the parent document and the multiboxcontainer for enlarging.
			       //the size of enlarging can be controlled by the number of records returned
			       var doc=parent.document;
			       
			       response=eval( '(' + response + ')' );

			       var errFound = 'false';
			       var errString = '';
			       switch(response.storeDetails[0].searchStatus){
					case 'session':
						errString='<strong>Session Expired:</strong> Your session has expired due to a time lapse. Please search again.';
						errFound = 'true';
						break;
					case 'general':
						errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'noStoreFound':
						errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'address':
						errString='<strong>ddress Match:</strong> This address shows no results. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'all':
						errString='<strong>No Results:</strong> This information produced no results. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'zip':
						errString='<strong>ZIP Code Match:</strong> This ZIP code shows no results. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'wagError':
						errString='<strong>Temporarily Unavailable:</strong> The Store Locator Utility is temporarily unavailable. Please try again later.';
						errFound = 'true';
						break;
					case 'mqError':
						errString='<strong>Temporarily Unavailable:</strong> The Store Locator is temporarily unavailable. Please try again later.';
						errFound = 'true';
						break;
					case 'missingCriteria':
						errString='<strong>Missing or Invalid Info:</strong> The city, state or ZIP code entered is missing or invalid. Please modify your search and try again.';
						errFound = 'true';
						break;
					case 'invalidSearchCriteria':
						errString='<strong>Missing or Invalid Info:</strong> The city, state or ZIP code entered is missing or invalid. Please modify your search and try again.';
						errFound = 'true';
						break;
				}        
	                      
	                      
	           if (errFound == 'true') {
	           	var commentErrorDiv = $('commentError');
	           	commentErrorDiv.innerHTML=errString;
	           	commentErrorDiv.style.visibility='visible';
			commentErrorDiv.style.display='block';
			errFound = 'false';		
			errString = '';
			Data='';
			$('resultsContainer').innerHTML=Data;
			if(doc.getElementsByClassName){
				doc.getElementsByClassName('MultiBoxContainer')[0].set('styles' , { 'height':'180px'});
				doc.getElementsByClassName('MultiBoxContent')[0].set('styles' , { 'height':'180px'});
			} else {
					i = 0;
	               	a = doc.getElementsByTagName("div");
			            while (element = a[i++]) {
  				           if (element.className == "MultiBoxContainer") {
    			         	     var boxes=element;
    			            }
  			          }
					  var cc=boxes.firstChild;
			  	        //alert(mbcc);
			  	        var mbcc=cc.firstChild;
			   	        //alert(mbcc);
			   			    var ifram=mbcc.firstChild;
			  			    //alert(ifram);
			   			    
			   	                //resize the multibox

					   boxes.set('styles' , { 'height':'180px'});
					   cc.set('styles',{  'height': '180px'});
			   			    mbcc.set('styles', { 'height':'180px'});		    
	                       ifram.set('styles', { 'height':'180px'});	
	                       ifram.set('height','180px');
			}
			return;
	           }
	           
	           if(doc.getElementsByClassName){        
	           	var boxes=doc.getElementsByClassName('MultiBoxContainer');
			            var cc=doc.getElementsByClassName('MultiBoxContent');
			    
			    			  cc[0].set('styles',{ 'width': '633px', 'height': '600px'});
			    	      //mbcc is MultiBoxContentContainer 
			    	      var mbcc=cc[0].childNodes;
			    	                
			    		  	var ifram=mbcc[0].childNodes;
			    			    
			    	      //resize the multibox
			    	      if(response.storeDetails[0]){
			    		    boxes[0].set('styles' , {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});
			    		    cc[0].set('styles',{ 'width': '633px', 'height': '770px'});
	                        ifram[0].set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});		    
	                      }
	            }  else {
	                i = 0;
	               	a = doc.getElementsByTagName("div");
			            while (element = a[i++]) {
  				           if (element.className == "MultiBoxContainer") {
    			         	     var boxes=element;
    			            }
  			          }
  			   
			   			    //cc.set('styles',{ 'width': '633px', 'height': '658px'});
			   	        //mbcc is MultiBoxContentContainer 
			 	          var cc=boxes.firstChild;
			  	        //alert(mbcc);
			  	        var mbcc=cc.firstChild;
			   	        //alert(mbcc);
			   			    var ifram=mbcc.firstChild;
			  			    //alert(ifram);
			   			    
			   	                //resize the multibox
			   	   if(response.storeDetails[0]){
			   			    boxes.set('styles' , {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});
			   			    cc.set('styles',{ 'width': '633px', 'height': '770px'});
			   			    mbcc.set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'50px', 'left':'200px'});		    
			   			    
	                       ifram.set('styles', {'visibility':'visible', 'opacity':'1', 'display':'block', 'width':'633px', 'height':'770px', 'top':'100px', 'left':'200px'});	
	                       ifram.set('height','770px');
	                       ifram.set('width','633px');
	               }
  		        }
						    
	              //write inital static ontent to the page
			        var clear=$('findAWalgreensForm');
			        var table = new Element( 'div' , { 'id':'resultsContainer'}) ;
	            table.inject(clear);
                        var table2=new Element('div', {'id':'paginationLinks'});
                        table2.inject(clear);
			    
	            //var colGroup = new Element( 'colgroup' , { }) ;
			        //colGroup.injectInside(table);
	            //var col1 = new Element( 'col' , {'width':'35' }) ;
			        //col1.injectInside(colGroup);
		
	            
	            Data='<table id="results-container" cellpadding="0" cellspacing="0" border="0"><colgroup><col width="35" /><col width="250" /><col width="200" /><col width="115" /></colgroup><tr><th>&nbsp;</th><th>Store Location</th><th>Pharmacy Hours</th><th>&nbsp;</th></tr>';
			            //Data=Data+'<tr><td><strong></strong></td><td>Store<br/><br/><br/><br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" alt="Choose This Store" class="pickStore" value="1234"/></td></tr>';	
	                //$('results-container').innerHTML=Data;
	                //alert(response);
	            var result;
	            var length=response.storeDetails[0].results.length;
					    totalResultsLength = length;
					    resultList = response.storeDetails[0].results;
		    if (totalResultsLength < defOffSet) {
		    	offset = totalResultsLength;
		    } else {
		    	offset = defOffSet;
		    }
		        var pResult = get_search_string(response.nextDataURL,'pageResults');
		        var pResultStart = get_search_string(response.nextDataURL,'pageResultsStart');
	            for(i=0;i<offset;i++){
	               result =response.storeDetails[0].results[i];
	               
					     var x= i+1 +(pResultStart-pResult);
						 var sNumber =  result.storeNumber;
						 if(result.storeInfoBean){

				         Data=Data+'<tr><td><strong>'+x+'</strong></td><td>Store '+result.storeNumber+'<br/>'+result.address+'<br/>'+result.city+','+result.state+' '+result.zipcode+'<br/>'+'('+result.storeInfoBean.storeAreaCd + ')'+result.storeInfoBean.storePhoneNum.substring(0,3) + '-' +result.storeInfoBean.storePhoneNum.substring(3.7)+'<br/>'+result.storeInfoBean.intersection+'<br/></td>'
						 Data=Data+ storeHours(result);
						 Data=Data+'<td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore"  onclick="selectstore('+sNumber+');" alt="Choose This Store" class="pickStore" value="'+sNumber+'"/></td></tr>';
						 } else {
                         Data=Data+'<tr><td><strong>'+x+'</strong></td><td>Store '+result.storeNumber+'<br/>'+result.address+'<br/>'+result.city+','+result.state+' '+result.zipcode+'<br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore"  onclick="selectstore('+sNumber+');" alt="Choose This Store" class="pickStore" value="'+sNumber+'"/></td></tr>';
						 }

				         
		        
			        }

				     nextIndex = currentIndex + offset;
				     $('resultsContainer').innerHTML=Data;
				     Data='';
				     Data='<table cellpadding="0" cellspacing="0" border="0">';
				     					  Data=Data+'<tr>';
				     					  Data=Data+'<td width="98%"></td>';
				     					  if(response.prevDataURL)
				     				           Data = Data +'<td width="1%"><a href="#" class="pagination" title="prev" id="'+response.prevDataURL+'"><img src="/images/buttons/prev-btn.gif" alt="Previous Page" width="18" height="18" class="vertical-middle"  /></a>&nbsp;&nbsp;</td>';
				     					  if(response.nextDataURL)
				     					       Data=  Data +'<td width="1%"><a href="#" class="pagination" title="next" id="'+response.nextDataURL+'"><img src="/images/buttons/next-btn.gif" alt="Next Page" width="18" height="18" class="vertical-middle" /></a></td>';
				     					  Data=Data+'</tr>';
				     					  $('paginationLinks').innerHTML=Data;  // store locator common function for pagination.
				                                               // this will call next and previous functions.
				     					  if(response.prevDataURL || response.nextDataURL)
						                                initializePagination();
	            //initializePickStore();
			        return(false);	
	             }
	         }).send();	   
	       });
	      });     
}

function initializePickStore(){

      if($('pickStore')){
	    $('pickStore').addEvent('click', function(event) {
	       //alert(this.get('value'));
	            $('pickUpStore').value=this.get('value');
	    });
      }
}

function selectstore(storeNumber){
	$('pickUpStore').value=storeNumber;
}

var DropDown = new Class({
	/**
	 * implements
	 */
	Implements: [Options],
	
	version: "1.0.0",

	/**
	 * defaultOptions
	 * Options used by default
	 */
	defaultOptions: {
		'showClassName': 'show',
		'hideClassName': 'hide',
		'closeClassName': "close",
		'mouseoverClassName': "mouseover_on",
		'menuDuration': 500,
		'iframeFix': true
	},

	_ddActive: false,
	_ddOpen: false,
	_ddSlideIn: false,
	_ddSlideOut: false,

	initialize: function(triggerClass, options) {	
		this.setOptions(this.defaultOptions, options);
		this.triggerClass = triggerClass;
		this.menus = {};

		var secureBlankPage = '';
		var isIE6 = (document.all) && (navigator.userAgent.toUpperCase().indexOf('OPERA') < 0) && (navigator.userAgent.indexOf('MSIE 7') < 0);
		if (isIE6) {
			secureBlankPage = '/pharmacy/includes/blank.jsp';
		}
		var secureBlankPage = '';
		var isIE6 = (document.all) && (navigator.userAgent.toUpperCase().indexOf('OPERA') < 0) && (navigator.userAgent.indexOf('MSIE 7') < 0);
		if (isIE6) {
			secureBlankPage = '/pharmacy/includes/blank.jsp';
		}

		this.createEvents();
	},
	
	createEvents: function() {		
		$$("." + this.triggerClass).each(function(el) {
			var menu = el.rel;
			this.menus[menu] = new Fx.Slide(menu, {duration: this.options.menuDuration, onComplete: this.setMenuEvents.pass(el, this)});
			if(!$(menu).hasClass(this.options.hideClassName)) {
				this._ddOpen = [menu, el];
			}
			else {
				this.menus[menu].hide();
				$(menu).removeClass(this.options.hideClassName);
			}
			el.addEvent('mouseleave', this.leave.pass([el, 'trigger'], this));
			el.addEvent('mouseover', this.over.pass([el, 'trigger'], this));
			
			$$("#" + el.rel + " ." + this.options.closeClassName).each(function(el) {
				el.addEvent('click', function(e) {
					new Event(e).stop();
					this.resetTriggerImage($(this._ddOpen[1]).getElement("img"));
					this.menus[this._ddOpen[0]].cancel();
					this.menus[this._ddOpen[0]].hide();
					$clear(this._ddSlideOut);
					this._ddOpen = false;
					return(false);
				}.bind(this));
			}.bind(this));
		}.bind(this));

	},
	
	setMenuEvents: function(el) {
		$(el.rel).addEvent('mouseleave', this.leave.pass([el, 'menu'], this));
		$(el.rel).addEvent('mouseover', this.over.pass([el, 'menu'], this));
	},
	
	removeMenuEvents: function(id) {
		$(id).removeEvent('mouseleave');
		$(id).removeEvent('mouseover');
	},
	
	over: function(el, source) {
		if(this._ddActive[0] == el.rel) {
			if(this._ddActive[1]) $clear(this._ddSlideOut);
			else return(false);
		}
		else {
			if(this._ddOpen) {
				this.resetTriggerImage($(this._ddOpen[1]).getElement("img"));
				this.menus[this._ddOpen[0]].cancel();
				this.menus[this._ddOpen[0]].hide();
				$clear(this._ddSlideOut);
				$clear(this._ddSlideIn);
			}

			this._ddActive = [el.rel, source];

			var img = el.getElement("img");
			img.removeEvents();

			this._ddOpen = [el.rel, el];
			this.menus[this._ddOpen[0]].cancel();
			this._ddSlideIn = this.slideIn.delay(this.options.menuDuration, this, [el]);
		}
	},
	
	slideIn: function(el) {
		this.menus[el.rel].slideIn();
	},
	
	leave: function(el, source) {
		this._ddSlideOut = this.slideOut.delay(this.options.menuDuration, this, el);
	},
	
	slideOut: function(el) {
		if(this._ddActive[0] == el.rel) {
			this.removeMenuEvents(el.rel);
			this.menus[el.rel].cancel();
			this.menus[el.rel].slideOut();
			this._ddOpen = false;
			this._ddActive = false;
			this.resetTriggerImage.delay(this.options.menuDuration, this, el.getElement("img"), this);
		}
	},
	
	resetTriggerImage: function(img) {
		if(img.outImage && img.hasClass(this.options.mouseoverClassName)) {
			img.setProperty('src', img.outImage.src);
			mouseover(img);
		}
	}
});

var headerMenu;
var miniCart;
window.addEvent('domready', function() {
	headerMenu = new DropDown("primaryNav")
	//Commenting out minicart for the July Release
	//miniCart = new DropDown("miniCart");
});

var Tabs = new Class({	
	/**
	 * implements
	 */
	Implements: [Options],
	
	version: "1.0.0",

	/**
	 * defaultOptions
	 * Options used by default
	 */
	defaultOptions: {
		'tabClassName': 'tab-container',
		'containerSlug': 'content',
		'selectedClassName': 'on',
		'mouseoverKey': 'on',
		'hideClassName': 'hide',
		'tabSlug': 'tab',
		'sectionHeaderClassName': 'section-header'
	},
	
	initialize: function(tabContainer, options) {
		this.setOptions(this.defaultOptions, options);
		this.activeTab = false;
		this.triggers = $(tabContainer).getElements("div." + this.options.tabClassName + " div.tab");
		this.addEvents();

		$(tabContainer).getElements("div." + this.options.tabClassName).removeClass(this.options.hideClassName);
	},
	
	addEvents: function() {
		this.triggers.each(function(el, index) {
			var id = el.getProperty("id");
			
			var contentDivId = id.replace('tab-', '') + '-' + this.options.containerSlug;
			$(contentDivId).removeClass('large-gradient-box');
			
			var contentHeader = $(contentDivId).getElements('h2.' + this.options.sectionHeaderClassName);
			if (contentHeader) {
				contentHeader.addClass('hide');
			}
			
			if (index > 0) {
				$(contentDivId).addClass(this.options.hideClassName);
			}
			
			el.addEvent('click', function(e) {
				new Event(e).stop();
				this.toggleTabs(id);
				return(false);
			}.bind(this));
		}, this);
	},
	
	toggleTabs: function(id) {
		var active = $$("div." + this.options.tabClassName + " div." + this.options.selectedClassName)[0];
		var activeId = $$("div." + this.options.tabClassName + " div." + this.options.selectedClassName)[0].getProperty('id');
		
		if(id != activeId) {
			if(active) {
				activeId = activeId.replace(this.options.tabSlug + "-", "");
				active.removeClass(this.options.selectedClassName);
				$(activeId + "-" + this.options.containerSlug).addClass(this.options.hideClassName);
			}
			
			$(id).addClass(this.options.selectedClassName);
			$(id.replace(this.options.tabSlug + "-", "") + "-" + this.options.containerSlug).removeClass(this.options.hideClassName);
		}
	}
});

/*
 *	Quick Look
*/
/*
 *     Defect ID : 4443 
 *     Defect Description : Product Quick view button displays blank popup  .
 *     Change/s Done : replaced ID with ID=
 *     Owner : vishal agrawal (Professional Access)
 *     Date and Time : 25-08-09, 03:22 P.M.

*/
function QuickLook(el) {
	if(el.quicklook != "enabled") {
		var product = el.getFirst("a");
		var href = product.getProperty("href");
		var qs = "";
		if (href && href.indexOf("ID=") > 0) {
			qs = href.substr(href.indexOf("ID="),href.length);
		var temp1 = qs.substr(qs.indexOf("ID=")+2,href.length);
		var temp2 = qs.substr(qs.indexOf("ID="),2);
		temp2 = temp2.replace('ID','id');
		qs = "?"+temp2+temp1;
		} else {
			qs = (href && href.indexOf("?") > 0 ? href.substr(href.indexOf("?"),href.length) : "");
		}
		
		 // quick look image asset
		var quickLook = new Element('a', {
			'href': '/store/browse/overlays/quick_view_details.jsp'  +qs,
			'class': 'quick-look-trigger',
			'title': 'Quick Look',
			'rel': 'width:597::height:680'
		});
		
		var size;
		if(el.getSize().x / 2 == 0)
		{
			size = 77.5
			
		}
		else
		{
			size = el.getSize().x / 2;
			
		}
		var quickLookImage = new Element('img', {
			'alt':'Quick Look',
			'class': 'quick-image mouseover_on',
			'src': '/images/buttons/quick-look.png',
			'width': '107',
			'height': '26',
			'styles': {
				'height': '26px',
				'left': (size - 75),
				'display': 'none',
				'position': 'absolute',
				'top': (size + 30),
				'width': '107px'
			}
		});
		
		quickLook.adopt(quickLookImage);		
		mouseover(quickLookImage);
	
		// inject the quick look image over each product item
		el.adopt(quickLook);
		box.reinit(quickLook);
	
		// fade it in/out
		el.addEvents({
			'mouseenter': function(e){
				this.getElement('.quick-image').setStyle('display','');
			},
			'mouseleave': function(e){
				this.getElement('.quick-image').setStyle('display','none');
			}
		});
		
		el.quicklook = "enabled";
	}
}




window.addEvent('domready', function() {
	$$('.quick-look').each(function(el) { QuickLook(el) });
});

/*
Class: Slider
        Creates a slider with two elements: a knob and a container. Returns the values.
Note:
        The Slider requires an XHTML doctype.
Arguments:
        element - the knob container
        knob - the handle
        options - see Options below
        maxknob - an optional maximum slider handle
Options:
	start - the minimum value for your slider.
	end - the maximum value for your slider.
        mode - either 'horizontal' or 'vertical'. defaults to horizontal.
        offset - relative offset for knob position. default to 0.
        knobheight - positions the max slider knob
	snap - whether the slider will slide in steps 
	numsteps - number of slide steps 
Events:
        onChange - a function to fire when the value changes.
        onComplete - a function to fire when you're done dragging.
        onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position.
                Passes as parameter the new position.
*/
var Slider = new Class({
	Implements: [Events, Options],

	
	options: {
		onChange: Class.empty,
		onComplete: Class.empty,
		onTick: function(pos){
			this.moveKnob.setStyle(this.p, pos);			
		},
		start: 0,
		end: 100,
		offset: 0,
		knobheight: 20,
		knobwidth: 12,
		mode: 'horizontal',
		clip_w:0, 
		clip_l:0,
		isinit:true,
		range: false,
		numsteps:null
	},

	initialize: function(el, knob, options, maxknob) {
		this.setOptions(options);
		this.element = $(el);
		this.knob = $(knob);
		this.previousChange = this.previousEnd = this.step = -1;
		//this.bkg = $(bkg);
		if(this.options.steps==null) this.options.steps = this.options.end - this.options.start;
		if(maxknob!=null) this.maxknob = $(maxknob);
		//else this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
		var mod, offset;
		switch(this.options.mode){
			case 'horizontal':
				this.z = 'x';
				this.p = 'left';
				mod = {'x': 'left', 'y': false};
				offset = 'offsetWidth';
				break;
			case 'vertical':
				this.z = 'y';
				this.p = 'top';
				mod = {'x': false, 'y': 'top'};
				offset = 'offsetHeight';
		}
		this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.half = this.knob[offset]/2;
		this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
		this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
		this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);

		this.range = this.max - this.min;
		this.steps = this.options.steps || this.full;
		this.stepSize = Math.abs(this.range) / this.steps;
		this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;

		if(maxknob != null) {
			this.maxPreviousChange = -1;
			this.maxPreviousEnd = -1;
			this.maxstep = this.options.end;
			this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
		}
		var lim = {};
		//status = this.z
		lim[this.z] = [- this.options.offset, this.max - this.options.offset];
		//lim[this.z] = [100, this.max - this.options.offset];

		this.drag = new Drag(this.knob, {
			limit: lim,
			modifiers: mod,
			snap: 0,
			onStart: function(){
					this.draggedKnob();
			}.bind(this),
			onDrag: function(){
					this.draggedKnob();
			}.bind(this),
			onComplete: function(){
					this.draggedKnob();
					this.end();
			}.bind(this)
		});
		if(maxknob != null) {  
			this.maxdrag = new Drag(this.maxknob, {
				limit: lim,
				modifiers: mod,
				snap: 0, 
				onStart: function(){
					this.draggedKnob(1);
				}.bind(this),
				onDrag: function(){
					this.draggedKnob(1);
				}.bind(this),
				onComplete: function(){
					this.draggedKnob(1);
					this.end();
				}.bind(this)
			});		
		}

		if (this.options.snap) {
			//this.drag.options.grid = Math.ceil(this.stepWidth);
			this.drag.options.grid = (this.full)/this.options.numsteps ;
			this.drag.options.limit[this.z][1] = this.full;
			//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
			//status = "GRID - " + this.drag.options.grid  + "  , full = " + this.full// DEBUG

		}
		if (this.options.initialize) this.options.initialize.call(this);
	},
	
	setMin: function(stepMin){
		this.step = stepMin.limit(this.options.start, this.options.end);
		this.checkStep();
		this.end();
		this.moveKnob = this.knob;
		//this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
		//status =this.bkg.style.clip + "  vl= " + parseInt(this.toPosition(this.step)) ; //Debug
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
	},
	
	setMax: function(stepMax){
		this.maxstep = stepMax.limit(this.options.start, this.options.end);
		this.checkStep(1);
		this.end();
		this.moveKnob = this.maxknob;
		var w = Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3;
		var r = parseInt(this.clip_l + w); 
		//this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)";

		this.fireEvent('onTick', this.toPosition(this.maxstep));
		// For Init Only 
		if(this.options.isinit){
			var lim = {}; var mi,mx;
			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;
			this.options.isinit = false;
		}
		return this; 
	},
	
	clickedElement: function(event){
		var position = event.page[this.z] - this.getPos() - this.half;
		position = position.limit(-this.options.offset, this.max -this.options.offset);

		this.step = this.toStep(position);

		//this.moveKnob = this.knob;
		//this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"  
		//status =this.bkg.style.clip; //Debug
		this.checkStep();
		this.end();
		this.fireEvent('onTick', position);
	},

	draggedKnob: function(mx){
		var lim = {}; var mi,mx;
		if(mx==null) {
			this.step = this.toStep(this.drag.value.now[this.z]);	 
			this.checkStep();
		}else {
			this.maxstep = this.toStep(this.maxdrag.value.now[this.z]); 
			this.checkStep(1);
		}
	},
	
	checkStep: function(mx){
		var lim = {}; var mi,mx;
		var limm = {};
		if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
		else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}

		if(this.maxknob!=null) {

			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-((this.knob.getSize().x-1)/2);
			//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;
		

			mi = parseInt(this.knob.getStyle('left'))-this.options.offset+((this.knob.getSize().x+1)/2); 
			//mi = parseInt(this.knob.getStyle('left'))-this.options.offset; 
			
			mx= this.max - this.options.offset;
			limm[this.z] = [mi, mx];
			this.maxdrag.options.limit = limm; 

			if(this.step < this.maxstep){
				this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
				//this.clip_l = parseInt(this.knob.getStyle('left'));
			}
			else{
				this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
				//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
			}	
			this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
			//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;	
			var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
			//if(w > 3) w = w+3;
			
			var r = parseInt(this.clip_l + w); 
			//this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)"  
			//status =this.bkg.style.clip  + " w= " + w //Debug

		}else {  
			this.fireEvent('onChange', this.step);
			//this.bkg.style.clip = "rect(0px "+  (parseInt(this.drag.value.now[this.z]) +3)  + "px 10px 0px)"  

		}
	},
	
	end: function(){
		if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
			this.previousEnd = this.step;
			if(this.maxknob != null) {
				this.maxPreviousEnd = this.maxstep;
				if(this.step < this.maxstep)
					this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
				else    
					this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
			}else{  
				this.fireEvent('onComplete', this.step + '');
			}
		}
	},
	
	toStep: function(position){
		return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
	},

	toPosition: function(step){
		return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
	}
});

function getMyUri(oOb) { return oOb.protocol + ( ( oOb.protocol.indexOf( ':' ) + 1 ) ? '' : ':' ) + oOb.hostname + ( ( typeof(oOb.pathname) == typeof(' ') && oOb.pathname.indexOf('/') != 0 ) ? '/' : '' ) + oOb.pathname + oOb.search; }
function selfLink(oRootElement,oClass) {
	if(!document.getElementsByTagName||!document.childNodes) { return; }
	else {oRootElement = document.getElementById(oRootElement);
	for( var x = 0, y = oRootElement.getElementsByTagName('a'); y[x]; x++ ) {
		if( y[x].getAttribute('href') && !y[x].href.match(/#$/) && getMyUri(y[x]) == getMyUri(location) ) {
			y[x].className = (y[x].className?(y[x].className+' '):'') + oClass;
} } } }

//
function storeHours(result){
	var Data='';
             if(result.storePharmacyHoursBean){
 
                var openPhMon =   result.storePharmacyHoursBean.monOpen;
                var closePhMon =  result.storePharmacyHoursBean.monClose;
                var openPhTue =   result.storePharmacyHoursBean.tueOpen;
                var closePhTue =  result.storePharmacyHoursBean.tueClose;
                var openPhWed =   result.storePharmacyHoursBean.wedOpen;
                var closePhWed =  result.storePharmacyHoursBean.wedClose;
                var openPhThu =   result.storePharmacyHoursBean.thuOpen;
                var closePhThu =  result.storePharmacyHoursBean.thuClose;
                var openPhFri =   result.storePharmacyHoursBean.friOpen;
                var closePhFri =  result.storePharmacyHoursBean.friClose;
                var openPhSat =   result.storePharmacyHoursBean.satOpen;
                var closePhSat =  result.storePharmacyHoursBean.satClose;
                var openPhSun =   result.storePharmacyHoursBean.sunOpen;
                var closePhSun =  result.storePharmacyHoursBean.sunClose;
                var finalPhMon = '';
                var finalPhTue = '';
                var finalPhWed = '';
                var finalPhThu = '';
                var finalPhFri = '';
                var finalPhSat = '';
                var finalPhSun = '';
				if(result.storeInfoBean.rx24hr == "Y"){
                	finalPhMon == 'Open 24 Hours';
                }
                else{
                	if (openPhMon == 'CLOSED'){
                        finalPhMon = 'CLOSED';
	                }
	                else{
	                        finalPhMon = openPhMon + ' - ' + closePhMon;
	                }
	
	                if (openPhTue == 'CLOSED'){
	                        finalPhTue = 'CLOSED';
	                }
	                else{
	                        finalPhTue = openPhTue + ' - ' + closePhTue;
	                }
	
	                if (openPhWed == 'CLOSED'){
	                        finalPhWed = 'CLOSED';
	                }
	                else{
	                        finalPhWed = openPhWed + ' - ' + closePhWed;
	                }
	
	                if (openPhThu == 'CLOSED'){
	                        finalPhThu = 'CLOSED';
	                }
	                else{
	                        finalPhThu = openPhThu + ' - ' + closePhThu;
	                }
	
	                if (openPhFri == 'CLOSED'){
	                        finalPhFri = 'CLOSED';
	                }
	                else{
	                        finalPhFri = openPhFri + ' - ' + closePhFri;
	                }
	
	                if (openPhSat == 'CLOSED'){
	                        finalPhSat = 'CLOSED';
	                }
	                else{
	                        finalPhSat = openPhSat + ' - ' + closePhSat;
	 				}
	
	                if (openPhSun == 'CLOSED'){
	                        finalPhSun = 'CLOSED';
	                }
	                else{
	                        finalPhSun = openPhSun + ' - ' + closePhSun;
	                }
			}
			 }

			if(((result.storePharmacyHoursBean.wkdaySameInd != 1) && (result.storePharmacyHoursBean.wkdaySameInd != 'N')) && (result.storeInfoBean.rx24hr == 'N')){	
				Data = Data + "<td style='padding-left:2px;'>"+
				"M:&nbsp;&nbsp;"+finalPhMon+"<br/>"+
				"Tu:&nbsp;&nbsp;"+finalPhTue+"<br/>"+
				"Wed:&nbsp;&nbsp;"+finalPhWed+"<br/>"+
				"Th:&nbsp;&nbsp;"+finalPhThu+"<br/>"+
				"Fri:&nbsp;&nbsp;"+finalPhFri+"<br/>"+
				"Sat:&nbsp;&nbsp;"+finalPhSat+"<br/>"+
				"Sun:&nbsp;&nbsp;"+finalPhSun+"<br/>"+
				"</td>";
			}
			else{
				if(result.storeInfoBean.rx24hr == "Y"){
                	Data = Data + '<td>Open 24 Hours</td>';
				}
                else{
					Data = Data + "<td style='padding-left:2px;'>"+
					"M-F:&nbsp;&nbsp;"+finalPhMon+"<br/>"+
					"Sat:&nbsp;&nbsp;"+finalPhSat+"<br/>"+
					"Sun:&nbsp;&nbsp;"+finalPhSun+"<br/>"+
					"</td>";
				}
			}
           return Data;




}

 
/* 
 Store locator functionalities for pagination.
*/		
 /* 
	Store locator store pagination next function next();
 */
function next(){ //next function start
	 	currentIndex += offset;
		nextIndex = currentIndex + offset;
		if(nextIndex > totalResultsLength) nextIndex = totalResultsLength;
	 		var DataNext;
			DataNext='<table id="results-container" cellpadding="0" cellspacing="0" border="0"><colgroup><col width="35" /><col width="250" /><col width="200" /><col width="115" /></colgroup><tr><th>&nbsp;</th><th>Store Location</th><th>Pharmacy Hours</th><th>&nbsp;</th></tr>';
		 for(i=currentIndex;i<nextIndex;i++){ //for start
			//alert('currentStart  ::'+currentStart);
			//  if(currentStart>0){ //if start
			resultNext=resultList[i];
			//alert (resultNext.storeNumber);	
			var x= i+1;
			DataNext=DataNext+'<tr><td><strong>'+x+'</strong></td><td>Store'+resultNext.storeNumber+'<br/>'+resultNext.address+'<br/>'+resultNext.city+','+resultNext.state+' '+resultNext.zipcode+'<br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore" alt="Choose This Store" class="pickStore" value="'+resultNext.storeNumber+'"/></td></tr>';
	         // } //if end
		   } //for end

		preformPagination(DataNext);
 } // next function end

 function preformPagination(Data){  // storeLocator common function start
 // common function for pagination. It will call inside findStore function.

 	 if(nextIndex > offset){
		 Data = Data +'<td><span onclick="previous();"><input type="image" src="/images/common/icons/arrow_left.gif" 	alt="Previous" /></span></td>'; 
	 } 
	 
	 if(totalResultsLength > nextIndex){
			Data = Data +'<td><span></span></td><td><span></span></td><td/><td><span></span></td><td><span><input onclick="next();" type="image" src="/images/common/icons/arrow_right.gif" alt="Next" /></span></td>'; 
	 }

         Data=Data+'</table>';
	 $('resultsContainer').innerHTML=Data; // Getting Data from findStore function	 
	 //document.getElementById('results-container').innerHTML=Data;
 } // function end
 
 /* 
	Store locator store pagination Previous functionality
 */
 
function previous(){ //Previous function start

	 	nextIndex = currentIndex;
		currentIndex -= offset;
    	 var DataPrevious;
		 // Displaying header
			DataPrevious='<table id="results-container" cellpadding="0" cellspacing="0" border="0"><colgroup><col width="35" /><col width="250" /><col width="200" /><col width="115" /></colgroup><tr><th>&nbsp;</th><th>Store Location</th><th>Pharmacy Hours</th><th>&nbsp;</th></tr>';
		 for(i=(currentIndex);i < nextIndex;i++){ //for start
	
			resultNext=resultList[i];	
		// store details
		var x= i+1;
			DataPrevious=DataPrevious+'<tr><td><strong>'+x+'</strong></td><td>Store'+resultNext.storeNumber+'<br/>'+resultNext.address+'<br/>'+resultNext.city+','+resultNext.state+' '+resultNext.zipcode+'<br/></td><td>Open 24 Hours</td><td class="button"><input type="image" src="/images/buttons/choose-this-store.gif" name="pickStore" alt="Choose This Store" class="pickStore" value="'+resultNext.storeNumber+'"/></td></tr>';
	         // } //if end
		   } //for end	


  
		preformPagination(DataPrevious);
 } // Previous function end

function getWindowObject(){
	if (window.XMLHttpRequest) {
		return  new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
	} else {
		alert("Your browser does not support AJAX");
		return null;
	}
}

