﻿///<reference path="jquery-1.3.2.js" />


$(function() {

    //startup function on EVERY page	

    initializeMenu();

    $("#btnBrowseByCategory").click(btnBrowseByCategory_Click);

    $("#pnlApplyNow a").click(lnkApplyNow_Click);

    $("#TwoColumnTemplate .LeftColumn a:contains('Point Balance')").click(lnkPointsBalance_Click);
    $("#TwoColumnTemplate .LeftColumn a:contains('Solde de points')").click(lnkPointsBalance_Click);

    $("#MenuContainer a").hover(menuItemOver, menuItemOut);



    //startup on the promo image rotator on the brand details page...
    initializeBrandDetails();


    //initialize any badge rotators..
    $(".BadgeRotator").each(function() {
        initializeBadgeRotator($(this));
    });

    //fadeout any error messages after 5 seconds
    setTimeout(function() {
        $("div.FadingError").slideUp("normal");
    }, 5000);


    //do the hover for the highlight links
    $(".HighlightLink a").hover(
		function() {
		    $("span", this).removeClass("Normal");
		},
		function() {
		    $("span", this).addClass("Normal");
		}
	);

    //do the hover for the badge footer links
    $(".Badge a").hover(
		function() {
		    $("span", this).removeClass("Normal");
		},
		function() {
		    $("span", this).addClass("Normal");
		}
	);


    //hookup the search
    $('#murale-search-button').click(function() {
        var q = $('#murale-search').val();

        window.location = window.baseUrl + "SearchResults.aspx?q=" + q;
        return false;
    });


    $('#murale-search').bind('keyup', function(e) {

        if (e.keyCode == 13) {

            var q = $('#murale-search').val();
            window.location = window.baseUrl + "SearchResults.aspx?q=" + q;
        }

        return false;
    });
});

  
function ResolveUrl(url) {
	//resolves a url with ~/
	//relies on the baseUrl variable set in the Global.master.
	if (url.indexOf("~/") == 0) {
		url = baseUrl + url.substring(2);
	}
	return url;
}


function initializeMenu() {
	//initialize the menu hover states
	//take off the ~/en-ca/
	var startingUrl = appRelativeCurrentExecutionFilePath.substring(("~/en-ca/").length).toLowerCase();
	if (startingUrl.indexOf("/") != -1 && startingUrl.indexOf("/") < startingUrl.indexOf(".aspx")) {
		startingUrl = startingUrl.substring(0, startingUrl.indexOf("/"));		
	} else if (startingUrl.indexOf(".aspx") != -1) {
		startingUrl = startingUrl.substring(0, startingUrl.indexOf(".aspx"));
	}
	var miElem = $("#mi" + startingUrl);
	if (miElem.size() > 0) {
		var className = miElem.attr("className");
		if (className.indexOf("-sel") == -1) {
			miElem.attr("className", className + "-sel")		
		}	
	}
}

var viewTheStore_sequencePlayer = null;

function viewTheStore_Init() {

  
        if (viewTheStore_sequencePlayer == null) {

            var properties = {
                photoHeight: 110,
                photoWidth: 186,
                rotationSpeed: 2500,
                sequenceList: viewTheStore_SequenceList
            };

            viewTheStore_sequencePlayer = new SequencePlayer('.SequencePlayer', properties);
        }
        
        $("#ViewTheStore").show();
        $(".Navigator").bind("click", null, function() { return false; });
}

function lnkApplyNow_Click() {
	var url = $(this).attr("href");	
	openMuralePopupWindow(url, 650, 730);	
	return false;
}

function lnkPointsBalance_Click() {
	var url = $(this).attr("href");	
	openMuralePopupWindow(url, 650, 730);	
	return false;
}


function NewsletterSignup() {
	btnNewLetterSignup_Click();
}

function btnNewLetterSignup_Click() 
{	
	var url = "https://www.formdesk.com/shoppersdrugmart/murale_optin";
	if (languageCode == "fr-ca") {
		url = "https://www.formdesk.com/shoppersdrugmart/murale_fr_optin";
	}
		
	url += "?nobutton";
	openMuralePopupWindow(url, 625, 500);
	
	return false;
}

function openMuralePopupWindow(url, w, h, showMenuBar) {
	
	var winHeight = window.screen.height;
	var winWidth = window.screen.width;
	var top = (winHeight / 2) - (h / 2);
	var left = (winWidth / 2) - (w / 2);
	
	if (winHeight < h) {
		h = winHeight;
		top = 0;
	}
	
	var menuBar = "0";
	if (showMenuBar != undefined && showMenuBar == true) {
		menuBar = "1";
	}
	
	try {	
		var options = "height=" + h + ", width=" + w + ", left="+left+", top="+top+" location=0, menubar="+menuBar+", status=0, toolbar=0, scrollbars=1";
	
		var win = window.open(url, "_blank", options);		
	} catch (Error) {
		alert("The popup window could not be shown.  Please enable popup windows on this site.");
	}
	try {
		//win.moveTo(left, top);
	} catch (Error) {
		
	}
	
	
	
}


function btnBrowseByCategory_Click() 
{

	var className = $("#btnBrowseByCategory").attr("className");
	className = className.replace("Unselected", "Selected");
	
	$("#btnBrowseByCategory").attr("className", className);
	
		
	showCategoryPopup();
		
}


function hideCategoryPopup() {
	$("#CategoryPopup").slideUp("fast", function() {
		
		
		var className = $("#btnBrowseByCategory").attr("className");
		className = className.replace("Selected", "Unselected");
	
		$("#btnBrowseByCategory").attr("className", className);
	
		$(document).unbind("click", hideCategoryPopup);
	});
	
}

function showCategoryPopup() {
	
	var pos = $("#btnBrowseByCategory").position();	
	var width1 = $("#btnBrowseByCategory").width();	
	var width2 = $("#CategoryPopup").width();	
	var offset = width2 - width1 - 3;
		
	$("#CategoryPopup").css("top", (pos.top + 22) + "px");	
	$("#CategoryPopup").css("left", (pos.left - offset) + "px");
	
	
	$("#CategoryPopup").slideDown("fast", function() {	
		$(document).bind("click", hideCategoryPopup);
	});			
}



function menuItemOver(e) {

	var className = $(this).attr("className");
		
	$(this).attr("origClassName", className)
	
	if (className.indexOf("-sel") == -1) {

		$(this).attr("className", className + "-sel")		
	}	
		
}


function menuItemOut(e) {
	var className = $(this).attr("origClassName");
	 $(this).attr("className", className);
}


/* BRAND DETAILS */

var isRotating = false;

function initializeBrandDetails() {

	if ($("#pnlFeatureBoxItems .BrandPromo").size() > 1) {
		//set up the promo rotator	
		$("#pnlFeatureBoxItems").data("rotatorIndex", 0);

		$("#pnlFeatureBoxItems .LeftArrow").click(function() { isRotating = false; rotateBrandDetailsPromo(1); });
		$("#pnlFeatureBoxItems .RightArrow").click(function() { isRotating = false; rotateBrandDetailsPromo(-1); });

		var timeoutVar = setTimeout(function() { isRotating = true; rotateBrandDetailsPromo(1); }, imageRotationSpeedSeconds * 1000);
		
		$("#pnlFeatureBoxItems").data("timeoutVar", timeoutVar);
		$("#pnlFeatureBoxItems").hover(

			function() {
			    //over 
			    isRotating = false;
			    //cancel rotation...
			    var toVar = $("#pnlFeatureBoxItems").data("timeoutVar");
			    if (toVar != -1) clearTimeout(toVar);
			    $("#pnlFeatureBoxItems").data("timeoutVar", -1);

			    //show the arrow
			    $("#pnlFeatureBoxItems .LeftArrow").show();
			    $("#pnlFeatureBoxItems .RightArrow").show();


			}, function() {
			//out - restart the rotation
			    
			    isRotating = true;
			    if ($("#pnlFeatureBoxItems").data("timeoutVar") == -1) {
			        var timeoutVar = setTimeout(function() { rotateBrandDetailsPromo(1); }, imageRotationSpeedSeconds * 1000);
			        $("#pnlFeatureBoxItems").data("timeoutVar", timeoutVar);
			    }

			    //hide the arrows
			    $("#pnlFeatureBoxItems .LeftArrow").hide();
			    $("#pnlFeatureBoxItems .RightArrow").hide();

			});
		} else {
			//set up the initial item if it is video...
			if ($("#pnlBrandPromo_0 .pnlVideo").size() > 0) {
			    rotateBrandDetailsPromo(1);
			    isRotating = false;
			}
		}



}

var thePlayer = null;
var playerState = "";

function rotateBrandDetailsPromo(plusMinus) {

    if ((thePlayer != null) && (isRotating) && ((playerState == "PLAYING") || (playerState == "BUFFERING"))) {
        
        // do nothing, video is playing or buffering.
    } else {

        thePlayer = null;
        playerState = "";
        
	    $("#pnlFeatureBoxItems").data("timeoutVar", -1);
    	
	    if (isNaN(plusMinus) || plusMinus < 1) plusMinus = 1;

	    var index = $("#pnlFeatureBoxItems").data("rotatorIndex");
    	
	    var size = $("#pnlFeatureBoxItems .BrandPromo").size();
    	
	    if (isNaN(index)) index = 0;
    	
	    var nextIndex = index + plusMinus;	
	    if (nextIndex > size - 1) nextIndex = 0;

	    //check for image or video
	    var pnlVideo = $("#pnlBrandPromo_" + nextIndex + " .pnlVideo");

	    if (pnlVideo.size() == 0) {
    	
		    //*********** IMAGE **************/
    	
    		
		    //preload the next image if we have to...
		    var src2 = $("#pnlBrandPromo_" + nextIndex + " img").attr("src2");	

		    var img = new Image();

		    $(img).load(function() {

		        //set the src of the next image...
		        $("#pnlBrandPromo_" + nextIndex + " img").attr("src", src2);

		        //hide the rotator at this index...
		        $("#pnlBrandPromo_" + index).fadeOut("normal", function() {

		            //show the rotator at the next index (loop)		
		            index = nextIndex;


		            $("#pnlFeatureBoxItems").data("rotatorIndex", index);

		            $("#pnlBrandPromo_" + index).fadeIn("normal", function() {
		                if (isRotating == true) {
		                    var timeoutVar = setTimeout(function() { rotateBrandDetailsPromo(1); }, imageRotationSpeedSeconds * 1000);
		                    $("#pnlFeatureBoxItems").data("timeoutVar", timeoutVar);
		                }
		            });
		        });

		    }).attr("src", src2);
    	 
    	
    	
    	
	    } else {

    		
    		
		    //*********** VIDEO **************/
    	    
	        var flvUrl = pnlVideo.attr("url");

	        var flashvars = {
                autostart: "false",
                file: flvUrl
            };
            var params = {
                wmode: "transparent",
                allowfullscreen: "true"
            };
            var attributes = {
                id: "videoPlayer_" + nextIndex
            };
            
            var swfUrl = ResolveUrl("~/swf/player.swf");
            var expressInstallUrl = ResolveUrl("~/swf/expressInstall.swf");
            
            
            
            var expressInstallRequiredVersion = "6.0.65";
            var versionStr = "9.0.0";
            if (swfobject.hasFlashPlayerVersion(expressInstallRequiredVersion)) {
			    pnlVideo.html("<div id='pnlVideo_" + nextIndex + "'></div>");
            
                swfobject.embedSWF(swfUrl, "pnlVideo_" + nextIndex, "615", "305", versionStr, "/swf/expressInstall.swf", flashvars, params, attributes);
            } else {
                pnlVideo.html("<div style='height: 305px; width: 615px; text-align: center;'>This content requires <a href='http://get.adobe.com/flashplayer/' target='_blank'>Flash</a>.</div>");
            }
            
		    //hide the rotator at this index...
            $("#pnlBrandPromo_" + index).fadeOut("normal", function() {

                //show the rotator at the next index (loop)		
                index = nextIndex;

                $("#pnlFeatureBoxItems").data("rotatorIndex", index);

                $("#pnlBrandPromo_" + index).fadeIn("normal", function() {
                    if (isRotating == true) {
                        var timeoutVar = setTimeout(function() { rotateBrandDetailsPromo(1); }, imageRotationSpeedSeconds * 1000);
                        $("#pnlFeatureBoxItems").data("timeoutVar", timeoutVar);
                    }
                });
            });
	    }
	}	
}


///GENERIC IFRAME DIALOG FUNCTIONS
function showIFrameDialog(url, height, width) {
	url = ResolveUrl(url);	
	$("#" + reusableDialogID).Show({iframeUrl:url, height:height, width:width, y:150});
}

function hideIFrameDialog() {
	setTimeout(function() {
	$("#" + reusableDialogID).Hide();
	}, 0);
}


function showAskAQuestionDialog(expertID) 
{	
	showIFrameDialog("~/OurExperts/AskAnExpert.aspx?expertID=" + expertID, 473, 462);
}



function blogArchiveChange(select) {
	var url = ResolveUrl("~/OurExperts.aspx");
	if (select.selectedIndex > 0) 
	{	
		url += select.options[select.selectedIndex].value;		
	}
	location.href = url;
}


function printBlogItem(blogID) {	
	var url = ResolveUrl("~/Dialogs/PrintBlogItem.aspx?BlogID=" + blogID);
	
	openMuralePopupWindow(url, 660, 500, true);
	
	return false;
	
	
}


/*
MAPS FUNCTIONS
*/
function InitializeRegionMap(RegionName, MappingAddress) {
	
	
	 if (GBrowserIsCompatible()) {
		var address = MappingAddress; 
		var geocoder = new GClientGeocoder();
		var map = new GMap2(document.getElementById("map_canvas"));
		regionMap = map;
		map.enableScrollWheelZoom();	
		var gsc = new GLargeMapControl3D();
		map.addControl(gsc);


		geocoder.getLatLng(
		  address,
		  function(point) {
			if (!point) {
				//TODO: figure out what to do here...
			} else {

				map.setCenter(point, 10);


				//add the markers for the stores
				for (var i = 0; i < stores.length; i++) {
					var store = stores[i];

					if (store.Latitude != '' && store.Longitude != '') {

						var storePoint = new GLatLng(store.Latitude, store.Longitude);
						createStoreMarker(map, storePoint, store);

					}
					else {

						geocoder.getLatLng(store.Address + ", " + store.City + ", " + store.PostalCode,
							function(storePoint) {
								createStoreMarker(map, storePoint, store);
							});
					}
				}


			}
		}
	  );
	  	 
	}
}

function createStoreMarker(map, storePoint, store) {

	store.latlng = storePoint;

	marker = createMarker(storePoint);

	map.addOverlay(marker);
	store.marker = marker;
	store.isMarkerInfoShowing = false;

	GEvent.addListener(marker, "click", function() {
		showMapMarker(store.index);
	});

	GEvent.addListener(marker, "infowindowclose", function() {
		store.isMarkerInfoShowing = false;
	});
}

function createMarker(storePoint) {

	var url = ResolveUrl("~/Images/Maps/mapIcon.png")

	var myIcon = new GIcon();
	myIcon.image = ResolveUrl("~/Images/Maps/Icon/image.png")
	myIcon.printImage = ResolveUrl("~/Images/Maps/Icon/printImage.gif")
	myIcon.mozPrintImage = ResolveUrl("~/Images/Maps/Icon/mozPrintImage.gif")
	myIcon.iconSize = new GSize(51, 51);
	myIcon.shadow = ResolveUrl("~/Images/Maps/Icon/shadow.png")
	myIcon.transparent = ResolveUrl("~/Images/Maps/Icon/transparent.png")
	myIcon.shadowSize = new GSize(77, 51);
	myIcon.printShadow = ResolveUrl("~/Images/Maps/Icon/printShadow.gif")
	myIcon.iconAnchor = new GPoint(26, 51);
	myIcon.infoWindowAnchor = new GPoint(26, 0);
	myIcon.imageMap = [39, 1, 44, 2, 45, 3, 46, 4, 47, 5, 47, 6, 47, 7, 47, 8, 48, 9, 48, 10, 48, 11, 48, 12, 48, 13, 48, 14, 48, 15, 48, 16, 48, 17, 48, 18, 48, 19, 48, 20, 48, 21, 48, 22, 48, 23, 48, 24, 48, 25, 48, 26, 48, 27, 48, 28, 48, 29, 48, 30, 48, 31, 48, 32, 47, 33, 47, 34, 47, 35, 47, 36, 46, 37, 46, 38, 44, 39, 41, 40, 32, 41, 31, 42, 30, 43, 30, 44, 29, 45, 28, 46, 28, 47, 21, 47, 20, 46, 19, 45, 18, 44, 17, 43, 17, 42, 16, 41, 8, 40, 5, 39, 4, 38, 3, 37, 2, 36, 2, 35, 2, 34, 2, 33, 2, 32, 2, 31, 2, 30, 2, 29, 2, 28, 2, 27, 2, 26, 2, 25, 2, 24, 2, 23, 2, 22, 2, 21, 2, 20, 2, 19, 2, 18, 2, 17, 2, 16, 2, 15, 2, 14, 2, 13, 2, 12, 2, 11, 2, 10, 2, 9, 2, 8, 2, 7, 2, 6, 2, 5, 3, 4, 4, 3, 5, 2, 10, 1];

	var markerOptions = { icon: myIcon };
	var marker = new GMarker(storePoint, markerOptions);

	return marker;
}

 function showMapMarker(index) {
	var store = stores[index];
	if (store.marker != undefined) {
		var marker = store.marker;
		if (store.isMarkerInfoShowing) {
			marker.closeInfoWindow();
		} else {
			var marker = store.marker;
			var html = "<b>" + store.StoreName + "</b><br/>" + store.Address + ", " + store.City + "<br/>" + store.PostalCode;
			marker.openInfoWindowHtml(html);
			regionMap.setZoom(15)
		}
		
		store.isMarkerInfoShowing = ! store.isMarkerInfoShowing;
	}
 }


function ddlChangeRegion_Change(select) {
	var index = select.selectedIndex;
	if (index != 0) {
		var region = select.options[index].text;
		var url = ResolveUrl("~/StoresAndEvents/Region.aspx?region=" + escape(region));
		location.href = url;
	}
}

/*
Video on an event details module
*/

function initializeVideoForEvent() {
		
	var pnlVideo = $(".pnlEventVideo");
	if (pnlVideo.size() == 0)return;
    
    var flvUrl = pnlVideo.attr("url");
    
    var flashvars = {
        autostart: "true",
        file: flvUrl,
        id: "videoPlayer_Event"
    };
    var params = {
        wmode: "transparent",
        allowfullscreen: "true"
    };
    var attributes = {
        id: "videoPlayer_Event",
        name: "videoPlayer_Event"        
    };
    
    var swfUrl = ResolveUrl("~/swf/player.swf");
    var expressInstallUrl = ResolveUrl("~/swf/expressInstall.swf");               
    
    var expressInstallRequiredVersion = "6.0.65";
    var versionStr = "9.0.0";
    if (swfobject.hasFlashPlayerVersion(expressInstallRequiredVersion)) {
		pnlVideo.html("<div id='pnlVideo_Event'></div>");
    
        swfobject.embedSWF(swfUrl, "pnlVideo_Event", "624", "312", versionStr, "/swf/expressInstall.swf", flashvars, params, attributes);
    } else {
        pnlVideo.html("<div style='height: 312px; width: 624px; text-align: center;'>This content requires <a href='http://get.adobe.com/flashplayer/' target='_blank'>Flash</a>.</div>");
    }
}

function playerStateListener(obj) {

    playerState = obj.newstate;

    if (obj.newstate == "IDLE" && obj.oldstate != "IDLE") {
        isRotating = true;
        if ($("#pnlFeatureBoxItems").data("timeoutVar") == -1) {
            var timeoutVar = setTimeout(function() { rotateBrandDetailsPromo(1); }, imageRotationSpeedSeconds * 1000);
            $("#pnlFeatureBoxItems").data("timeoutVar", timeoutVar);
        }

        //hide the arrows
        $("#pnlFeatureBoxItems .LeftArrow").hide();
        $("#pnlFeatureBoxItems .RightArrow").hide();
    }    
}

function playerReady(player) {
    thePlayer = document.getElementById(player.id);
    thePlayer.addModelListener("STATE", "playerStateListener");
}

function initializeBadgeRotator(rotatorContainer) {

	//choose a random badge to show from .BadgeRotatorItem in the container
	var rotatorItems = $(".BadgeRotatorItem", rotatorContainer);	
	if (rotatorItems.size() < 2) return;	
	var rand = Math.random();
	var index = Math.floor((Math.random() % 1) * rotatorItems.size())	
	$(rotatorItems.get(index)).show();
		

}


function ImageRotator(containerId, properties) {

    var self = this;
    var currentIndex = 0;
    var prevIndex = 0;
    var navIsFading = false;
    var navIsVisible = false;
    
    var defaults = {
        autoPlay: false,
        enableButtonFade: true,
        nextButtonUrl: ResolveUrl('~/Images/Buttons/btnRotateRight.gif'),
        prevButtonUrl: ResolveUrl('~/Images/Buttons/btnRotateLeft.gif'),
        rotationSpeed: 2500
    };

    this.container = null;
    this.image = null;
    this.nextBtn = null;
    this.prevBtn = null;
    this.imagesInfo = null;
    this.imageCount = 0;
    this.timerCallback = null;

    this.init = function() {

        defaults = $.extend({}, defaults, properties || {});

        this.container = $(containerId);
        this.imagesInfo = this.container.find('a');
        this.image = this.container.find('img').eq(0);
        this.imageCount = this.imagesInfo.length;

        if (this.imageCount == 0) return;

        cleanUp();
        initEvents();
        showImage();

        if (this.imageCount > 1) {
            if (defaults.autoPlay == true) {
                self.timerCallback = setInterval(function() { nextImage(); }, 5000);
            }
        }
    }

    function cleanUp() {
    
        self.container.remove('div.Next');
        self.container.remove('div.Prev');
    }

    function initEvents() {

        if (self.imageCount > 1) {
        
            self.nextBtn = $('<div class="Next"></div>').append($('<img />').attr('src', defaults.nextButtonUrl).css('opacity', '0'))
                    .bind('click', nextImage);
            self.prevBtn = $('<div class="Prev"></div>').append($('<img />').attr('src', defaults.prevButtonUrl).css('opacity', '0'))
                    .bind('click', previousImage);

            self.container.append(self.nextBtn).append(self.prevBtn);
            
            if (defaults.enableButtonFade == true) {
                self.nextBtn.hover(showNavButtons, hideNavButtons);
                self.prevBtn.hover(showNavButtons, hideNavButtons);
            }
            else {
                self.nextBtn.find('img').css('opacity', '1');
                self.prevBtn.find('img').css('opacity', '1');
            }
                
            if (defaults.autoPlay == true) {
                self.container.hover(function() {
                    clearInterval(self.timerCallback);
                }, function() {
                    clearInterval(self.timerCallback);
                    self.timerCallback = setInterval(function() { nextImage(); }, 5000);
                });
            }
            
        }
    }

    function showNavButtons() {
        if (!navIsVisible && !navIsFading) {
            navIsFading = true;
            self.nextBtn.find('img').fadeTo('normal', 1, function() { navIsFading = false; navIsVisible = true; });
            self.prevBtn.find('img').fadeTo('normal', 1, function() { navIsFading = false; navIsVisible = true; });
        }
    }

    function hideNavButtons() {
        if (navIsVisible && !navIsFading) {
            navIsFading = true;
            self.nextBtn.find('img').fadeTo('normal', 0, function() { navIsFading = false; navIsVisible = false; });
            self.prevBtn.find('img').fadeTo('normal', 0, function() { navIsFading = false; navIsVisible = false; });
        }
    }

    function nextImage() {
        prevIndex = currentIndex;
        currentIndex = (currentIndex == self.imageCount - 1 ? 0 : currentIndex + 1);
        showImage();
    }

    function previousImage() {
        prevIndex = currentIndex;
        currentIndex = (currentIndex == 0 ? self.imageCount - 1 : currentIndex - 1);
        showImage();
    }

    function showImage() {
        var a = self.imagesInfo.eq(currentIndex);
        self.image.fadeOut('normal', function() {

            var linkUrl = a.attr("linkUrl");

            if (linkUrl != "") {
                $(this).bind("click", function() {
                    window.location = linkUrl;
                });
                $(this).css("cursor", "pointer");
            } else {
                $(this).unbind("click");
                $(this).css("cursor", "default");
            }

            $(this).attr('src', a.attr('href')).attr('alt', a.attr('title')).load(function() {
                $(this).fadeIn('normal');
            });
        });
    }

    this.init();
}
