/* --- -----------------------------------------------------------------------------
 Filename:		JavaNav.js
 Description: 	Java Script navigation scripts 

 Copyright (c) 1999-2009 JADE International, Inc. All rights reserved.
------------------------------------------------------------------------------- */
function ConfirmDelete(form, action, strMsg) {
        if (confirm(strMsg)) {
			form.action=action;
			form.submit();
        }
}

function ConfirmFormAction(form, action, strMsg) {
        if (confirm(strMsg)) {
			form.action=action;
			form.submit();
        }
}

function ConfirmLinkAction(action, strMsg, strMsg2) {
	if (confirm(strMsg)) {
		if (typeof(strMsg2) == 'undefined' ){
			window.location=action;
		}
		else
		{
			if (confirm(strMsg2)) {
				window.location=action;
			}
		}
	}
} 		

function GoTo(strHref) {
	window.location.href = strHref;
}

function ExecuteForm(form, action) {
	form.action=action;
	form.submit();
}

function openHelpWindow (parHref)
{
  openWindow (parHref, 300, 300, 20, 30);
}

function openWindow(parHref, width, height, screenX, screenY) 
{
  // Check if screenX and screenY are undefined
  if(typeof(screenX)=="undefined"){ screenX = 80 }
  if(typeof(screenY)=="undefined"){ screenY = 60 }
  
  winOptions = 'width=' + width + ',height=' + height 
             + ',screenx=' + screenX + ',screeny=' + screenY
             + ',left=' + screenX + ',top=' + screenY
             + ',toolbar=no,location=no,resizable=yes,scrollbars=yes';
  winName = 'Window' + width + height;
  newWindow = window.open(parHref, winName, winOptions)
		newWindow.focus();
}

function getRadioButtonValue (radio)
{
  var found=0;
  for (var i = 0; i < radio.length; i++)
  {
    if (radio[i].checked)
	{
	  var found=found+1;
	  return radio[i].value;
	}
  }
  if (found == 0)
  {
    return false;
  }
}

// Field validation
function checkLen(field, intLen, divMsg)
{
	if (field.value.length >= intLen)
	{
		divMsg.innerHTML = "0 Characters left";
		field.value = field.value.substr(0, intLen);
		return false;
	}

	intRemainder = intLen - field.value.length;

	if (intRemainder > 1)
		divMsg.innerHTML = intRemainder + " characters left.";
	else
		divMsg.innerHTML = intRemainder + " character left.";
	
	return true;
}

// String trim functions
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// Catalog quantity field validation
function validateOrderQty (fldQty)
{
	if (trim (fldQty.value).length == 0)
	{
		alert ("Please enter a quantity.");
		fldQty.focus();
		return false;
	}
	
	if (!isNumeric (fldQty.value))
	{
		alert ("Please enter a valid quantity.");
		fldQty.value = "";
		fldQty.focus();
		return false;
	}

	return true;
}

function isNumeric (number)
{
	var NumericRegExp = /^\d+$/;
	return NumericRegExp.test (number);
}

function incValue (field)
{
		if (isNaN (parseInt (field.value)))
			field.value = 1;
		else
			field.value = parseInt (field.value) + 1
}

function autoResize(id, height, width)
{
	
	var obj = $("#" + id);
	var image = new Image();
	
	image.onload = function()
	{
		
		var newH = image.height > height ? height : image.height;
		var newW = image.height > height ? image.width*(height/image.height) : image.width;
		
		var newH = newW > width ? newH*(width/newW) : newH;
		var newW = newW > width ? width	: newW;
		
		obj.attr("height", Math.ceil(newH));
		obj.attr("width", Math.ceil(newW));
		obj.css("height", Math.ceil(newH) + "px");
		obj.css("width", Math.ceil(newW) + "px");
	};
	
	image.src = obj.attr("src");
}


// ------------------------------------------------------------
// Roll over Image Functions
// These functions are used for the roll over navigation images
// ------------------------------------------------------------

//Change Images Function
// This function swaps the OFF image with the ON image
function RCChangeImages(imgName, state) 
{
	if (document.images && (RCPreloadFlag == true)) 
	{	
		// Turn on/off current link
		if(state == "on")	
		{
			document[imgName].src = RolloverImages[imgName][1];
		}
		else
		{
			document[imgName].src = RolloverImages[imgName][0];
		}
	}
}		

// Preload Images function
// This function loads all of the images for the rollovers so that
// they are cached in the browser for faster viewing.
function RCPreloadImages() 
{
	if (document.images) 
	{
		// To prevent a memory leak, only define this object once
		var OnImage = new Image();
		
		for(var i in RolloverImages)
		{					
			OnImage.src = RolloverImages[i][1];
		}
		
		RCPreloadFlag = true;
	}
}

// ----------------------------------------------------------------------------
//	Product 'Stock Status'
//
//	Arguments:
//		element		: The '<select>' tag context
//		returnQty	: Flag if the quantity should be placed in the <span> or
//					  a string "In/Out of Stock"
// ----------------------------------------------------------------------------

function GetStockStatus( element, returnQty )
{	
	// Create a variable to hold this flag in the 'closure' scope so that
	// the closure function in the AJAX 'completed' parameter can access it.
	var ReturnQuantity = returnQty;
	
	//
	// Get the form and the option group elements for this product
	//
	var Form = $(element).closest("form");
	var Options = $(Form).find('select[name^="OptionGroup"]');
	
	//
	// Setup an XML document to pass in the AJAX call
	//
	var Product = "<?xml version='1.0' encoding='UTF-8'?>";	
	
	var ProductId = $(Form).children('input[name="ProductId"]').val();
	Product += "<Product id='" + ProductId + "' qty='" + returnQty + "'" + ">";
	
	//
	//	Create the Option Group Mapping
	//
	for( var i = 0; i < Options.length; i++ )
	{		
		var GroupValue = $(Options[i]).val();
		
		// If we run into an option that is not selected, we are not going to do an AJAX call
		if(GroupValue == 0){ return; }
		
		Product += "<OptionGroupValue>" + GroupValue + "</OptionGroupValue>";			
	};
	
	Product += "</Product>";
	
	var test = true ? "this" : "that";
	
	//
	// Construct the AJAX call
	//	
	$.ajax({
		type: "POST",
		contentType: "text/xml",
		url: "/RapidCat/Catalog/DisplayProduct_GetStockUpdate.cfm",
		dataType: "xml",
		data: Product,
		complete: function(RequestResult, Status){
			
			// Create a jQuery object from the XML result
			var XMLResponse = $(RequestResult.responseXML).children("StockStatusResponse");
			
			// Parse the result, setting status text, color, and quantity
			var StockStatus = (XMLResponse.children("Status").attr("instock") == "true") ? "In Stock" : "Out of Stock";
			var StockStatusColor = (StockStatus == "In Stock") ? "color: #478740;" : "color: #87312D;";
			var StockStatusInfo = (StockStatus == "In Stock") ? "display: none" : "display: inline";
			var StockQty = "Available Qty: " + XMLResponse.children("Status").attr("qty");
			
			// Update the HTML elements below the price with the result value
			if( ReturnQuantity == true )
				$("#StockStatus" + ProductId).html(StockQty).attr("style", StockStatusColor);
			else if( ReturnQuantity == false )
				$("#StockStatus" + ProductId).html(StockStatus).attr("style", StockStatusColor);
			
			$("#StatusInfo" + ProductId).attr("style", StockStatusInfo);
		}
	});
	
}

// ----------------------------------------------------------------------------
//	Validate 'Add to Cart'
// ----------------------------------------------------------------------------

function ValidateAddToCart( form )
{
	var Options = $(form).find('select[name^="OptionGroup"]');
	var Qty = $.trim( $(form).find('input[name="Qty"]').val() );

	// Validate the quantity
	// If the quanity is blank set it to one
	if (Qty.length == 0)
	{
		Qty = 1;
		$(form).find('input[name="Qty"]').val('1');
	}	
	// (must be valid number and between 1 and 2 characters)
	else if (!Qty.match(/^\d{1,2}$/))
	{ alert ("Please enter a valid quantity."); return false; }	
	
	// Validate the options
	for (var i = 0; i < Options.length; i++)
	{
		if ($(Options[i]).val() == 0)
		{ alert("Please select valid product options."); return false; }
	}
	
	return true;
};

// ----------------------------------------------------------------------------
//	Tooltip
// ----------------------------------------------------------------------------

/* Wayfarer Tooltip
 * Version 1.0.9
 * Author Abel Mohler
 * URI: http://www.wayfarerweb.com/wtooltip.php
 * Released with the MIT License: http://www.wayfarerweb.com/mit.php
 */
(function($){ //jQuery.noConflict()compliant
    $.fn.wTooltip = function(o, callback){
        o = $.extend({ //defaults, can be overidden
            content: null, //string content for tooltip.
            ajax: null, //path to content for tooltip
            follow: true, //does tooltip follow the cursor?
            auto: true, //If false, tooltip won't automatically transition, it must be manually shown/hidden
            fadeIn: 0, //fade in, in milliseconds ("fast, "slow", etc may also be used)
            fadeOut: 0, //fade out, in milliseconds ("fast, "slow", etc may also be used)
            appendTip: document.body, //should probably not need to be overridden, but could be useful if you require a tip that remains relative to an exact point
            degrade: false, //if true, in IE6 tooltip will degrade to a title attribute message
            offsetY: 10, //offsetY and offsetX properties designate position from the cursor
            offsetX: 1,
            style: {},
            className: null, //to style the tooltip externally, pass a className or id
            id: null,
            callBefore: function(tooltip, node, settings){
            }, //called when mouse enters the area
            callAfter: function(tooltip, node, settings){
            }, //called when mouse leaves the area (same as "callback" option)
            clickAction: function(tooltip, node){
                $(tooltip).hide();
            }, //called when the element is clicked, with access to tooltip
            delay: 0, //delay (in milliseconds)before tooltip appears and callBefore executes
            timeout: 0 //delay (in milliseconds)before tooltip transitions away, and callAfter executes
        }, o ||
        {});

        if (!o.style && typeof o.style != "object") {
            o.style = {};
            o.style.zIndex = "1000";
        }
        else {
            o.style = $.extend({ //the default style rules of the tooltip
                border: "1px solid gray",
                background: "#edeef0",
                color: "#000",
                padding: "10px",
                zIndex: "1000",
                textAlign: "left"
            }, o.style ||
            {});
        }

        if (typeof callback == "function")
            o.callAfter = callback || o.callAfter;

        o.style.display = "none", o.style.position = "absolute"; //permanent defaults
        //private settings
        var title, timeout, timeout2, iId, over = {}, firstMove = true, hovered = false, maxed = false, tooltip = document.createElement('div'), ie6 = (typeof document.body.style.maxWidth == "undefined") ? true : false, talk = (typeof $.talk == "function" && typeof $.listen == "function") ? true : false;

        if (o.id)
            tooltip.id = o.id;
        if (o.className)
            tooltip.className = o.className;

        o.degrade = (o.degrade && ie6) ? true : false; //only degrades if also IE6
        for (var p in o.style)//apply styles to tooltip
             tooltip.style[p] = o.style[p];

        function fillTooltip(condition){
            if (condition) {
                if (o.degrade)//replace html characters for proper degradation to title attribute
                    $(tooltip).html(o.content.replace(/<\/?[^>]+>/gi, ''));
                else //otherwise just fill the tooltip with content
                     $(tooltip).html(o.content);
            }
        }

        if (o.ajax) { //if o.ajax is selected, this will fill and thus override o.content
            $.get(o.ajax, function(data){
                if (data)
                    o.content = data;
                fillTooltip(o.content);
            });
        }

        function offConditions(that){
            function _offActions(that){
                if (title && !o.content) {
                    title = "";
                }
            }
            function _execute(){
                if (!hovered && o.auto) {
                    clearInterval(iId);
                    if (o.fadeOut) {
                        $(tooltip).fadeOut(o.fadeOut, function(){
                            _offActions(that);
                        });
                    }
                    else {
                        _offActions(that);
                        tooltip.style.display = "none";
                    }
                }
                if (typeof o.callAfter == "function")
                    o.callAfter(tooltip, that, o);
                if (talk)
                    o = $.listen(o);
            }
            if (o.timeout > 0) {
                timeout2 = setTimeout(function(){
                    _execute();
                }, o.timeout);
            }
            else {
                _execute();
            }
        }

        $(tooltip).hover(function(){
            hovered = true;
        }, function(){
            hovered = false;
            offConditions(over);
        });

        //initialize
        if (talk) { //A "channel" for plugins to "talk" to each other, and callbacks to manipulate settings
            o.key = tooltip;
            o.plugin = "wTooltip";
            o.channel = "wayfarer";
            $.talk(o);
        }

        fillTooltip(o.content && !o.ajax);
        $(tooltip).appendTo(o.appendTip);

        return this.each(function(){ //returns the element chain
            $(this).hover(function(){
                var that = this;
                clearTimeout(timeout2);
                if ((this.title || this.titleMemKeep) && !o.degrade && !o.content) {
                    title = this.title || this.titleMemKeep;
                    if(this.title) {
                        this.titleMemKeep = this.title;
                        this.title = "";
                    }
                }
                if (o.content && o.degrade)
                    this.title = tooltip.innerHTML;

                function _execute(){
                    if (typeof o.callBefore == "function")
                        o.callBefore(tooltip, that, o);
                    if (talk)
                        o = $.listen(o); //ping for new settings

                    var display;
                    if (o.content) {
                        if (!o.degrade)
                            display = "block";
                    }
                    else
                        if (title && !o.degrade) {
                            $(tooltip).html(unescape(title));
                            display = "block";
                            title = "";
                        }
                        else {
                            display = "none";
                        }
                    if (o.auto) {
                        if (display == "block" && o.fadeIn)
                            $(tooltip).fadeIn(o.fadeIn);
                        else
                            tooltip.style.display = display;
                    }
                }

                if (o.delay > 0) {
                    timeout = setTimeout(function(){
                        _execute();
                    }, o.delay);
                }
                else {
                    _execute();
                }
            }, function() {
                clearTimeout(timeout);
                var that = this;
                firstMove = true;
                if (!o.follow || maxed || ((o.offsetX < 0 && (0 - o.offsetX < $(tooltip).outerWidth())) && (o.offsetY > 0 && 0 - o.offsetY < $(tooltip).outerHeight()))) {
                    setTimeout(function(){
                        iId = setInterval(function(){
                            offConditions(that)
                        }, 1)
                    }, 1);
                }
                else {
                    offConditions(this);
                }
            });

            $(this).mousemove(function(e){
                over = this; //tracks the event trigger in the plugin-global "over"
                if (o.follow || firstMove) {
                    var scrollY = $(window).scrollTop(), scrollX = $(window).scrollLeft(), top = e.clientY + scrollY + o.offsetY, left = e.clientX + scrollX + o.offsetX, outerH = $(o.appendTip).outerHeight(), innerH = $(o.appendTip).innerHeight(), maxLeft = $(window).width() + scrollX - $(tooltip).outerWidth(), maxTop = $(window).height() + scrollY - $(tooltip).outerHeight();

                    top = (outerH > innerH) ? top - (outerH - innerH) : top; //if appended area (usually BODY) has a border on top, adjust
                    maxed = (top > maxTop || left > maxLeft) ? true : false;

                    if (left - scrollX <= 0 && o.offsetX < 0)
                        left = scrollX;
                    else
                        if (left > maxLeft)
                            left = maxLeft;
                    if (top - scrollY <= 0 && o.offsetY < 0)
                        top = scrollY;
                    else
                        if (top > maxTop)
                            top = maxTop;

                    tooltip.style.top = top + "px";
                    tooltip.style.left = left + "px";
                    firstMove = false;
                }
            });

            if (typeof o.clickAction == "function") {
                $(this).click(function(){
                    o.clickAction(tooltip, this);
                });
            }
        });
    }
})(jQuery);

function addToFavorites()
{    
	var success=false;
	
	// try each until all fail...
 
	try {
		// IE
		window.external.AddFavorite(window.location, document.title); 
		success=true;
	} catch(e) {}
	
	try {
		if (success == false)
		{
			// Firefox
			window.sidebar.addPanel(document.title,location.href,'');
			success=true;
		}
	} catch(e) {}      
	
	if(!success)
	{
		alert("Bookmarking not supported\r\nIn your current browser.\r\n\r\nPress CTRL+D, or CMD+D\r\nto manually bookmark this page.");
	}
}  

/*
// Drop down menu javascript
var jsddm_timeout    = 500;
var jsddm_closetimer = 0;
var jsddm_ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   jsddm_ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

function jsddm_close()
{  if(jsddm_ddmenuitem) jsddm_ddmenuitem.css('visibility', 'hidden');}

function jsddm_timer()
{  jsddm_closetimer = window.setTimeout(jsddm_close, jsddm_timeout);}

function jsddm_canceltimer()
{  if(jsddm_closetimer)
   {  window.clearTimeout(jsddm_closetimer);
      jsddm_closetimer = null;}}

$(document).ready(function()
{  $('##jsddm > li').bind('mouseover', jsddm_open)
   $('##jsddm > li').bind('mouseout',  jsddm_timer)});

document.onclick = jsddm_close;			
*/
