// Site Class v0.1
var Pulse = new Class({
    options: {
        searchResultFormat: 0
    },
    initialize: function(options){
        this.setOptions(options);
    },
	begin: function(){
	    // Run our page default functions. 
        this.page_buildSearchMenu();
        this.page_buildCartItems();
        this.page_launchNotificationBubble();
        this.page_setRollOvers();
        $$('.searchText').each(function(el){if (el.getProperty('value')=='')el.setProperty('value','search the shop');});
        $$('.searchTextP').each(function(el){if (el.getProperty('value')=='')el.setProperty('value','search prescriptions');});
	},
	
	// Search Menu
	page_buildSearchMenu: function(){
        // This is the engine that drives the search list options. If the user makes a selection, we must 
        // re-order the list in the drop down and prepare our search form to use that option as it's search key
        if (undefined==window.searchKey)
            window.searchKey = 0;
        window.menuOrder = new Array(0,1); // Menu Order
        window.menuOptionsText = new Array('Shop','Prescriptions');
        window.dropDownOpen = false;
        window.togglerPosition = "down";
        // Initialize our rollovers
        $$('.searchDropDownMenu').each(function(el, i){
	        window.searchDropDownObject = new searchDropDownCreator($(el.id), i); // Create the drop downs
	        if (window.searchDropDownObject ==null) return; //Code added by Riz
	        window.setupSearchListOptions(i); // Add the uber slick background colour change for the search options
            var pl = new Pulse();
            pl.page_setupSearchBoxes(i);
        });
        
	},
	//Coded by Riz: sets up search boxes.
	page_setupSearchBoxes: function(myMenu)
	{
	    $$('#searchDropDownMenu_'+myMenu+' li').each(function(el, i){
	    // Who am i?
	    var id;
	    if ($('ctl00_ContentPlaceHolder1_searchheader_ctl00_hdnSearchType'))
			    id = $('ctl00_ContentPlaceHolder1_searchheader_ctl00_hdnSearchType').value;
        else 
            id = 0;
		if (id==0)
			{
			    $$('.searchText').each(function(el){
			    if ((getQueryString('Searches')=='') || (getQueryString('Searches')==null))
                    el.setProperty('value','search the shop');
                else
                    el.setProperty('value',unescape(getQueryString('Searches')));
                    
                    $$('.searchGo').each(function(el2)
	                {
	                    el2.removeClass('pres_go');
	                });

                    el.removeEvents('focus');
                    el.removeEvents('blur');
                    el.addEvent('focus',function(){
                        if($(el).getProperty('value') == 'search the shop') 
                            $(el).setProperty('value','');
                    });
                    el.addEvent('blur',function(){
                        if($(el).getProperty('value') == '') 
                            $(el).setProperty('value','search the shop');
                    });
		        });
                
                $$('.searchTextP').each(function(el){
   			    if ((getQueryString('Searches')=='') || (getQueryString('Searches')==null))
			        el.setProperty('value','search the shop');
                else
                    el.setProperty('value',unescape(getQueryString('Searches')));

                    $$('.searchGo').each(function(el2)
	                {
	                    el2.removeClass('pres_go');
	                });
                     el.removeEvents('focus');
                    el.removeEvents('blur');
                    el.addEvent('focus',function(){
                        if($(el).getProperty('value') == 'search the shop') 
                            $(el).setProperty('value','');
                    });
                    el.addEvent('blur',function(){
                        if($(el).getProperty('value') == '') 
                            $(el).setProperty('value','search the shop');
                    });
                });

			}
			else if (id==1)
			{
			    $$('.searchText').each(function(el){
   			    if ((getQueryString('Searches')=='') || (getQueryString('Searches')==null))
			            el.setProperty('value','search prescriptions');
                else
                    el.setProperty('value',unescape(getQueryString('Searches')));

			            $$('.searchGo').each(function(el2)
			                {
			                    el2.addClass('pres_go');
			                });
			            el.removeEvents('focus');
                        el.removeEvents('blur');
                        el.addEvent('focus',function(){
                            if($(el).getProperty('value') == 'search prescriptions') 
                                $(el).setProperty('value','');
                        });
                        el.addEvent('blur',function(){
                            if($(el).getProperty('value') == '') 
                                $(el).setProperty('value','search prescriptions');
                        });
			        });
                
                $$('.searchTextP').each(function(el){
   			    if ((getQueryString('Searches')=='') || (getQueryString('Searches')==null))
			        el.setProperty('value','search prescriptions');
                else
                    el.setProperty('value',unescape(getQueryString('Searches')));

		            $$('.searchGo').each(function(el2)
	                {
	                    el2.addClass('pres_go');
	                });
			        el.removeEvents('focus');
                    el.removeEvents('blur');
                    el.addEvent('focus',function(){
                        if($(el).getProperty('value') == 'search prescriptions') 
                            $(el).setProperty('value','');
                    });
                    el.addEvent('blur',function(){
                        if($(el).getProperty('value') == '') 
                            $(el).setProperty('value','search prescriptions');
                    });
                });
			}
		});
	},
	// For our shopping cart DIVS
	page_buildCartItems: function(){
		$$('.item').each(function(el, i){
			el.addEvent('mouseover',function(){
    		    $(el).setStyle('background-color','#EEF6FC');
			}).addEvent('mouseout',function(){
			    $(el).setStyle('background-color','#FFFFFF');
			});
		});
		$$('.presitem').each(function(el, i){
			el.addEvent('mouseover',function(){
			    $(el).addClass('pres_item_hover');
				$(el).setStyle('background-color','#eff8e4');
			}).addEvent('mouseout',function(){
			    $(el).removeClass('pres_item_hover');
			    $(el).setStyle('background-color','#FFFFFF');
			});
		});
		$$('.pres_cart_item').each(function(el, i){
			el.addEvent('mouseover',function(){
			    $(el).addClass('pres_item_hover');
				$(el).setStyle('background-color','#eff8e4');
			}).addEvent('mouseout',function(){
			    $(el).removeClass('pres_item_hover');
			    $(el).setStyle('background-color','#FFFFFF');
			});
		});
	},
	// Toggles the search result view (between rows & grids)
	page_toggleSearchView: function(){
	    if(this.options.searchResultFormat){
	        // Show in the default "row" view
	        this.options.searchResultFormat = 0;
	        //url = "/includes/ajax/search/gridview.html";
	        $('img_search_toggler').src = "/images/global/search_toggle_rows.gif";
	        $('search_results_ajax_holder').removeClass('search_grid_view');
	    }else{
	        // Show in the "grid" view
	        this.options.searchResultFormat = 1;
	        $('img_search_toggler').src = "/images/global/search_toggle_grid.gif";
	        $('search_results_ajax_holder').addClass('search_grid_view');
	        //url = "/includes/ajax/search/rowview.html";
	    }
	    LoginCheck.page_hideToolTip();
	    LoginCheck.login_close();
	    //loadAjaxURL('search_results_ajax_holder', url);
	},
	// Our notification bubble
	page_launchNotificationBubble: function(){
	    // For each DOM object with the class "alert", we must create an even which will launch our alert bubble on click.
	    $$('.alert').each(function(el, i){
	        el.addEvent('click', function(){
	            // We have an ever present 'global_Bubble' DIV which is hidden
	            $('global_BubbleInput').setHTML($(el).title);
	            $('global_Bubble').setStyles({opacity:1,display:'block'});
	            // Position it
	            var topAlignPosition = ($(el).getTop() - $('global_Bubble').getSize().size.y)-2;
	            var rightAlignPosition = ($(el).getLeft() + $(el).getSize().size.x+100) - ($('global_Bubble').getSize().size.x/2);
	            $('global_Bubble').setStyles({top:topAlignPosition+"px",left:rightAlignPosition+"px"});
	            //this.fx_FadeOutDiv('global_Bubble');
	        }.bind(this));
	        el.addEvent('focus', function(){
	            // We have an ever present 'global_Bubble' DIV which is hidden
	            $('global_BubbleInput').setHTML($(el).title);
	            $('global_Bubble').setStyles({opacity:1,display:'block'});
	            // Position it
	            var topAlignPosition = ($(el).getTop() - $('global_Bubble').getSize().size.y)-2;
	            var rightAlignPosition = ($(el).getLeft() + $(el).getSize().size.x+100) - ($('global_Bubble').getSize().size.x/2);
	            $('global_Bubble').setStyles({top:topAlignPosition+"px",left:rightAlignPosition+"px"});
	            //this.fx_FadeOutDiv('global_Bubble');
	        }.bind(this));
	   }.bind(this));
	},
	page_hideNotificationBubble: function(){
	    $('global_Bubble').setStyles({display:'none'});
	},
	page_ClearNotifications: function(){
		this.page_hideNotificationBubble();
	},
    // Display the tool top
    page_showToolTip: function(t)
    {
        if(t == "basket")
        {
            $('tooltip_button').setStyle('display','');
            $('tooltip_button').setProperty('src',"/images/global/but_viewcart.gif");
            $('tooltip_button').addEvent('mouseover',function(){
                this.setProperty('src',"/images/global/but_viewcart_on.gif");
            }).addEvent('mouseout',function(){
                this.setProperty('src',"/images/global/but_viewcart.gif");
            });
            //$('button_url').setProperty('href','/viewitems.aspx');
            $('button_url').setProperty('href','/checkout1.aspx');
        }
        else if (t=="instoreonly")
        {
            $('tooltip_button').setProperty('src',"/images/global/but_stores.gif");            
            $('tooltip_button').addEvent('mouseover',function(){
                this.setProperty('src',"/images/global/but_stores_on.gif");
            }).addEvent('mouseout',function(){
                this.setProperty('src',"/images/global/but_stores.gif");
            });
            $('button_url').setProperty('href','/storelocator.aspx?Store=');
        }
        else if (t=="message")
        {
            $('tooltip_button').setStyle('display','none');            
            $('button_url').setProperty('href','#');
        }
        else
        {
            $('tooltip_button').setProperty('src',"/images/global/addedtolist_butviewlist.gif");            
            $('button_url').setProperty('href','/viewlist.aspx');
        }
    
	    // show the div and reset its properties
	    $('toolTip').setStyles({opacity: 1, display: 'block', top: (window.triggerTop-100)+'px', left: (window.triggerLeft-150)+'px'});
	    
	    
	    
	    
	    // fade out the div
	    /*var fadeFx = new Fx.Style('toolTip', 'opacity', {
		    duration: 1000, 
		    transition: Fx.Transitions.Quart.easeInOut,
		    wait: false
	    });*/
	    //this.fx_FadeOutDiv('toolTip');
	    //fadeFx.start.pass([1,0], fadeFx).delay(3000);
	},
    page_hideToolTip: function(){
        $('toolTip').setStyle('display','none');
        $$('.toolTipContent').each(function(el){
            el.removeClass('authority_required');
            el.removeClass('multipack');
        });
    },
    page_setRollOvers:function(){
        // These are serverside controls (img buttons), controlled by .NET.. only way to access them easily is via javascript
        $$('.addedtoCartButView1').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/continue_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/continue.gif')});
        });
        $$('.checkout_print').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_print_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_print.gif')});
        });         

        $$('.but_subscribe').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/columns/but_subscribe_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/columns/but_subscribe.gif')});
        });        
        $$('.but_subscribecontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_subscribe_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_subscribe.gif')});
        }); 
        $$('.but_accountsubscribecontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_accountsubscribe_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_accountsubscribe.gif')});
        });
        $$('.but_accountunsubscribecontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_accountunsubscribe_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_accountunsubscribe.gif')});
        }); 
        $$('.but_delete').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_delete_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_delete.gif')});
        });
        $$('.but_nextcontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_next_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_next.gif')});
        });
        $$('.but_checkout').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_checkout_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_checkout.gif')});
        });
        
        $$('.but_place_your_order').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_place_your_order_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_place_your_order.gif')});
        });
        
        $$('.but_checkout2').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_checkout2_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_checkout2.gif')});
        });
        $$('.but_checkout_as_guest').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_checkout_as_guest_on.jpg')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_checkout_as_guest.jpg')});
        });
        $$('.but_checkout_as_member').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_checkout_as_member_on.jpg')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_checkout_as_member.jpg')});
        });
        $$('.but_create_new_account').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_create_new_account_on.jpg')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_create_new_account.jpg')});
        });
        $$('.checkout_steps_terms_top_continuecheck').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_continue_checkout_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_continue_checkout.gif')});
        });
        $$('.checkout_steps_bottom_continuecheck').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_continue_checkout_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_continue_checkout.gif')});
        });
        
        $$('.but_validationcode').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_validatecode_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_validatecode.gif')});
        });
        $$('.but_previouscontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_previous_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_previous.gif')});
        });
        $$('.but_login').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/login_butlogin_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/login_butlogin.gif')});
        });
        $$('.but_checkout_as_member').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_checkout_as_member.jpg')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_checkout_as_member.jpg')});
        });
        $$('.but_submit').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/popup_butsubmit_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/popup_butsubmit.gif')});
        });        
        $$('.but_editcontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_accountedit_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_accountedit.gif')});
        });  
        $$('.but_viewcontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_view_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_view.gif')});
        });
        $$('.but_vieweditcontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_view_edit_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_view_edit.gif')});
        });
        $$('.but_accountenterprofile').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_accountenterprofile_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_accountenterprofile.gif')});
        });
        $$('.but_joincontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_joinpulse_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_joinpulse.gif')});
        });
        $$('.but_sendmail').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/columns/but_sendmail_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/columns/but_sendmail.gif')});
        });
        $$('.but_compareSelected').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_compareselected_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_compareselected.gif')});
        });
        $$('.but_printpage').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_printpage_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_printpage.gif')});
        });
        $$('.but_signout').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_signout_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_signout.gif')});
        });
        $$('.but_saveprofilecontrol').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_saveprofile_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_saveprofile.gif')});
        });        
        $$('.but_continueshopping').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_continueshopping_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_continueshopping.gif')});
        });        
        $$('.but_continueshopping2').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/account/but_continueshopping2_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/account/but_continueshopping2.gif')});
        });  
        
        $$('.but_FindPrescriptions').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_findprescriptions_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_findprescriptions.gif')});
        });  
       $$('.but_RepeatPrescriptions').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_repeatprescriptions_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_repeatprescriptions.gif')});
        });  
        $$('.but_TalkToPharmacist').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_talkpharmacist_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_talkpharmacist.gif')});
        });  
        $$('.but_PrescriptionPrices').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_prescriptionprices_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_prescriptionprices.gif')});
        });  
        $$('.but_ViewBrands').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_viewaltbrands_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_viewaltbrands.gif')});
        }); 
        $$('.but_question').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_question_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_question.gif')});
        }); 
        $$('.but_InStore').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_availableinstore_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_availableinstore.gif')});
        });
        $$('.but_close').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_close_green_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_close_green.gif')});
        });
        $$('.but_green_moreinfo').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_moreinfo_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_moreinfo.gif')});
        });
        $$('.but_ReschReminder').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_resced_reminder_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_resced_reminder.gif')});
        });
        $$('.but_ReturnScript').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_return_script_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_return_script.gif')});
        });
        $$('.but_gotoAccount').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_go_to_account_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_go_to_account.gif')});
        });
        $$('.but_Cancel').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_cancel_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_cancel.gif')});
        });
        $$('.but_Save').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_save_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_save.gif')});
        });
        $$('.but_Confirm').each(function(el){
            el.addEvent('mouseover',function(){this.setProperty('src','/images/global/but_confirm_on.gif')});
            el.addEvent('mouseout',function(){this.setProperty('src','/images/global/but_confirm.gif')});
        });
    },
    // Build the add to basket interactivity
    page_buildAddToBasket: function(){


        $$('.chkRepeat').each(function(el){
            el.addEvent('click',function(){
                window.currentEl = el;
                var arr=el.className.split(" ");
                PulseWebSite.AjaxHandler.SetProductRepeat(arr[1].replace("pid",""),el.getProperty("checked"),this.SetProductRepeat_CallBack);
                return;
            }
            );
        }
        );
        $$('.lnk_Authority').each(function(el){
            el.addEvent('click',function(){
                Site.resetToolTip();
                window.currentEl = el;
                window.triggerTop = $(el).getTop()-110;
                window.triggerLeft = $(el).getLeft();
                $$('.toolTipContent').each(function(el){
                    el.removeClass('multipack');
                    el.addClass('authority_required');
                });
                $('toolTipText').setHTML("This item requires an Authority Prescription approved by the Government to qualify for the NHS subsidised prices. If you do not have an Authority Prescription, please select the 'Private' price. If you are unsure, please contact us for clarification.<br/>");
                Site.page_showToolTip('message');
                return;
            }
            );
        }
        );
        $$('.but_question').each(function(el){
            el.addEvent('click',function(){
                Site.resetToolTip();
                window.currentEl = el;
                window.triggerTop = $(el).getTop();
                window.triggerLeft = $(el).getLeft()-80;
                $('toolTipText').setHTML('Generic brands are less expensive versions of common medicines.<br/>');
                Site.page_showToolTip('message');
                return;
            }
            );
        }
        );
        $$('.but_InStore').each(function(el){
            el.addEvent('click',function(){
                Site.resetToolTip();
                window.currentEl = el;
                window.triggerTop = $(el).getTop();
                window.triggerLeft = $(el).getLeft();
                $('toolTipText').setHTML('This product is available in store only.<br/>');
                Site.page_showToolTip('instoreonly');
                return;
            }
            );
        }
        );
        $$('.but_addToBasket').each(function(el){
            el.addEvent('click',function(){
                Site.resetToolTip();
                this.options.triggerDiv = el.className.split(" ");
		        this.options.triggerRF = this.options.triggerDiv[1];
                window.currentProductID = this.options.triggerDiv[1].replace('pid','');
                window.currentEl = el;
                window.isPrescription = false;
                window.multiPack = false;
                window.triggerTop = $(el).getTop();
                window.triggerLeft = $(el).getLeft();
                if (this.options.triggerDiv.length>=4)
                {
                    if (this.options.triggerDiv[3]=="pres")
                    {
                        window.isPrescription = true;
                    }
                }
                if (this.options.triggerDiv.length>=5)
                {
                    if (this.options.triggerDiv[4]=="multi")
                    {
                        window.multiPack = true;
                    }
                }
                $$('.PriceHandler' + window.currentProductID).each(function(el2){
                    var tmpArr = el2.className.split(" ");
                    if (el2.lastChild.checked)
                    {
                        window.priceType=tmpArr[0];
                    }
                }
                );
                
                if (window.isPrescription==true)
                {
                    if (window.priceType==undefined)
                    {
                        $('toolTipText').setHTML('Please select a price type first.<br/>');
                        Site.page_showToolTip('message');
                        return;
                    }
                }
                
                window.currentVariationID = 0;
                
                $$('.ddlVariation' + window.currentProductID + this.options.triggerDiv[2]).each(function (el){
                    window.currentVariationID = el.options[el.selectedIndex].value;
                });
                    
                
                window.currentQuantity = 1;
                
                $$('.ddlQuantity' + window.currentProductID + this.options.triggerDiv[2]).each(function (el){
                    window.currentQuantity = el.options[el.selectedIndex].value;
                });

             

                this.page_addToBasket()
	        }.bind(this));
	        el.addEvent('mouseover',function(){
	        
	            if (this.getProperty('src') == '/images/global/but_preorder.gif')
	            {
    	            this.setProperty('src','/images/global/but_preorder.gif');
	            }
                else if (this.getProperty('src') == '/images/global/but_green_addtobasket.gif')
	            {
    	            this.setProperty('src','/images/global/but_addtobasket_green_on.gif');
	            }
	            else if (this.getProperty('src') == '/images/global/but_add_to_cart.gif')
	            {
    	            this.setProperty('src','/images/global/but_add_to_cart_on.gif');
	            }
	            else
	            {
    	            this.setProperty('src','/images/global/but_addtocart_on.gif');
	            }
	            
	        }).addEvent('mouseout',function(){

	            if (this.getProperty('src') == '/images/global/but_preorder.gif')
	            {
    	            this.setProperty('src','/images/global/but_preorder.gif');
	            }
	            else if (this.getProperty('src') == '/images/global/but_addtobasket_green_on.gif')
	            {
    	            this.setProperty('src','/images/global/but_green_addtobasket.gif');
	            }
	            else if (this.getProperty('src') == '/images/global/but_add_to_cart_on.gif')
	            {
    	            this.setProperty('src','/images/global/but_add_to_cart.gif');
	            }
	            else
	            {
    	            this.setProperty('src','/images/global/but_addtocart.gif');
	            }

//	            this.setProperty('src','/images/global/but_addtobasket.gif');
	        });
	    }.bind(this));
    },
    resetToolTip: function(){
            $$('.toolTipContent').each(function(el){
            el.removeClass('authority_required');
            el.removeClass('multipack');
        });
    },
	page_addToBasket: function(){

	    // do ajax here...
	    
	    if (window.isPrescription==true)
            PulseWebSite.AjaxHandler.AddToBasket(window.currentProductID,window.currentQuantity,window.currentVariationID,window.priceType,true,this.AddToBasket_CallBack);
	    else	    
    	    PulseWebSite.AjaxHandler.AddToBasket(window.currentProductID,window.currentQuantity,window.currentVariationID,"private",false,this.AddToBasket_CallBack);
	    
	},
    
    SetProductRepeat_CallBack: function(result){
        
        var success; // returned from our ajax function
        var results = result.split(":");
        if (results[0]=="success")
            success = true;
        else
            success = false;
	    return success;   
    },
    AddToBasket_CallBack: function(result){
        Site.resetToolTip();
        var success; // returned from our ajax function
        var results = result.split(":");
        if (results[0]=="success")
            success = true;
        else
            success = false;
            
	    if(success){// success
	        //$$(".viewCartItemCount").setText(parseInt($$(".viewCartItemCount").getText())+1); // update the item count in header
	        $$(".viewCartItemCount").setText(parseInt(results[1])); // update the item count in header
	        Omniture_AddToBasket(window.currentProductID);
	       if (!window.multiPack){
	        $('toolTipText').setHTML('You have successfully added this product to your shopping cart');
	       }
	       else {
	               $$('.toolTipContent').each(function(el){
                        el.removeClass('authority_required');
                        el.addClass('multipack');
                    });
                window.triggerTop = window.triggerTop-160;
                window.triggerLeft = window.triggerLeft-40;
    	        $('toolTipText').setHTML("Multiple quantity product: This item can only be dispensed if your doctor has written your prescription for the specified quantity or endorsed your prescription with 'Regulation 24'. If you order this item without the correct prescription for it, we will dispense the quantity specified on your prescription and refund you the difference. If you are unsure, please contact us for clarification.");
	       }
	       if ($('updViewBasketName') !=null)
	       {
	        $($('updViewBasketName').value).click();
	       }
	    }else{// failure
	       if (results[0]=="over")
	            $('toolTipText').setHTML('Note: You can enter a maximum of ' + results[1] + ' items of this type.');
	        else if (results[0]=="pseudo")
	            $('toolTipText').setHTML('Due to company policy Pulse can only supply ' + results[1] + ' product with pseudoephedrine per order.');
	        else
	            $('toolTipText').setHTML('There was a processing error.');
	    }
	    // return success or failure
        // Display popup
        Site.page_showToolTip('basket'); //This is changed as requested by Luke
	    window.priceType=undefined;
	    return success;   
    },
	
	// Effects
	fx_FadeOutDiv: function(el){
	    try{
	        window.myFx.stop();
	    }catch(e){
	    }
        var myElement = $(el);
        var to = 0;
        window.myFx = myElement.effect('opacity', {
                duration: 1000,
                onCancel: function(){
                    //$(el).setStyle('display','none');
                }
        });
        (function(){ window.myFx.start(to) }).delay(1000);
    }    
    
});
Pulse.implement(new Options, new Events);
Site = new Pulse({
    //launchRequired: 0 // this variable will allow us to trigger page specific functions & operations
});




/*
var PulseCart = Pulse.extend({
    options: {
        checkoutStep: 0,
        maxNumSteps: 4
    },
    initialize: function(options){
        this.setOptions(options);
    },
	begin: function(){
        this.checkout_Next();
	},
	// Shopping Cart Functions
	cart_deleteMe: function(i){
		// now update the cart via ajax / total items / etc
		$("viewCartItemCount").innerHTML--;
		Site.page_ClearNotifications(); // Clear popups and other
		$('item'+i).remove(); // Delete the element
		this.cart_updateTotalCost();
	},
	// Changes the quanity requested by the user and adjusts the totals
	cart_changeQuantity: function(el){
        this.cart_updateTotalCost();
	},
	// Evaluates and returns it's price / quantity & total cost
	cart_getMyPrice: function(i){
	    return $("price"+i).innerHTML.substring(1,$("price"+i).innerHTML.length); // removes "$" & returns price
	},
	cart_getMyQuantity: function(i){
	    return $("qty"+i).getValue(); // returns item quantity
	},
	cart_getCurrentTotalCost: function(){
	    return $("viewCartTotalCost").innerHTML.substring(1,$("viewCartTotalCost").innerHTML.length); // removes "$" & returns total
	},
    cart_updateTotalCost: function(){
        // Cycle through all items currently on page and multiply their cost by their quantity, then add to the totalcost and show total.
        var totalCost = 0;
        $$('.item').each(function(el){
            var id = $(el).id.split("item"); // "removes 'cart' from the front and returns our item num (item1, item5132)
            totalCost += Cart.cart_getMyPrice(id[1]) * Cart.cart_getMyQuantity(id[1]);
        });
        $("viewCartTotalCost").setHTML("$"+formatAsMoney(totalCost));
    },
    
    // For the checkout process
    checkout_Next: function(){
        if(this.options.checkoutStep < this.options.maxNumSteps){
            this.options.checkoutStep++;
            // When the user clicks next, we load in the next step via ajax (includes/ajax/checkout/stepX.html)
            var url = "/includes/ajax/checkout/step"+this.options.checkoutStep+".html";
            loadAjaxURL('checkout_AjaxHolder', url);
            // Now show / hide the relative buttons
            this.checkout_changeStatus();
        }
    },
    checkout_Previous: function(){
        if(this.options.checkoutStep > 1){
            this.options.checkoutStep--;
            // When the user clicks previous, we load in the previous step via ajax (includes/ajax/checkout/stepX.html)
            var url = "/includes/ajax/checkout/step"+this.options.checkoutStep+".html";
            loadAjaxURL('checkout_AjaxHolder', url);
            // Now show / hide the relative buttons
            this.checkout_changeStatus();
        }
    },
    checkout_Purchase: function(){
        // Do fancy AJAX purchasing
            // loadAjaxURL('', ajaxURL);
        // Now advance a step
        this.options.checkoutStep++;
        var url = "/includes/ajax/checkout/step"+this.options.checkoutStep+".html";
        loadAjaxURL('checkout_AjaxHolder', url);
        // Now show / hide the relative buttons
        $('but_continueShopping').setStyle('display','block');
        $('but_signOut').setStyle('display','block');
        $('but_previous').setStyle('display','none');
        $('but_purchase').setStyle('display','none');
        this.checkout_changeStatus();
    },
    checkout_changeStatus: function(){
        $$('.checkout_status_on').each(function(el){
            $(el).removeClass('checkout_status_on').setStyle('color','#C6C8C7');
        });
        $('checkout_status_step'+this.options.checkoutStep).addClass('checkout_status_on').setStyle('color','#000');
    }
});
PulseCart.implement(new Options, new Events);
Cart = new PulseCart();
*/


var PulseLoginCheck = Pulse.extend({
    options: {
        open: 0,
        triggerDiv: null,
        triggerRF: null,
        openDiv: null
    },
    initialize: function(options){
        this.setOptions(options);
    },
	begin: function(){
	    this.page_starRating();
	    this.login_buildLoginRequiredPopup();
	},
    login_buildLoginRequiredPopup: function(){
	    $$('.chkLogin').each(function(el){
		    el.addEvent('click',function(){ // Once clicked.
		        this.login_checkUser(el);
		    }.bind(this));
	    }.bind(this));
    },
    
    // Check to see if the user is logged in, then run a return function as required
    login_checkUser: function(el){
	    // First, determine which dialog we want to load if they've logged in by stripping our class
		this.options.triggerDiv = el.className.split(" ");
		myReturnFunction = this.options.triggerDiv[2];
		this.options.triggerRF = this.options.triggerDiv[1];
		window.currentReturnFunction = this.options.triggerDiv[2];
        window.currentProductID = this.options.triggerDiv[1].replace('pid','');
        window.currentEl = el;
        
        // Sets the position of our triggerDiv
		window.triggerTop = $(el).getTop();
		window.triggerLeft = $(el).getLeft();
        
        if ((getSubCookie("ckLoginInfo","LoggedIn")=="true") || getSubCookie("ckLoginInfo","LoggedIn")=="True"){
			// Calls the return function
			this.login_executeReturnFunction();
        }else{
            // Show Login
		    //if(!this.options.open){
		        this.page_hideToolTip();
			    $('loginPopup').setStyle('display','block');
			    this.options.openDiv = 'loginPopup';
			    var topPos = ((parseInt(window.getHeight())/2)-110)+parseInt(window.getScrollTop());
			    $('loginPopup').setStyle('top',topPos+"px"); // 110 is half the size of loginpopup
			    $('loginPopup').setStyle('left',330+"px");
                // Close others
			    //if($chk($('addedtoList'))) $('addedtoList').setStyle('display','none');
			    // Dont allow any other popups to occur
			    this.options.open = true;
		    //}
        }
        
	},
	
	login_showError:function (msg){
	    $('loginError').setHTML(msg);
	    $('loginError').setStyle('display','block');
	},
	
	// Processes the user login data
	login_Process: function(){
	    var eml = $('loginEmailAddress').value;
	    var pwd = $('loginPassword').value;
	    
	    // AJAX FUNCTION GOES HERE
		if (eml == ''){
		    this.login_showError('Please enter an email address');
		    return false;
		}else{
		    if(!this.regTest(eml, "val_eml")){
                this.login_showError('Please enter a valid email address');
		        return false;
		    }
		}
        
		if (pwd == ''){
            this.login_showError('Please enter your password');
		    return false;
		}else{
		   /* if(!this.regTest(pwd, "val_txt")){
		        this.login_showError('Please enter your password');
		        return false;
		    }*/
		}
		
		PulseWebSite.AjaxHandler.Login($('loginEmailAddress').value,$get('loginPassword').value,this.login_CallBack);
	},
	
	login_CallBack: function(result){
	    if (result=="success"){
	        setSubCookie("ckLoginInfo","LoggedIn",true);
	        //alert ('You have successfully logged in');
	        Omniture_Login();
	        LoginCheck.showLoginComponents();
			LoginCheck.login_executeReturnFunction();
	        //LoginCheck.login_close();
	    }
	    else{
	        setSubCookie("ckLoginInfo","LoggedIn",false);
	        LoginCheck.login_showError('Following error occurred while trying to login, please try again:<br>' + result);
	    }
	},
	
	login_executeReturnFunction: function(){
		// Show our dialog
		// This is one of the returned functions to run according to what we want our login box to do
		switch (window.currentReturnFunction) {
			// product added to list
			case "t1":
                PulseWebSite.AjaxHandler.AddToList(window.currentProductID,this.addToList_CallBack);
				break;
			// Write a review popup
			case "t2":
				this.login_close();
				// Show review popup
				var topPos = ((parseInt(window.getHeight())/2)-110)+parseInt(window.getScrollTop());
				$('reviewPopup').setStyles({top:topPos,left:300,display:'block'});
				this.options.open = true;
				this.options.openDiv = 'reviewPopup';
				window.triggerTop = parseInt($(window.currentEl).getTop())-100;
				window.triggerLeft = $(window.currentEl).getLeft();
                $get('reviewPopupTitle').innerHTML = $get('pName' + window.currentProductID).value;
				break;
			case "t3":
				break;
			default:
				this.login_close();
		}
	},
	
	addToList_CallBack:function(result){
        LoginCheck.login_close();
		$('toolTipText').setHTML('This product is now added to your list');
		Site.page_showToolTip();
	},
	
	// Close the loging popup
	login_close: function(){
	    if(this.options.open){
		    this.options.open = false;
		    $(this.options.openDiv).setStyle('display','none');
		    this.options.openDiv = null;
		}
	},
	// Submit the user's review
	login_submitReview: function(){
        // Submits the users review
        // ajax ....
        if (parseInt($get('currentRating').value)<=0)
        {
            alert ('Please rate this product before you submit');
            return false;
        }
        if (($get('review').value==''))
        {
            alert ('Please write a review for this product before you submit');
            return false;
        }
        if (($get('review').length>1000))
        {
            alert ('Review cannot be greater than 1000 characters');
            return false;
        }
        PulseWebSite.AjaxHandler.WriteAReview($get('currentRating').value,$get('review').value,window.currentProductID,this.review_CallBack);
        // now close
        //this.login_close();
	},
	review_CallBack:function(result){
	    if (result=="success")
	    {
	    Omniture_ProductReview(window.currentProductID);
        // now close
        LoginCheck.login_close();
	    }
	    else
	    {
	        alert ("An error occurred while trying to submit the review:\n" + result);
	        return false;
	    }
	},
	// Star rating interactivity
	page_starRating: function(){
	    $$('#ratingStarContainer .ratingStar').each(function(el, i){
		    el.addEvent('mouseover',function(){
			    this.starRating_setStarRating(i+1);
		    }.bind(this));
		    el.addEvent('click',function(){
			    // run our ajax call to set our STAR rating in stone
		
		    }.bind(this));
	    }.bind(this));
    },
    starRating_setStarRating: function(i){
	    // Loop through all the stars up until the star we are over and turn them on
	    $$('#ratingStarContainer .ratingStar').each(function(el, i){
		    el.src = '/images/global/star-empty.gif';
	    });
	    $get('currentRating').value = i;
	    for(j=1;j<=i;j++){
		    $('ratingStarContainer').getElements('img')[j-1].src = '/images/global/star-full.gif';
	    }
    },
    
    showLoginComponents:function(){
        PulseWebSite.AjaxHandler.IsLoggedIn(this.isLogin_CallBack)
    },
    
    isLogin_CallBack:function(result)
    {
            $$('.loginVisible').each(function(el){
            if (result==true){
                el.setStyle('display','block');
            }
            else{
                el.setStyle('display','none');
            }
        });
        
        $$('.logoutVisible').each(function(el){
            if (result==true){
                el.setStyle('display','none');
            }
            else{
                el.setStyle('display','block');
            }
        });

    },
    
    regTest:function(v, type){
        min = 1;
        switch(type){
            // Text
            case "val_txt":
                if(v.length < min) return false;
                return /^[a-zA-Z]+$/.test(v);
                break;
            // Email
            case "val_eml":
                return /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
                break;
            // Amount
            case "val_num":
                if(v.length < min) return false;
                if(v > 0){
                    return /([0-9])(\.\d{1,2})/.test(v);
                }
                break;
        }
    
    }
});
PulseLoginCheck.implement(new Options, new Events);
LoginCheck = new PulseLoginCheck();


window.onDomReady(function(){
    // We will try and install ONE onDomReady function only...
    Site.begin();
    LoginCheck.page_buildAddToBasket();
    LoginCheck.begin();
    LoginCheck.showLoginComponents();
    // --- from checkout.js
    if($chk($('checkout_giftYes'))){
		if($('checkout_giftYes').checked) showHideDiv('checkout_giftDetails',1);
	}
	// ---
});