﻿// JScript File
var _checkClientResolution = false;
var _loginUrl = "";
var _previousToolTip = null;
var _searchUrl = "";
var _asynchProcessRunning = 0;
var _ipaEventTarget = "";
var _ipaEventArgument = "";
var _asynchTimeAllowance = 600;
var _asynchTimeUsed = 0;
var _loadingDivImage = "";
var _alertImage = "";

/** tell ie6 to cache background images**/
if(document.all)
{
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
}
/** end tell ie6 to cache**/

$(document).ready(function() {
	// Enable the left flyouts
	enableFlyoutMenu(true);

	// part of the Ugly URL on postback fix
	if( theForm )
		theForm.action = __CMS_CurrentUrl;
	else
	{
		var theForm = document.forms[0];
		theForm.action = __CMS_CurrentUrl;
	}
	
	if(_checkClientResolution) {
		setTimeout("checkClientResolution()", 1000);
	}
	
	if (typeof(Sys) != "undefined")
	{
	    // Set the handler to process the Web request.
        Sys.Net.WebRequestManager.add_completedRequest(On_WebRequestCompleted);
    
        // Set the handler to call before the Web request is executed.
        Sys.Net.WebRequestManager.add_invokingRequest(On_InvokingRequest);  
    }
    
});

function CompleteAsyncCalls(){
	if(_asynchProcessRunning > 0){
		setTimeout('CheckAsyncCalls()', 50);
	}else{
		return true;
	}
	return false;
}

function CheckAsyncCalls()
{
	_asynchTimeUsed += 50;
	if(_asynchProcessRunning > 0 && _asynchTimeUsed < _asynchTimeAllowance){
		setTimeout('CheckAsyncCalls()', 50);
	}else{
		_asynchTimeUsed = 0;
		__doPostBack(_ipaEventTarget, _ipaEventArgument);
	}
}

// The On_InvokingRequest can be used to perform
// processing prior to the Web request being executed. 
function On_InvokingRequest(executor, eventArgs)
{
	_asynchProcessRunning++;
}

// The On_WebRequestComplete occurs after the
// Web request has returned, and can be used to
// get error status, process returned data, etc...
function On_WebRequestCompleted(executor, eventArgs) 
{
	_asynchProcessRunning--;
}

function enableFlyoutMenu(firstLoad) {;
	$("ul.menu li").each(function() {
		var iCount = 0;
		// Check for IE6
		if(typeof document.body.style.maxHeight == "undefined") {
			this.onmouseover = menuItemHover;
			this.onmouseout = menuItemBlur;
		}
		
		if (!firstLoad) {
			// Remove the enabled class
			if(this.className.indexOf("disabled") >= 0) {
				this.className = this.className.replace("disabled", "");
			}
			this.style.zIndex = 5;
		}
		
		// Determine if the menu has sub menus
		$(this).children().each(function() {
			iCount++;
		});
		
		if(iCount <= 1) {
			if(this.className)
				this.className += " nosub";
			else
				this.className = "nosub";
		}
	});
}

///
/// Handles the key down event on the search text box
///
function searchKeyDown(e, searchUrl) {
	if(e.keyCode == 13 || ($.browser.safari && e.keyCode == 3)) {
		e.cancelBubble = true;
		if (e.stopPropagation)
			e.stopPropagation();
		executeSearch(searchUrl);
		return false;
	}
}

///
/// Handles the key down event on the search text box
///
function reviewSearchKeyDown(e, searchUrl, dropDownId) {
	if(e.keyCode == 13 || ($.browser.safari && e.keyCode == 3)) {
		e.cancelBubble = true;
		if (e.stopPropagation)
			e.stopPropagation();
		executeReviewSearch(searchUrl, dropDownId);
		return false;
	}
}

///
/// Executes the search based on criteria in the header
/// It needs to wait until the user setting has been saved before redirecting or an error will be thrown
///
function executeSearch(searchUrl) {
	// Get the search terms
	var searchTerms = $("#search input:text").val();
	var queryString = "?term=" + (searchTerms == "Item#, MFG# or Keyword" ? "" : searchTerms) + "&DefSort=Y";
	
	// Send the user to the search page
	window.location.href = searchUrl + queryString;
}

function reviewSearchKeyDown(e, searchUrl, dropDownId){
	if(e.keyCode == 13 || ($.browser.safari && e.keyCode == 3)) {
		e.cancelBubble = true;
		if (e.stopPropagation)
			e.stopPropagation();
		executeReviewSearch(searchUrl, dropDownId);
		return false;
	}
}

function executeReviewSearch(searchUrl, dropDownId){
	// Get the search terms
	var searchTerms = $("#reviewSearch input:text").val();
	
	var categoryId = dropDownManager.getDropDown(dropDownId).value();
	
	var queryString = "?term=" + (searchTerms == "Item#, MFG# or Keyword" ? "" : searchTerms) + "&id=&DefSort=Y&searchFilter=ALL" + (categoryId != "" ? "&CatId=" + categoryId : "") ;
	// Send the user to the search page
	window.location.href = searchUrl + queryString;
}

///
/// Redirects to the search page using criteria in the header
///
function redirectSearch() {
	
}

function noClientCallback() {}

function cookieCheck()
{
    if (document.cookie == "")
    {
       this.window.location.replace("/IPA/Error/NoCookies");
    }
}


function lowerLeftColumn() {
	$("ul.menu li").each(function() {
		this.style.zIndex = 1;
	});
}


function disableFlyoutMenu() {
	$("ul.menu li").each(function() {
		this.onmouseover = menuItemBlur;
		this.onmouseout = menuItemBlur;
		this.className += " disabled";
	});
	
}

function menuItemHover() {
	if(this.className.indexOf("sfhover") < 0) {
		this.className += " sfhover";
	}
}

function menuItemBlur() {
	$(this).removeClass("sfhover");
}

//TAB functions

// set this to the number of tabs available.
window.tabNumber = 2;

var selectOn = null;

function checkClientResolution() {
    if (typeof(UI) != "undefined") {
	    UI.Services.AjaxWebService.StoreClientScreenWidth(screen.width,
	    function() {
		    if (screen.width <= 800) {
			    window.location.reload(false);
		    }
	    });
	}
}

///
/// Stores a user setting in session
///
function saveUserSetting(key, value, callback) {    
	if(typeof(UI) != "undefined")
		UI.Services.AjaxWebService.SaveUserSetting(key, value, callback);
}

///
/// Retrieves a user setting from session
///
function getUserSetting(key, callback) {
	if(typeof(UI) != "undefined")
		UI.Services.AjaxWebService.SaveUserSetting(key, value, callback);
}

///
/// Stores the auth URL and redirects to the login page after a session timeout
///
function timeoutRedirect(returnUrl, loginUrl) {
    if(typeof(UI) != "undefined") {
	    UI.Services.AjaxWebService.CheckTimeout(returnUrl, function(response) {
		    // Only redirect if the session has actually timed out
		    if(response) {
			    this.window.location.replace(_loginUrl);
		    // Hasn't timed out, check every ten seconds
		    } else {
			    setTimeout("timeoutRedirect(\"" + returnUrl + "\",\"" + loginUrl + "\");", 10000);
		    }
	    });
	}
	
	_loginUrl = loginUrl;
}

///
/// function which is attached to the "delete" link on the manage groups page
/// - will display alert if the group has users
/// - or will evaluate the links href tag (which is a .net callback function)
///
function groupHasUsers(groupId, transferUrl, confirmMessage, linkHref) {
    if(typeof(UI) != "undefined") {
	    UI.Services.AjaxWebService.GroupHasUsers(groupId, function(response) {
			//only delete if the user is sure
		    if (confirm(unescape(confirmMessage)))
		    {
			    //if there are users in the group, go to the user transfer tool page, else delete the group
			    if (response) {
				    this.window.location = transferUrl;
			    }
			    else {
				    eval(linkHref);
			    }
		    }
	    });
	}
	
	return false;
}

///
/// Creates or shows a loading div with the specified name
///
function showLoadingDiv(name, parentControl, text, loadingOptions) {
	var loadingDiv = document.getElementById("loadingDiv_" + name);
	var loadingImage = document.createElement("img");
	loadingImage.src = _loadingDivImage;
	if(!loadingDiv) {
		// Create the loading div
		loadingDiv = document.createElement("div");
		loadingDiv.className = "loadingDiv";
		loadingDiv.id = "loadingDiv_" + name;
		
		// Add the text
		$(loadingDiv).html(text);
		
		// Add the image
		$(loadingDiv).append(loadingImage);
		$(loadingDiv).css("position", "absolute");
			$(loadingDiv).css("zIndex", "10");
		if(parentControl) {
			if($(parentControl).css("position") != "absolute" && $(parentControl).css("position") != "relative") {
				$(loadingDiv).css("top", $(parentControl).offset().top + "px");
				$(loadingDiv).css("left", $(parentControl).offset().left + "px");
			} else {
				$(loadingDiv).css("top", "0px");
				$(loadingDiv).css("left", "0px");
			}
			$(loadingDiv).css("width", (loadingOptions && loadingOptions.width ? loadingOptions.width : $(parentControl).width()) + "px");
			$(loadingDiv).css("height", (loadingOptions && loadingOptions.height ? loadingOptions.height : $(parentControl).height() / 2) + "px");
			$(loadingDiv).css("padding", (loadingOptions && loadingOptions.padding ? loadingOptions.padding : $(parentControl).height() / 2) + "px 0 0 0");
			$(parentControl).append(loadingDiv);
		} else {
			$(loadingDiv).css("top", (loadingOptions && loadingOptions.top ? options.top : "0") + "px");
			$(loadingDiv).css("left", (loadingOptions && loadingOptions.left ? options.left : "0") + "px");
			$(loadingDiv).css("width", (loadingOptions && loadingOptions.width ? loadingOptions.width : document.documentElement.scrollWidth) + "px");
			$(loadingDiv).css("height", (loadingOptions && loadingOptions.height ? loadingOptions.height : (document.documentElement.scrollHeight / 2)) + "px");
			$(loadingDiv).css("padding", (loadingOptions && loadingOptions.padding ? loadingOptions.padding : ($(window).height() / 2)) + "px 0 0 0");
			$(document.body).append(loadingDiv);
		}
	} else {
		$(loadingDiv).html(text);
		$(loadingDiv).append(loadingImage);
		$(loadingDiv).show();
	}
	
	return loadingDiv;
}

///
/// Hides the loading div with the specified name
///
function hideLoadingDiv(name) {
	if(document.getElementById("loadingDiv_" + name)) {
		$("#loadingDiv_" + name).hide();
	}
}

///
/// Initiates the emailing of a page
///
function emailPage(fromEmail, fromName, toEmail, message) {
	if(Page_ClientValidate("EmailPage") && typeof(UI) != "undefined") {
		$("#emailPage").hide();
		showLoadingDiv("emailPage", null, "Emailing page...");
		setTimeout(function() { executeEmailPage(fromEmail, fromName, toEmail, message.replace(/\n/g, "<br />").replace(/\r/g, "").replace(/\\\"/g, "\\\"")); }, 250);
	}
}

///
/// Executes the server side portion of emailing a page
///
function executeEmailPage(fromEmail, fromName, toEmail, message) {
	var bodyHtml = $("body").html();
	
	if(bodyHtml.indexOf("\"") == 0)
		bodyHtml = bodyHtml.subString(1, bodyHtml.length - 1).replace(/\\\"/g, "");
	
	hideLoadingDiv("emailPage");
	storeHtml = $("div.fauxColumnWrap").html();
	//Opera message fix...
	//Opera seems slow to respond to the AJAX query - insert a message so the user waits
	if ($.browser.opera) { $( function() { $("#userMessage").before("<div id=\"sendMessage\">Sending page - one moment, please...</div>"); } ); }
	try {
		if (typeof(UI) != "undefined") UI.Services.AjaxWebService.EmailPage(fromEmail, fromName, toEmail, storeHtml, $("head").html(), message.replace(/\\\"/g, ""), emailCallback, emailError);
	} catch (e) {
		emailError(null);
	}
	
	//Second part of the Opera fix - hide the custom mesage
	if ($.browser.opera) { $("#sendMessage").hide(); }
	showLoadingDiv("emailPage");
	
	// track the email this page through google
	var re = new RegExp("(/ipa/[^?]+)\\??", "i");
	var result = re.exec(document.URL);
	var path = "";
	
	if (result.length > 0)
	{
		path = result[1];
	}
	
	analyticsProvider.trackGooglePage("/emailPageSubmit" + path);
}

///
/// Handles the callback for the email page method
///
function emailCallback(response) {
	hideLoadingDiv("emailPage");
	$("#emailMessage").html(response);
}

///
/// Handles the error callback for the email page method
///
function emailError(response) {
	hideLoadingDiv("emailPage");
	$("#emailMessage").html("There was an error sending the message, please try again.");
	$("#emailPage").show();
}

///
/// Gets a skinnable image path server side
///
function getSkinnableImage(src, callback) {
	var skinFile = src;
	if(typeof(UI) != "undefined") {
		UI.Services.AjaxWebService.GetSkinnableFile(src, callback);
	}
}

// This is a null callback to allow for true async calls.
function cbnull(resp) { }

///
/// Analytics handler
///
var analyticsProvider = {
	trackAddToCart: function(product, quantity, customEvent) {
		if(typeof(s) != "undefined" && typeof(product) != "undefined") {
		    s=s_gi(s_account);
            s.linkTrackVars='events,products';
			s.products = ";" + analyticsProvider.getSafeAnalyticsValue(product.sku) + ";" + quantity;
			s.events = "scAdd" + (mc.countItems() == 0 ? ",scOpen" : "") + (typeof(customEvent) == "undefined" ? "" : ("," + customEvent));
			s.linkTrackEvents=s.events;
			s_objectID = typeof(customEvent) == "undefined" ? "Other Add To Cart" : customEvent;
            s.tl(this,'o',s_objectID);
		}
	},
	
	///
	/// Executes the analytics code
	///
	processAnalytics: function() {
		s_code = s.t();
		if(s_code)
			document.write(s_code);
	},
	
	/// <summary>
	/// Returns a value that is safe for transfer to the current analytics provider.
	/// </summary>
	/// <param name="value">The value.</param>
	/// <returns></returns>
	getSafeAnalyticsValue: function(value) {
		var output = "";
		
		if(value != null)
			output = value.toString();
		
		// strip bad stuff first
		output = output.replace(/[^\040-\176]/, "");
		output = output.replace(/<[^>]+>|\&\#153|['""|=$]/, "");

		// trim to valid length
		if (output.Length > 100)
		{
			output = output.substring(0, 100);
		}

		return output.toLowerCase();
	}
}

function homePageLoginClick(summaryID) {
	if(Page_ClientValidate()) {
		balloonManager.hide("login_error");
		//showLoadingDiv("login", window.parent.$("#rightColumn")[0], "Authenticating", {height: $("div#login").height()});
	} else {
		$("#" + summaryID).hide();
		balloonManager.show("login_error", $("#" + summaryID).html(), document.getElementById("rightColumn"));
	}
}

function printPage() {

	window.print();
    
}

function popPage() {
         
       $(document).ready(function() {
       if ($(window.opener).location.indexOf("emailPage=1&displayForm=1") > 0)
        {
            c = $(window.opener.document.body).find("#content").html();
            $("#content").html(c);
        }
      });
    
}

function existsCheckedBoxes(parent) {
	if (parent) {
		numfound = 0;
		$("#" + parent).find("input[@type='checkbox']:checked").each(function() {
			numfound++;
		});
		if (numfound == 0) {
			alert("Please select at least one item.");
		}
		return (numfound > 0);
	}
}


    //Fix for the searchresults not preserving the page index when emailed
    //Event sniffer - if a new window opens and it's an email this page with 
    //search results, grab the results from the parent window and use them to populate the 
    //search results in the child window
    $(document).ready(function() {
        var loc = window.location.href;
        if (loc.indexOf("emailPage=1&displayForm=1") > 0)    {
        c = $(window.opener.document.body).find("#searchControl").html();
        $("#searchControl").html(c);
        }
    });
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {encode : function (string) {return escape(this._utf8_encode(string));},decode : function (string) {return this._utf8_decode(unescape(string));},_utf8_encode : function (string) {string = string.replace(/\r\n/g,"\n");var utftext = "";for (var n = 0; n < string.length; n++) {var c = string.charCodeAt(n);if (c < 128) {utftext += String.fromCharCode(c);}else if((c > 127) && (c < 2048)) {utftext += String.fromCharCode((c >> 6) | 192);utftext += String.fromCharCode((c & 63) | 128);}else {utftext += String.fromCharCode((c >> 12) | 224);utftext += String.fromCharCode(((c >> 6) & 63) | 128);utftext += String.fromCharCode((c & 63) | 128);}}return utftext;},_utf8_decode : function (utftext) {var string = "";var i = 0;var c = c1 = c2 = 0;while ( i < utftext.length ) {c = utftext.charCodeAt(i);if (c < 128) {string += String.fromCharCode(c);i++;}else if((c > 191) && (c < 224)) {c2 = utftext.charCodeAt(i+1);string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));i += 2;}else {c2 = utftext.charCodeAt(i+1);c3 = utftext.charCodeAt(i+2);string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));i += 3;}}return string;}}

// handles roll in / out animations in a fashion that won't allow the user to get stuck
// and also won't let them make an element go nuts with animations.
function rolloverAnimation(anchor, target, parentAnchor) {
	// handle to the hover "thread"
	this.hoverTimeout = 0;
	// handle to the hover out "thread"
	this.hoverOutTimeout = 0;
	// the element that acts as the anchor.
	// this element will trigger the display of the target element as the mouse hovers over the anchor element
	this.anchor = anchor;
	// this element is used if there is a parent of the anchor involved, so that the hover out is only triggered when the mouse
	// leaves the parent anchor
	this.parentAnchor = parentAnchor;
	// the element whose display is toggled
	this.target = target;
	this.animating = false;
	
	this.hoverDelay = 500;
	this.hoverOutDelay = 500;
	this.hoverAnimationLength = 500;
	this.hoverOutAnimationLength = 500;
	
	// events
	this.onPreHover = null;
	this.onPreHoverOut = null;
	this.onPostHover = null;
	this.onPostHoverOut = null;
	
	// animation properties
	this.showAnimation = { opacity: "show", width: "show" };
	this.hideAnimation = { opacity: "hide", width: "hide" };

	// handles the initial roll in of the mouse	
	this.rollIn = function(e) {
		var object = this.rolloverHandler;
		
		// clear the roll out timeout, so that only one animation is queued up at once
		clearTimeout(object.hoverOutTimeout);
		
		// queue up the hover animation
		object.hoverTimeout = setTimeout(function() { object.fireHover(object, true); }, object.hoverDelay);
	}
	
	this.__show = function(callback) {
		$(this.target).animate(this.showAnimation, this.hoverAnimationLength, callback);
	}
	
	this.show = function(timeout) {
		// clear the roll out timeout, so that only one animation is queued up at once
		clearTimeout(this.hoverOutTimeout);
		
		if (timeout != null) {
			var object = this;
			// queue up the hover out animation
			this.hoverTimeout = setTimeout(function() { object.fireHover(object, false); }, timeout);
		} else {
			this.fireHover(this);
		}
	}
	
	this.__hide = function(callback) {
		$(this.target).animate(this.hideAnimation, this.hoverOutAnimationLength, callback);	
	}
	
	this.hide = function(timeout) {
		// clear the roll in timeout, so that only one animation is queued up at once
		clearTimeout(this.hoverTimeout);
		
		if (timeout != null) {
			var object = this;
			// queue up the hover out animation
			this.hoverOutTimeout = setTimeout(function() { object.fireHoverOut(object, false); }, timeout);
		} else {
			this.fireHoverOut(this);
		}
	}
	
	// handles the roll out of the mouse
	this.rollOut = function(e) {
		var object = this.rolloverHandler;
	
		// clear the roll in timeout, so that only one animation is queued up at once
		clearTimeout(object.hoverTimeout);
		
		// queue up the hover out animation
		object.hoverOutTimeout = setTimeout(function() { object.fireHoverOut(object, true); }, object.hoverOutDelay);
	}
	
	// triggers the show animation
	this.fireHover = function(object, userAction) {
		var e = { "continueAnimation": true, "animationHandler": object, "userAction": userAction };
		
		// fire the pre hover event
		if (object.onPreHover != null) {
			object.onPreHover(e);
		}

		// allow the above handler to cancel animation
		if (e.continueAnimation && !object.animating) {
			object.animating = true;
			
			object.__show(function() {
				object.animating = false;
				// fire the post hover event
				if (object.onPostHover != null) {
					object.onPostHover(object);
				}
			});
		}
	}
	
	// triggers the hide animation
	this.fireHoverOut = function(object, userAction) {
		var e = { "continueAnimation": true, "animationHandler": object, "userAction": userAction };
		
		// fire the pre hover out event
		if (object.onPreHoverOut != null) {
			object.onPreHoverOut(e);
		}
		
		// allow the above handler to cancel animation
		if (e.continueAnimation && !object.animating) {
			object.animating = true;
			
			object.__hide(function() {
				object.animating = false;
				
				// fire the post hover out event
				if (object.onPostHoverOut != null) {
					object.onPostHoverOut(object);
				}
			});
		}
	}
	
	// wire up the hover events
	if (this.parentAnchor == null) {
		$(this.anchor).hover(this.rollIn, this.rollOut);
	} else {
		$(this.anchor).hover(this.rollIn, function() { });
		$(this.parentAnchor).hover(function() { }, this.rollOut);
		
		this.parentAnchor.rolloverHandler = this;
	}
	
	// attach an instance of this object to the anchor for use later
	this.anchor.rolloverHandler = this;
}

//if the opener is in a frame we cannot set its location from say the Related Products Popup - put this function here to get around that
function redirectPage(url)
{
	location.replace(url);
}