var isExternal = true;

/*****   jQuery Objects used in the script   *****/
var tooltipUser = $j(".pInfo-tooltip,.pInfo-tooltip-anchor"); // elements that when hovered-over, triggers quick info tooltiip
var tooltipContainer = $j("#tooltipContainer"); // container element for the quick info tooltip
var tooltipContent = $j("#tooltipContent"); // element that contains the actual quick info

// iframe element that is placed behind tooltip box to prevent drop-down box in IE6 to bleed through the tooltip
var tooltipIE6Overlay = $j("#fixIEOverlay");


var tooltipHoveredElement = null;   // element that is currently being hovered over
var tooltipIsAvailable = false;
var origHoveredTitle = "";

var tooltipTimer;
var tooltipDelay = 1000;    // in milliseconds


function getString(stringType, stringName)
{
    var result = "";
    
    stringType = stringType.toLowerCase();
    stringName = stringName.toLowerCase();
    if (stringType == "url") {
        if (stringName == "pinfo")
        {
            result = isExternal 
                ? "http://resource.arcadianlighting.com/productinfo.ashx" 
                : "/arcadian/resource/productinfo.ashx";
        }
        else if (stringName = "opt")
        {
            result = isExternal
                ? "http://resource.arcadianlighting.com/OptionAvailChecker.ashx"
                : "/arcadian/resource/OptionAvailChecker.ashx";
        }
    }
    else if (stringType == "format") {
        if (stringName == "product")
        {
            result = isExternal
                ? "{code}.html"
                : "product.aspx?code={code}";
        }
        else if (stringName == "filter")
        {
            result = isExternal
                ? "http://search.arcadianlighting.com/refined.aspx?filter={filter}"
                : "SearchResultInternal.aspx?filter={filter}";
        }
    }
    return result;
}

function toggleElementTitle(element, t)
{
    var origHoveredTitle;
    // hiding element title
    if (t == 0) {
        var hidingElement;
        
        if (element.hasClass("pInfo-tooltip-anchor")) {
            hidingElement = element.children("img");
        } else {
            hidingElement = element;
        }
        
        origHoveredTitle = hidingElement.attr("title");
        if (origHoveredTitle != null && origHoveredTitle.length > 0) {
            hidingElement.attr("title", "");
        }
        hidingElement = null;
    } else { // show element title
        if (origHoveredTitle != null && origHoveredTitle.length != 0) {
            if (element.hasClass("pInfo-tooltip-anchor")){
                element.children("img").attr("title", origHoveredTitle);
	        }
	        else {
                element.attr("title", origHoveredTitle);
            }
	        origHoveredTitle = "";
        }
    }
}

function getTooltipContent(code, tooltipID)
{
    var param = "code=" + code;
    if (!isExternal) {
        param += "&tags=1"
    }
    
	$j.ajax ({
		async: false,
		type: "GET",
		url: getString("url", "pinfo"),
		dataType: "jsonp",
		data: param,
		success: function(json) {
			var i = 0;
			var optionHtml = "";
			var linkFormat = "";
			
			var properties = json.info.properties;
			if (properties != null && properties.length != 0)
			{
			    optionHtml = '<h4 class="propertiesInfoList">Quick Info:</h4>';
			    optionHtml += '<ul class="propertiesInfoList">';
			    for (i = 0; i < properties.length; i++) 
			    {
			        if (properties[i].val.length != 0) {
			            optionHtml += '<li><b>' + properties[i].name + ': </b>' + properties[i].val + '</li>';
			        }
			    }
			    optionHtml += '</ul>';
			}
			
			properties = json.info.tags;
			if (properties != null && properties.length != 0)
			{
			    linkFormat = getString("format", "filter");
			    optionHtml += '<span id="tag"><b>Tags:&nbsp;&nbsp;</b>';
			    for (i = 0; i < properties.length; i++)
			    {
			        optionHtml += '<a href="' + linkFormat.replace("{filter}", properties[i].id) + '">' + 
			            properties[i].name + '</a>';
			        if (i < properties.length - 1){
			            optionHtml += ", ";
			        }
			    }
			    optionHtml += '</span>';
			}
			
			properties = json.info.options;
			if (properties != null && properties.length != 0)
			{
				optionHtml += '<h4 class="optionInfoList">Available options:</h4>';
				optionHtml += '<ul class="optionInfoList">';
				for (i = 0; i < properties.length; i++)
				{
					optionHtml += '<li><span>&middot;</span>' + properties[i].type + ' (' + properties[i].count + ') </li>';
				}
				optionHtml = optionHtml + '</ul>';
			}
			
			var thumbnailHtml = '';
			var imageFolder = json.info.imagefolder;
			var thumbnails = json.info.images;
			if (imageFolder != null && imageFolder.length != 0 &&
				thumbnails != null && thumbnails.length != 0) 
			{
			    var lowerCasedCode = code.toLowerCase();
			    linkFormat = getString("format", "product");

			    imageFolder = 'http://images.arcadianhome.com/' + imageFolder + '/';
				thumbnailHtml = '<ul class="thumbnailInfoList">';
				for (var i = 0; i < thumbnails.length; i++)
				{
				    if (i != thumbnails.length - 1) {
				        thumbnailHtml = thumbnailHtml + '<li>';
				    }
				    else {
				        thumbnailHtml = thumbnailHtml + '<li class="last">';
				    }
					thumbnailHtml = thumbnailHtml +
						'<a href="' + linkFormat.replace("{code}", lowerCasedCode) + '">' +
						'<img src="' + imageFolder + thumbnails[i] + '.75x75.jpg" />' +
						'</a></li>';
				}
				thumbnailHtml = thumbnailHtml + '</ul><br />';
			}
			
			if (optionHtml.length != 0 || thumbnailHtml.length != 0) {
				if (optionHtml.length != 0) {
					$j(tooltipID).append(optionHtml);
				}
				
				if (thumbnailHtml.length != 0) {
					$j(tooltipID).append(thumbnailHtml);
				}
			}
			
			showTooltip(code, tooltipID);
		}
	});
}

function showTooltip(code, detailInfoID)
{
    // position tooltip in relation to product image
	var contentHtml = $j(detailInfoID).html();
	if (contentHtml.length != 0)
	{
	    tooltipIsAvailable = true;
	    
	    // display tooltip	
		tooltipContent.html(contentHtml);
		
		var productImage = $j("a.pInfo-tooltip-anchor[name='" + code + "']").children("img");
		var imagePosition = productImage.offset();
		var imageWidth = productImage.outerWidth(true);
		var imageHeight = productImage.outerHeight(true);
		
		var tooltipLeft = imagePosition.left + imageWidth * 0.75;
		var tooltipTop = imagePosition.top + imageHeight * 0.75;
		var tooltipRight = tooltipLeft + tooltipContainer.outerWidth(true);
		var tooltipBottom = tooltipTop + tooltipContainer.outerHeight(true);
		
		var viewportHeight = window.innerHeight ? window.innerHeight : $j(window).height();
		var viewportWidth = $j(window).width();
		
		
		// default tooltip is lower-right hand corner, therefore the mega-phone should be placed on the upper-left hand corner
		var horizontalSide = 'l';
		var verticalSide = 't';
		
		// if tooltip appears outside of the viewport horizontally, move to left (mega-phone to right)
		if (tooltipRight >= viewportWidth)
		{
		    tooltipLeft = tooltipLeft - imageWidth/2 - tooltipContainer.outerWidth(true)
		    horizontalSide = 'r';
		}
		
		// if tooltip appears outside of the viewport vertically, move to top (mega-phone to bottom)
		if (tooltipBottom >= viewportHeight + $j(window).scrollTop())
		{
		    tooltipTop = tooltipTop - imageHeight/2 - tooltipContainer.outerHeight(true);
			verticalSide = 'b';
		}
		
		var visibleCornerID = "#corner-" + verticalSide + horizontalSide;
		$j(visibleCornerID).removeClass("hidden");
		
		tooltipContainer.css("top", tooltipTop + "px");
		tooltipContainer.css("left", tooltipLeft + "px");
		tooltipContainer.show();
		
				//var cornerWidth = $j(visibleCornerID).width();
		tooltipIE6Overlay.width(tooltipContent.width());
		tooltipIE6Overlay.height(tooltipContainer.height());
		tooltipIE6Overlay.css("top", tooltipContent.offset().top + "px");
		tooltipIE6Overlay.css("left", tooltipContent.offset().left + "px");
		tooltipIE6Overlay.css("display", "block");
    }
    else {
        toggleElementTitle(tooltipHoveredElement, 1);
    }
    tooltipHoveredElement = null; // release variable
}

function customTooltipHandler() {
    // retrieve product code from the hovered over element
        
    var code = tooltipHoveredElement.attr("name");
    if (code != null && code.length > 0) {
        tooltipHoveredElement = tooltipHoveredElement.children("img");
    }
    else {
        code = tooltipHoveredElement.attr("id");
        if (code != null && code.length > 0) {
            code = code.substring(3, code.length);
        }
        else {
            code = tooltipHoveredElement.attr("alt");
        }
        if (code == null || code.length == 0) {
            return false;
        }
    }
    
    // check if we've already retrieve information on this product, if not, send a request to web service
    var detailID = code + "_detail";
    if (!document.getElementById(detailID))
	{
		$j("body").append('<div id="' + detailID + '" class="hidden"></div>');
		getTooltipContent(code, "#" + detailID);
	}
	else
	{
	    showTooltip(code, "#" + detailID);
	}
}

var pInfoMouseleaveHandler = function(event) {
    if (tooltipHoveredElement != null) {
        toggleElementTitle(tooltipHoveredElement, 1);
        tooltipHoveredElement = null;
        clearTimeout(tooltipTimer);
    } else {
	    var cur = $j(this);
    	
	    if (cur.is('a')) {
	        tooltipContainer.hide();
	        tooltipIsAvailable = false;
	    }
	    else {
	        var position = cur.position();
    	    
	        var left = position.left;
	        var right = position.left + cur.outerWidth(true);
	        var top = position.top;
	        var bottom = position.top + cur.outerHeight(true);
    	    
	        if (event.pageX <= left || event.pageX >= right ||
	            event.pageY <= top || event.pageY >= bottom)
	        {
		        if (cur.is('img')) 
		        {
			        tooltipContainer.hide();
		        }
		        else 
		        {
			        cur.hide();
		        }
		        tooltipIsAvailable = false;
	        }
	    }

	    if (!tooltipIsAvailable) {
	        $j("img.tooltipCorner").attr("class", "tooltipCorner hidden");
	        toggleElementTitle(cur, 1);
	        
	        tooltipIE6Overlay.css("display", "");
	    }
	    cur = null;
	}
};

// show tooltip upon mouseover
tooltipUser.mouseenter(function(){
    tooltipHoveredElement = $j(this);
    toggleElementTitle(tooltipHoveredElement, 0);
    tooltipTimer = setTimeout("customTooltipHandler(tooltipHoveredElement)", tooltipDelay);
});
tooltipUser.mouseleave(pInfoMouseleaveHandler);
tooltipContainer.mouseleave(pInfoMouseleaveHandler);


// Use to show option available images
var itemCodesToCheck = new Array();
$j(".pInfo-tooltip-anchor").each(function() {
    itemCodesToCheck.push($(this).attr("name"));
});

$j.ajax ({
	async: true,
	type: "GET",
	url: getString("url", "opt"),
	dataType: "jsonp",
	data: "codes=" + itemCodesToCheck.join(),
	success: function(json) {
		if (json.codes != null && json.codes.length != 0)
		{
		    for (var i = 0; i < json.codes.length; i++) 
		    {
		        $j("img.opt-avail[alt='" + json.codes[i] + "']").css("display", "");
		    }
		}
	}
});
itemCodesToCheck = null;
// Use to show option available images
