//
var superMenu;
var loggedIn;
// get the language of the user for proper flash pieces
var language = getCookie('hhLanguage');
var homepageTrigger = getCookie('hhTrigger');
var destinationUrl;
var map;
var dir;
var panel;
var latitude;
var longitude;
var mapForStore;
var loadvideo = '';
var loginContext = false;
var googleLoaded = true;
var workingPage = '';
var positionFixedIsInvalid;

// this needs to be first or IE gets confused during some ajax calls
try { // set the login flag
	checkLogin();
} catch (e) {
}

function initPage() {
	// loadGoogleStuff();

	// heyo, heyo, load all swfs here, k thx.
	// swf object, ftw.

	if (language == '') {
		language = 'en';
	}

	// LSI
	try {
		var so = new SWFObject("/swf/" + language + "/hh_lsi_container.swf",
				"hh_storeLocator", "204", "210", "9", "#ffffff");
		so.addParam("quality", "high");
		so.addParam("wmode", "transparent");
		so.addParam("allowScriptAccess", "always");
		so.write("location");
	} catch (e) {
	}

	// spotlight thang
	try {
		var so = new SWFObject("/swf/" + language
				+ "/hh_spotlight_container.swf", "hh_spotlight", "960", "620",
				"9", "#ffffff");
		so.addParam("quality", "high");
		so.addParam("allowScriptAccess", "always");
		so.write("spotlight_container");
	} catch (e) {
	}

	// header thing
	try {
		workingPage = String($('hh_feature').className);
	} catch (e) {
	}

	try {
		if (workingPage != '') {
			var swfHeight = "290";
			var swfName = "/hh_feature.swf";
			if (workingPage == 'highlight_beautitone_landing' || 
				workingPage == 'highlight_homeathome_landing' || 
				workingPage == 'highlight_homeowner' || 
				workingPage == 'highlight_homeinstalls' || 
				workingPage == 'highlight_toughasnails') {
				swfHeight = "234";
				swfName = "/hh_bt_feature.swf";
			}

			var so = new SWFObject("/swf/" + language + swfName,
					"hh_feature", "489", swfHeight, "9", "#ffffff");
			so.addParam("quality", "high");
			so.addParam("wmode", "transparent");
			so.addParam("allowScriptAccess", "always");
			so.addVariable("pageName", workingPage);
			so.write("hh_feature");
		}
	} catch (e) {
	}

	// TODO: any other loading things

	try {
		Event.observe('search_terms', 'click', selectSearch);
	} catch (e) {
	}
	
	try {
		Event.observe('splashEmailEntryEnglish', 'click', selectEmailEntryEnglish);
	} catch (e) {
	}
	
	try {
		Event.observe('splashEmailEntryFrench', 'click', selectEmailEntryFrench);
	} catch (e) {
	}
	
	initMenu();

	// attach events to anything with the class 'signin', 'print', or 'external'
	var docLinkList = document.getElementsByTagName('a');
	for ( var i = 0; i < docLinkList.length; i++) {
		if (docLinkList[i].className == 'signin') {
			try {
				Event.observe(docLinkList[i], 'click', doLogin);
			} catch (e) {
			}
		} else if (docLinkList[i].className == 'external') {
			try {
				Event.observe(docLinkList[i], 'click', trackLink);
				docLinkList[i].target = "_blank";
			} catch (e) {
			}
		} else if (docLinkList[i].className == 'print') {
			try {
				Event.observe(docLinkList[i], 'click', printThis);
			} catch (e) {
			}
		} else if (docLinkList[i].className == 'storeMap') {
			try {
				Event.observe(docLinkList[i], 'click', doMap);
			} catch (e) {
			}
		} else if (docLinkList[i].className == 'pricePopup') {
			try {
				Event.observe(docLinkList[i], 'click', doPriceInfo);
			} catch (e) {
			}
		}
	}
    try {
        Event.observe('howthisworks', 'click', showHowThisWorks);
    } catch (e) {}

	if ($('hh_exclusivetohome_videos')) {
		// 1 - 9
		var videoToLoad = window.location.href.slice(window.location.href.indexOf('/video/') + 7).substr(0, 1);
		
		try {
			var so = new SWFObject("/swf/" + language + "/hh_excl2home_vids.swf",
					"hh_exclusivetohome_videos", "489", "164", "9", "#dedede");

			so.addParam("quality", "high");
			so.addParam("allowScriptAccess", "always");
			so.addParam("wmode", "transparent");
			so.addParam("FlashVars", "video=" + videoToLoad);
			so.write("hh_exclusivetohome_videos");
		} catch (e) {}
	}
	
	// Home Network popup tag exists, observe it
	if ($('homeNetworkPopup')) {

		try {
            Event.observe('homeNetworkPopup', 'click', function(e) {
            	e.stop();
            	setupHomeNetworkPopup();
            });
            Event.observe('homeNetworkPopupLink', 'click', function(e) {
            	e.stop();
            	setupHomeNetworkPopup();
            });
        } catch (e) {}
	}
	
	if ($('showHomeNetwork')) {
		setupHomeNetworkPopup();
	}

	if ($('toyotaTundraWinnerBanner')) {
		try {
			Event.observe('toyotaTundraWinnerBanner', 'click', showTundraVideo);
		} catch (e) {
		}
	}
	
	if ($('magic_gallery')) {
	    // a gallery tag exists, load it up.
	    $('magic_gallery').innerHTML = '<center><img src="/images/spinner.gif" /></center>';
	    var url = '/index/ajax/where/Gallery/method/getGallery/name/' + $('magic_gallery').className;
	    new Ajax.Updater(
            'magic_gallery',
            url, {
            method: "get",
            onComplete: setupGalleryImages
            }
        );
	}

	if ($('dealerWalkOnVideo')) {
		
		positionFixedIsInvalid = getPositionFixedIsInvalid(); 
		
		moveDealerWalkonVideo(true);
		
		if (positionFixedIsInvalid) {
			$('dealerWalkOnVideo').style.position = "absolute";
		}
		
		window.onresize = function () { 
			moveDealerWalkonVideo(true); 
		}
		
		window.onscroll = function () { 
			moveDealerWalkonVideo(false); 
		}
	}
}

function moveDealerWalkonVideo(nonScroll)
{
	if (! positionFixedIsInvalid) {
		if (nonScroll) {
			var videoTopPosition = document.documentElement.clientHeight - 270;
			$('dealerWalkOnVideo').style.top = videoTopPosition + "px";
		}
	} else {
		var videoTopPosition = document.documentElement.clientHeight + document.documentElement.scrollTop - 270;
		$('dealerWalkOnVideo').style.top = videoTopPosition + "px";
	}

	var defaultScreenWidth = 1264;
	var defaultMarginLeft  = 183;
	var marginDiff = (document.documentElement.clientWidth - defaultScreenWidth) / 2;
	var videoLeftPosition = defaultMarginLeft - marginDiff;
	$('dealerVideoContent').style.marginLeft = "-" + videoLeftPosition + "px";
}

function showTundraVideo()
{
	Modalbox.show('<div id="player"></div>', {	
                  title: '',
                  width: 452,
                  height: 330,
                  afterLoad : loadTundraVideo
	});	
}

function loadTundraVideo() {
	try {
		var so = new SWFObject("/swf/playa.swf", "flvPlayer", "432", "288", "9", "#ffffff");
		
		so.addVariable("tipVids", "/swf/en/videos/Toyota_Tundra_Contest_Winner_2009.flv");
		so.addParam("quality", "high");
		so.addParam("wmode", "transparent");
		so.write("player");

	} catch (e) {}
}

function setupGalleryImages()
{
    var images = $$('a.largeImage');
    for ( var i = 0; i < images.length; i++) {
        try {
            Event.observe(images[i], 'click', largeGalleryImage);
        } catch (e) {}
    }
}

function largeGalleryImage(event)
{
    event.stop();
    if (event.element(event).tagName != 'A') {
        var myElement = event.element(event).parentNode;
    } else {
        var myElement = event.element(event);
    }
    Modalbox.show('<p style="width: 650px; height: 500px;"><img src="' +
            myElement.href + '"/></p>', {title: '', width: '660'});
}
/*
function setupGalleryPages(pageId, pageNumber)
{
	try {
		Event.observe('galleryPage' + pageId, 'click', switchGalleryPage(pageNumber));
	} catch (e) {
		
	}	
}
*/
function switchGalleryPage(page)
{
	$('gallery_pagination').innerHTML = '<img src="/images/spinner.gif" />';
    var url = '/index/ajax/where/Gallery/method/getGallery/name/' + $('magic_gallery').className + '/galleryPage/' + page;
    new Ajax.Updater(
        'magic_gallery',
        url, {
        method: "get",
        onComplete: setupGalleryImages
        }
    );
    
    return false;
}

function setupHomeNetworkPopup() {
	
	Modalbox.show('<div id="radusWidgetDiv"></div>', {
		title :'',
		width :366,
		height :585,
		afterLoad : showHomeNetworkWidget 
	});
}

function showHomeNetworkWidget()
{
	var locale = "en_US";
	var applicationId = "";
	var passThrough = null;
	var itemID = null;
	var itemSource = null;
	
	if (language == 'fr') {
		locale = "fr_CA";
		applicationId = "0A791D96-1E80-4982-BFD6-3451F42509A9";
	} else {
		applicationId = "5B874C6A-0889-4483-BE14-F17537A69C9E";			
	}
	
	if ($('homeNetworkPassThrough')) {
		passThrough = $('homeNetworkPassThrough').value;
	}
	
	if ($('homeNetworkItemID')) {
		itemID = $('homeNetworkItemID').value;
	}
	
	if ($('homeNetworkSource')) {
		itemSource = $('homeNetworkSource').value;
	}
	
	embedRadus(applicationId, locale, "350", "540", passThrough, "1.8", false, itemID, itemSource);
}

function embedRadus(application, locale, width, height, passThrough, version, testing, itemID, itemSource)
{
	// Determine our root url
	var baseUrl = "http://homehardware.radus.com/";

    if (testing == true) {
          baseUrl = "http://staging.radus.com/";
    }

    baseUrl += "v" + version + "/";
    
    var so = new SWFObject(baseUrl + "Shell.swf", "Radus", width, height, "9.0.115", "#000000");
    
	so.addVariable("application", application);
    so.useExpressInstall(baseUrl + "expressinstall.swf");
    so.addParam("quality", "high");
    so.addParam("bgcolor", "#000000");
    so.addParam("allowfullscreen", "true");
    so.addParam("allowscriptaccess", "always");

    // en_US is included by default. ONLY include the locale
    // information if your locale is NOT en_US.
    if (locale != "en_US") {
      var resourceUrl = baseUrl + locale + "_ResourceModule.swf";
      so.addVariable("resourceModuleURLs", resourceUrl);
      so.addVariable("localeChain", locale);
    }
    
    // Next add the contentItemID if provided
    if (itemID != null) {
    	so.addVariable("contentItemID", itemID);
    }
    
    // And the itemSource
    if (itemSource != null) {
    	so.addVariable("itemSource", itemSource);
    }

    // If passThrough params are specified, then add them too
    if (passThrough != null) {
    	so.addVariable("passThrough", passThrough);
    }

    so.write('radusWidgetDiv');
}

function doPriceInfo(event) {
	event.stop();
	Modalbox.show('/index/ajax/where/Products/method/GetPricingInformation', {
		title :''
	});
}

function trackLink(event) {
	if (event.element(event).tagName != 'A') {
		var myElement = event.element(event).parentNode;
	} else {
		var myElement = event.element(event);
	}
	urchinTracker('/external/' + encodeURI(myElement));
	pageTracker._trackPageview('/external/' + encodeURI(myElement));
}

function printThis(event) {
	event.stop();
	window.print();
	urchinTracker('/printpage/' + encodeURI(self.location));
	pageTracker._trackPageview('/printpage/' + encodeURI(self.location));
}

function doLogin(event) {
	// fetch the login box and pop it up.
	if (loggedIn == true) {
		// continue on
	} else {
		event.stop();

		destinationUrl = event.element(event);
		// show a box
		Modalbox.show('/index/ajax/where/User/method/GetLoginBox', {
			title :'',
			width :325,
			height :290,
			afterLoad :attachLoginEvents
		});
	}

}

function attachLoginEvents() {
	loginContext = true;
	// howthisworks
	try {
		Event.observe('howthisworks', 'click', showHowThisWorks);
	} catch (e) {
	}
	// cancel
	try {
		Event.observe('button_cancel', 'click', cancelLogin);
	} catch (e) {
	}
	$('destinationUrl').value = destinationUrl;
}

function showHowThisWorks() {
	if (loginContext == true) {
		lc = '/login/1';
	} else {
		lc = '';
	}
	url = '/index/ajax/where/User/method/getHowThisWorks' + lc
	Modalbox.show(url, {
		title :'',
		width :400,
		afterLoad :attachHowThisWorksEvents
	});
}

function attachHowThisWorksEvents() {
	try {
		Event.observe('howthisworks_back', 'click', doLogin);
	} catch (e) {
	}

}

function cancelLogin() {
	loginContext = false;
	Modalbox.hide();
	try {
		Event.stopObserving('howthisworks', 'click', showHowThisWorks);
		Event.stopObserving('howthisworks_back', 'click', doLogin);
		Event.stopObserving('button_cancel', 'click', cancelLogin);
	} catch (e) {
	}

}

function selectSearch() {
	$('search_terms').select();
	Event.stopObserving('search_terms', 'click', selectSearch);
}

function selectEmailEntryEnglish()
{	
	$('splashEmailEntryEnglish').value = '';
}

function selectEmailEntryFrench()
{	
	$('splashEmailEntryFrench').value = '';
}

function getCookie(name) {
	var cookieValue = "";
	var search = name + "=";

	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) {
				end = document.cookie.length;
			}
			cookieValue = unescape(document.cookie.substring(offset, end))
		}
	}
	return cookieValue;
}

function setCookie(cookieName, cookieValue, nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays == null || nDays == 0)
		nDays = 1;
	expire.setTime(today.getTime() + 3600000 * 24 * nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires="
			+ expire.toGMTString();
}

function checkLogin() {
	var randNum = parseInt(Math.random() * 999999999999999);
	var url = '/index/ajax/where/User/method/CheckLogin/rand/' + randNum;

	new Ajax.Request(url, {
		method :'get',
		onSuccess : function(transport) {
			if (transport.responseText == '<user>true</user>') {
				loggedIn = true;
			} else {
				loggedIn = false;
			}
		},
		onFailure : function(transport, target) {
		}
	});
}

// Maps! Woot! (related to Stores, yo)
function doMap(store) {
	// figure out if store is a xxxx-x or an event.
	try {
		store.stop();
		var elementcontents = String(store.element(store));
		mapForStore = elementcontents.substring(elementcontents.length - 6);
	} catch (e) {
		mapForStore = store;
	}

	// fetch the info for the store
	Modalbox.show('/index/ajax/where/Store/method/getMapTemplate', {
		title :'',
		width :525,
		height :490,
		afterLoad :attachMapEvents
	});

	// slLoadMap(slLat, slLong, slType);
}

function attachMapEvents() {
	// attach stuff, and fire up the map
	if (googleLoaded) {
		slLoadMap('43', '-79', mapForStore, false);
	} else {
		setTimeout("attachMapEvents()", 10);
	}
}

function loadGoogleStuff() {
	google.load("maps", "2", {
		'locale' :language,
		'callback' : function() {
			googleLoaded = true;
		}
	});
}

// Create a marker whose info window displays the given number.
function slCreateMarker(point, html, icon) {
	var marker = new GMarker(point, icon);

	// Show this marker's index in the info window when it is clicked.
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function slLoadMap(latitude, longitude, store, directions) {
	var directions = directions;
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallZoomControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.setCenter(new GLatLng(latitude, longitude), 11);

	// add points
	GDownloadUrl(
			"/index/ajax/where/Store/method/getStoreDetails/store/" + store,
			function(data) {
				var xml = GXml.parse(data);
				var markers = xml.getElementsByTagName("store");
				for ( var i = 0; i < markers.length; i++) {
					try {
						lat = markers[i].getElementsByTagName("Latitude");
						latitude = lat[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						long = markers[i].getElementsByTagName("Longitude");
						longitude = long[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						storeType = markers[i]
								.getElementsByTagName("StoreType");
						storeType = storeType[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						hold = markers[i].getElementsByTagName("Name");
						storeName = hold[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						hold = markers[i].getElementsByTagName("Address");
						storeAddress = hold[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						hold = markers[i].getElementsByTagName("City");
						storeCity = hold[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						hold = markers[i].getElementsByTagName("PostalCode");
						storePostalCode = hold[0].firstChild.nodeValue;
					} catch (e) {
					}

					try {
						hold = markers[i].getElementsByTagName("PhoneNumber");
						storePhoneNumber = hold[0].firstChild.nodeValue;
					} catch (e) {
					}

					var point = new GLatLng(latitude, longitude);
					var html = '<div class="storeBubble"><img src="/images/'
							+ language + '/logo-store-' + storeType
							+ '.gif" /><br /></div>';

					var icon = new GIcon();
					icon.image = "/images/little_logo_" + storeType + ".png";
					icon.iconSize = new GSize(18, 18);
					icon.iconAnchor = new GPoint(6, 20);
					icon.infoWindowAnchor = new GPoint(5, 1);

					// populate the store deets
					imgStr = '<img src="/images/' + language + '/logo-store-'
							+ storeType + '.gif" width="165" height="91" />';
					document.getElementById("store_logo").innerHTML = imgStr;
					document.getElementById("store_address_name").innerHTML = storeName;
					try {
						document.getElementById("store_address_name_header").innerHTML = storeName;
					} catch (e) {
					} // this only exists on the dd page;
					document.getElementById("store_address_address").innerHTML = storeAddress;
					document.getElementById("store_address_city").innerHTML = storeCity;
					document.getElementById("store_address_postalcode").innerHTML = storePostalCode;
					document.getElementById("store_address_phonenumber").innerHTML = storePhoneNumber;
					try {
						document.getElementById("magicMapLink").href = '/StoreLocator/index/map/store/' + store;
					} catch (e) {
					}

					map.addOverlay(slCreateMarker(point, html, icon));
					map.setCenter(new GLatLng(latitude, longitude), 14);

					if (directions == true) {
						// load the directions panel
						panel = $("drivingDirections");
						dir = new GDirections(map, panel);
						slLoadDirections(latitude, longitude);
					}
				}
			});

}

function videoPopup(video)
{
	loadvideo = video;
	Modalbox.show('/index/ajax/where/Cms/method/GetContent/page/beautitone_video', {
		title :'',
		width :369,
		height :335,
		afterLoad : loadVideoPlease
	});
}

function loadVideoPlease() {
	var so = new SWFObject("/swf/playa.swf", "flvPlayer", "360", "270", "9", "#ffffff");
	so.addVariable("tipVids", "/swf/" + language + '/videos/' + loadvideo);
	so.addParam("quality", "high");
	so.addParam("wmode", "transparent");
	so.write('player');
	var url = '/Products/landing/videocounter/video/' + loadvideo + '/videolang/' + language;
	urchinTracker('/video/' + url);
	pageTracker._trackPageview('/video/' + url);
	new Ajax.Request(url);
}

function adBlockClickThru(adImg, adType, adLang)
{
	var url = '/index/adblock-click-thru/adImg/' + adImg + '/adType/' + adType + '/adLang/' + adLang;
    new Ajax.Request(
    		url, 
    		{	
    			method: 'get'
    		}
    	);
}

function getPositionFixedIsInvalid()
{
	var ver = getInternetExplorerVersion();
	
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && (ver > -1) && (ver < 7.0);
}

function getInternetExplorerVersion()
{
	var rv = -1; // Return value assumes failure.
	
	if (navigator.appName == 'Microsoft Internet Explorer') 	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	
	return rv;
}

function closeRadus()
{
	Modalbox.hide();
}

Event.observe(window, 'load', initPage);
