function CheckEmailAndPasswordMatch(MyForm)
{
ErrorMessage='';
CurrentEmail=MyForm.Email.value;
if(CurrentEmail == '' || CurrentEmail == ' ' || CurrentEmail == '  ')
	{
	
	ErrorMessage+='Please Fill in Email\n';
	}
PassOne=MyForm.Pass.value;
PassTwo=MyForm.ConfirmPass.value;
if(PassOne != PassTwo && PassOne!= '' && PassOne!= ' ' && PassOne!= '  ')
	{
	ErrorMessage+='Passwords do not match please retype and try again.\n';	
	}
	
if(ErrorMessage == '')
	{
	MyForm.submit();
	}
else
	{
	alert(ErrorMessage);
	}
}

function LoadRecentlyViewed(SKU)
{
script = document.createElement( 'script' );
GoLoc='https://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=GetRecentlyViewed&SKU='+SKU;
//alert(GoLoc);
script.src = GoLoc;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

function doUnload()
{
	//openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){
	openPopWin("MiniWin.html", 300, 300, "", 400, 300);
	popWin.focus();
}

function movepic(img_name,img_src) {
window.document.images['ImgSwapper'].src=img_src;
}

function CheckthatItemWasSelected(NumItems)
{var Flag=0;
var alertText;
	for(i=0; i<document.forms[1].elements.length; i++){
     if(document.forms[1].elements[i].type == "checkbox")
     	{
     	if(document.forms[1].elements[i].checked)
      	Flag=1;
      }
   }  
if(Flag == 1)
	{
	document.forms[1].submit();
	}
else
	{
	ErrorMessage='Please check item you want to return before continuing.';
	alert(ErrorMessage);
	}
	
}


function CheckEntryForm(MyForm)
{
ErrorMessage='';
Email=MyForm.Email.value;
if(Email == '')
	{
	//document.getElementById('Code').className = 'redTD';
	ErrorMessage+='Please Enter Email address.\n';
	}	
Code=MyForm.Code.value;
if(Code != '123keen')
	{
	//document.getElementById('Code').className = 'redTD';
	ErrorMessage+='Please Enter Correct Security Code\n';
	}	
if(ErrorMessage == '')
	{
	MyForm.submit();
	}
else
	{
	alert(ErrorMessage);
	}
}


function CheckReturnForm(MyForm)
{
//Go through each item to make sure return reason is selected
NumItems=MyForm.NumItems.value;
Count=1;
ErrorMessage='';
while(Count<=NumItems)
	{
	varname='RetCode'+Count;
	RetCode=eval('document.ReturnForm.'+varname+'.options[document.ReturnForm.RetCode'+Count+'.options.selectedIndex].value');
	if(RetCode=='')
		{
		//alert(RetCode);
		document.getElementById(varname).className = 'redTD';
		ErrorMessage+='Please select a reason for item '+Count+' of your return.\n';
		}	
	Count++;
	}

OrderNum=document.ReturnForm.OrderNumber.value




var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
CardType='';
	if(MyForm.CardType[0].checked)
		CardType='Visa';
	if(MyForm.CardType[1].checked)
		CardType='MasterCard';
	if(MyForm.CardType[2].checked)
		CardType='Discover';
	if(MyForm.CardType[3].checked)
		CardType='AmExpress';
		
	if(CardType =='')
		{
		document.getElementById('CardTypes').className = 'redTD';
		ErrorMessage+='Please Choose Card Type\n';
		}
	CCNum1=MyForm.CCNum1.value;
	if(CCNum1 == '')
		{
		document.getElementById('CardNum').className = 'redTD';
		ErrorMessage+='Please Fill in Card Box 1\n';
		}
	CCNum2=MyForm.CCNum2.value;	
	if(CCNum2 == '')
		{
		document.getElementById('CardNum').className = 'redTD';
		ErrorMessage+='Please Fill in Card Box 2\n';
		}
	CCNum3=MyForm.CCNum3.value;	
	if(CCNum3 == '')
		{
		document.getElementById('CardNum').className = 'redTD';
		ErrorMessage+='Please Fill in Card Box 3\n';
		}
	CCNum4=MyForm.CCNum4.value;	
	if(CCNum4 == '')
		{
		document.getElementById('CardNum').className = 'redTD';
		ErrorMessage+='Please Fill in Card Box 4\n';
		}
	Last4=MyForm.CCNum4.value;
		
	FullCCNum=CCNum1+CCNum2+CCNum3+CCNum4;
	CVV2=MyForm.CVV2.value;	
	if(CVV2 == '')
		{
		document.getElementById('CVV2Num').className = 'redTD';
		ErrorMessage+='Please Fill in all cvv2\n';
		}
	MonthExp=MyForm.MonthExp.value;	
	YearExp=MyForm.YearExp.value;	
	if(MonthExp <= curr_month)
		{
		if(curr_year == YearExp)
			{
			document.getElementById('ExpireDate').className = 'redTD';
			ErrorMessage+='Please Use a Card that is not expired.\n';
			}
		}


FirstName=MyForm.FirstName.value;
LastName=MyForm.LastName.value;
Address=MyForm.Address.value;
City=MyForm.City.value;
State=MyForm.ShipState.value;
Zip=MyForm.Zip.value;
if(FirstName == '')
	{
	document.getElementById('ShipFirstName').className = 'redTD';
	ErrorMessage+='Please enter First Name to continue.\n';
	}	
if(LastName == '')
	{
	document.getElementById('ShipLastName').className = 'redTD';
	ErrorMessage+='Please enter Last Name to continue.\n';
	}	
if(Address == '')
	{
	document.getElementById('ShipAddress').className = 'redTD';
	ErrorMessage+='Please enter Address to continue.\n';
	}	
if(City == '')
	{
	document.getElementById('ShipCity').className = 'redTD';
	ErrorMessage+='Please enter City to continue.\n';
	}	
if(State == '')
	{
	document.getElementById('ShipState').className = 'redTD';
	ErrorMessage+='Please Choose state before continuing.\n';
	}	
if(Zip == '')
	{
	document.getElementById('ShipZip').className = 'redTD';
	ErrorMessage+='Please enter Zip to continue.\n';
	}	
if(ErrorMessage == '')
	{
	MyForm.submit();
	}
else
	{
	alert(ErrorMessage);
	}
}



function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


var ns4 = (navigator.appName.indexOf("Netscape")>=0 
          && parseFloat(navigator.appVersion) >= 4 
          && parseFloat(navigator.appVersion) < 5)? true : false;
var ns6 = (parseFloat(navigator.appVersion) >= 5 
          && navigator.appName.indexOf("Netscape")>=0 )? true: false;
var ns = (document.layers)? true:false;
var ie = (document.all)? true:false;


function getElLeft(el) {
    if (ns4) {return el.pageX;} 
    else {
        xPos = el.offsetLeft;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            xPos += tempEl.offsetLeft;
              tempEl = tempEl.offsetParent;
        }
        return xPos;
    }
}
function getElTop(el) {
    if (ns4) {return el.pageY;} 
    else {
        yPos = el.offsetTop;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            yPos += tempEl.offsetTop;
              tempEl = tempEl.offsetParent;
        }
        return yPos;
    }
}

//Display a named menu, at the position of another object
function display_menu(ClickedItem,named)
{
	//get the named menu
	//var menu_element = document.getElementById(named);
	//override the 'display:none;' style attribute
	document.getElementById(named).style.display = "";
	LeftSpot=getElLeft(document.getElementById(ClickedItem));
	TopSpot=getElTop(document.getElementById(ClickedItem));
	//alert('Left = '+LeftSpot);
	//alert('top = '+TopSpot);
	//get the placement of the element that invoked the menu...
	//var placement = findPos(parent);
	//...and put the menu there
	document.getElementById(named).style.left =LeftSpot+'px';
	document.getElementById(named).style.top =TopSpot+'px';
}

//Hide a named menu
function hide_menu(named)
{
	//get the named menu
	var menu_element = document.getElementById(named);
	//hide it with a style attribute
	menu_element.style.display = "none";
}

function CheckContactUsForm(MyForm)
{
ErrorMessage='';
Code=MyForm.Code.value;
if(Code != '123keen')
	{
	//document.getElementById('Code').className = 'redTD';
	ErrorMessage+='Please Enter Correct Security Code\n';
	}	
if(ErrorMessage == '')
	{
	MyForm.submit();
	}
else
	{
	alert(ErrorMessage);
	}
}

function TrakIt(ThisSrc)
{
script = document.createElement( 'script' );
script.src = 'https://www.dynamicfootwear.com/phpscripts/pagetraker.php?Page='+ThisSrc;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

function SizeSearch(Gender,Size)
{
document.getElementById('InvSizes').innerHTML = "Getting All available Sizes...<img src=http://www.dynamicfootwear.com/images/big-roller.gif>";	

var url ='http://www.dynamicfootwear.com/phpscripts/AvailableSizeSearch.php?action=go&Gender='+Gender+'&Size='+Size;	
script = document.createElement( 'script' );
script.src = url;
document.getElementsByTagName( 'head' )[0].appendChild( script );	
}

function SwapColor(ColorCode,Style,ColorDesc,Gender)
{
if(document.getElementById('ColorName'))
	{document.getElementById('ColorName').innerHTML = 'Showing '+ColorDesc;}
ProdN=Gender+' '+Style+' '+ColorDesc;
if(document.getElementById('ProductName'))
	{document.getElementById('ProductName').innerHTML = ProdN;}
//alert(Style);
if(document.getElementById('ImgSwap'))
	{document.getElementById('ImgSwap').innerHTML = "Getting New Image...";	}
GetAvailableSizes(ColorCode,Style,Gender);
script = document.createElement( 'script' );
script.src = 'http://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=GetNewColorPic&ColorCode='+ColorCode+'&Style='+Style+'&Gender='+Gender;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

function SwapView(ColorCode,Style,Gender,View)
{
document.getElementById('ImgSwap').innerHTML = "Getting New Image...";	
script = document.createElement( 'script' );
script.src = 'http://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=GetNewViewPic&ColorCode='+ColorCode+'&Style='+Style+'&Gender='+Gender+'&View='+View;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

function GetSelectedColorName(ColorDesc)
{
document.getElementById('ColorName').innerHTML = 'Showing '+ColorDesc;
}

function GetColorMini(ColorCode,Style,ColorDescription,Gender)
{
script = document.createElement( 'script' );
script.src = 'http://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=GetNewColorPicMini&ColorCode='+ColorCode+'&Style='+Style+'&Gender='+Gender+'&DivID='+Style;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}


function GetAvailableSizes(ColorCode,Style,Gender)
{
//alert(ColorCode);
document.getElementById('AvailableSizes').innerHTML = 'Please wait, loading available sizes...';
script = document.createElement( 'script' );
script.src = 'https://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=AvailableSizes&ColorCode='+ColorCode+'&Style='+Style+'&Gender='+Gender;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}



function SelectSize(SKU)
{
//alert(SKU);
if(SKU != '')
	{document.getElementById('SelectedSize').innerHTML = '<input type=hidden id=UPC12digit name=sku value='+SKU+'>';}

}

var whosChanged = null;
function ChangeColor(el)
{
el.style.backgroundColor = "#FE3000";
el.style.color = "#000000";
if (whosChanged != null)
{
whosChanged.style.backgroundColor = ""
whosChanged.style.color = ""
}
whosChanged = el;
}



var popWin = null    // use this when referring to pop-up window
var winCount = 0
var winName = "popWin"

function openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){
  var d_winLeft = 20  // default, pixels from screen left to window left
  var d_winTop = 20   // default, pixels from screen top to window top
  winName = "popWin" + winCount++ //unique name for each pop-up window
  closePopWin()           // close any previously opened pop-up window
  if (openPopWin.arguments.length >= 4)  // any additional features?
    winFeatures = "," + winFeatures+',';
  else
    winFeatures = ""
  //window.open('jex5.htm','mywindow','width=400,height=200,left=0,top=100,screenX=0,screenY=100')
  if (openPopWin.arguments.length == 6)  // location specified
    winFeatures += 'width='+winWidth+',height='+ winHeight+',left='+ winLeft+',top='+ winTop;
  else
    winFeatures += 'width='+winWidth+',height='+ winHeight+',left='+d_winLeft+',top='+ d_winTop
  //alert(winFeatures);
  popWin = window.open(winURL, winName, winFeatures)
  }
  
  
function closePopWin(){    // close pop-up window if it is open
  if (navigator.appName != "Microsoft Internet Explorer"
      || parseInt(navigator.appVersion) >=4) //do not close if early IE
    if(popWin != null) if(!popWin.closed) popWin.close()
  }


function getLocation(winWidth, winHeight, winLeft, winTop){
  return ""
  }
  


function ParseQuerystring(qs) 
{ 
//alert('inside Parse');
// Using this function to grab query string and check for Commission Junction variable ref=cj
	this.params = {};
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) 
		{
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
			if(name == 'ref' || name == 'PID')			
				{
				//Post Cookie
				//alert('posting cj cookie');
				var exdate=new Date();
				var c_name='ref';
				var expiredays=45;
				exdate.setDate(exdate.getDate()+expiredays);
				//Setting cookie for CJ to expire in 45 days
				document.cookie=c_name+ "=" +escape(value)+
				((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
				//Track where visitor came from
				script = document.createElement( 'script' );
				//Loc='https://www.clogscentral.com/phpscripts/pagetraker2.php';
				Loc='https://www.dynamicfootwear.com/phpscripts/pagetraker2.php?Page='+window.location+'&Referer='+document.referrer;
				//alert(Loc);
				script.src = Loc;
				document.getElementsByTagName( 'head' )[0].appendChild( script );
				}
			if(this.params['Gender'] != "")
				{
				//alert(this.params['Gender']);
				SwapColor(this.params['ColorCode'],this.params['Style'],this.params['ColorDesc'],this.params['Gender']);
				//SwapColorForDrop(this.params['ColorCode'],this.params['Style'],this.params['ColorDesc'],this.params['Gender'],this.params['Cat'],this.params['Price']);
				//alert(this.params['ColorCode']);
				//alert(this.params['Style']);
				//alert(this.params['Gender']);
				//alert(this.params['Cat']);
				//alert(this.params['Price']);
				}
		}
}

function Redir404Page()
{
	//alert(document.location.href); 
	
	//var str=document.location.href;
	//URLPieces=str.split("/");
	
	//NumPiecesInURL=URLPieces.length;
	//NumPiecesInURL=NumPiecesInURL-1;
	//LastURLPiece=URLPieces[NumPiecesInURL];
	//script = document.createElement( 'script' );
	//Loc='https://www.dynamicfootwear.com/phpscripts/ProductHandler.php?action=LookForProduct&URLPiece='+LastURLPiece;
	//script.src = Loc;
	//document.getElementsByTagName( 'head' )[0].appendChild( script );
}

////////////////////////////////////////////////////////////
///////////Functions for Slide out when add to cart
function animate(elementID, newLeft, newTop, newWidth,
      newHeight, time, callback)
{
  var el = document.getElementById(elementID);
  if(el == null)
    return;
 
  var cLeft = parseInt(el.style.left);
  var cTop = parseInt(el.style.top);
  var cWidth = parseInt(el.style.width);
  var cHeight = parseInt(el.style.height);
 
  var totalFrames = 1;
  if(time> 0)
    totalFrames = time/40;

  var fLeft = newLeft - cLeft;
  if(fLeft != 0)
    fLeft /= totalFrames;
 
  var fTop = newTop - cTop;
  if(fTop != 0)
    fTop /= totalFrames;
 
  var fWidth = newWidth - cWidth;
  if(fWidth != 0)
    fWidth /= totalFrames;
 
  var fHeight = newHeight - cHeight;
  if(fHeight != 0)
    fHeight /= totalFrames;
   
  doFrame(elementID, cLeft, newLeft, fLeft,
      cTop, newTop, fTop, cWidth, newWidth, fWidth,
      cHeight, newHeight, fHeight, callback);
}

function doFrame(eID, cLeft, nLeft, fLeft,
      cTop, nTop, fTop, cWidth, nWidth, fWidth,
      cHeight, nHeight, fHeight, callback)
{
   var el = document.getElementById(eID);
   if(el == null)
     return;

  cLeft = moveSingleVal(cLeft, nLeft, fLeft);
  cTop = moveSingleVal(cTop, nTop, fTop);
  cWidth = moveSingleVal(cWidth, nWidth, fWidth);
  cHeight = moveSingleVal(cHeight, nHeight, fHeight);

  el.style.left = Math.round(cLeft) + 'px';
  el.style.top = Math.round(cTop) + 'px';
  el.style.width = Math.round(cWidth) + 'px';
  el.style.height = Math.round(cHeight) + 'px';
 
  if(cLeft == nLeft && cTop == nTop && cHeight == nHeight
    && cWidth == nWidth)
  {
    if(callback != null)
      callback();
    return;
  }
   
  setTimeout( 'doFrame("'+eID+'",'+cLeft+','+nLeft+','+fLeft+','
    +cTop+','+nTop+','+fTop+','+cWidth+','+nWidth+','+fWidth+','
    +cHeight+','+nHeight+','+fHeight+','+callback+')', 40);
}

function moveSingleVal(currentVal, finalVal, frameAmt)
{
  if(frameAmt == 0 || currentVal == finalVal)
    return finalVal;
 
  currentVal += frameAmt;
  if((frameAmt> 0 && currentVal>= finalVal)
    || (frameAmt <0 && currentVal <= finalVal))
  {
    return finalVal;
  }
  return currentVal;
}


function  slideDown(elementId)
{
//left: 550px;
//top: 10px;
//id of the element,left position,top position,width,height,animation length (in milliseconds),callback function
LeftPosition=SetLeftPosition();
var element = document.getElementById(elementId);
animate(elementId, LeftPosition, 90, 230, 220, 800, null);
element.down = true;
element.up = false;

}

function SlideUp(elementId)
{
var element = document.getElementById(elementId);
//id of the element,left position,top position,width,height,animation length (in milliseconds),callback function
LeftPosition=SetLeftPosition();
animate(elementId, LeftPosition, 90, 230, 0, 800, null);
element.up = true;
element.down = false;

}

///////////////////////////////////////////////////////////
////////// End Slide out when add to cart


function SetLeftPosition()
{
var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
 winW = document.body.offsetWidth;
 winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 winW = document.documentElement.offsetWidth;
 winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
 winW = window.innerWidth;
 winH = window.innerHeight;
}


LeftPosition=winW-340;
return(LeftPosition);
}


// SpryTabbedPanels.js - version 0.7 - Spry Pre-Release 1.6.1
//
// Copyright (c) 2006. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

(function() { // BeginSpryComponent

if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {};

Spry.Widget.TabbedPanels = function(element, opts)
{
	this.element = this.getElement(element);
	this.defaultTab = 0; // Show the first panel by default.
	this.tabSelectedClass = "TabbedPanelsTabSelected";
	this.tabHoverClass = "TabbedPanelsTabHover";
	this.tabFocusedClass = "TabbedPanelsTabFocused";
	this.panelVisibleClass = "TabbedPanelsContentVisible";
	this.focusElement = null;
	this.hasFocus = false;
	this.currentTabIndex = 0;
	this.enableKeyboardNavigation = true;
	this.nextPanelKeyCode = Spry.Widget.TabbedPanels.KEY_RIGHT;
	this.previousPanelKeyCode = Spry.Widget.TabbedPanels.KEY_LEFT;

	Spry.Widget.TabbedPanels.setOptions(this, opts);

	// If the defaultTab is expressed as a number/index, convert
	// it to an element.

	if (typeof (this.defaultTab) == "number")
	{
		if (this.defaultTab < 0)
			this.defaultTab = 0;
		else
		{
			var count = this.getTabbedPanelCount();
			if (this.defaultTab >= count)
				this.defaultTab = (count > 1) ? (count - 1) : 0;
		}

		this.defaultTab = this.getTabs()[this.defaultTab];
	}

	// The defaultTab property is supposed to be the tab element for the tab content
	// to show by default. The caller is allowed to pass in the element itself or the
	// element's id, so we need to convert the current value to an element if necessary.

	if (this.defaultTab)
		this.defaultTab = this.getElement(this.defaultTab);

	this.attachBehaviors();
};

Spry.Widget.TabbedPanels.prototype.getElement = function(ele)
{
	if (ele && typeof ele == "string")
		return document.getElementById(ele);
	return ele;
};

Spry.Widget.TabbedPanels.prototype.getElementChildren = function(element)
{
	var children = [];
	var child = element.firstChild;
	while (child)
	{
		if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
			children.push(child);
		child = child.nextSibling;
	}
	return children;
};

Spry.Widget.TabbedPanels.prototype.addClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
		return;
	ele.className += (ele.className ? " " : "") + className;
};

Spry.Widget.TabbedPanels.prototype.removeClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
		return;
	ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};

Spry.Widget.TabbedPanels.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
	if (!optionsObj)
		return;
	for (var optionName in optionsObj)
	{
		if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
			continue;
		obj[optionName] = optionsObj[optionName];
	}
};

Spry.Widget.TabbedPanels.prototype.getTabGroup = function()
{
	if (this.element)
	{
		var children = this.getElementChildren(this.element);
		if (children.length)
			return children[0];
	}
	return null;
};

Spry.Widget.TabbedPanels.prototype.getTabs = function()
{
	var tabs = [];
	var tg = this.getTabGroup();
	if (tg)
		tabs = this.getElementChildren(tg);
	return tabs;
};

Spry.Widget.TabbedPanels.prototype.getContentPanelGroup = function()
{
	if (this.element)
	{
		var children = this.getElementChildren(this.element);
		if (children.length > 1)
			return children[1];
	}
	return null;
};

Spry.Widget.TabbedPanels.prototype.getContentPanels = function()
{
	var panels = [];
	var pg = this.getContentPanelGroup();
	if (pg)
		panels = this.getElementChildren(pg);
	return panels;
};

Spry.Widget.TabbedPanels.prototype.getIndex = function(ele, arr)
{
	ele = this.getElement(ele);
	if (ele && arr && arr.length)
	{
		for (var i = 0; i < arr.length; i++)
		{
			if (ele == arr[i])
				return i;
		}
	}
	return -1;
};

Spry.Widget.TabbedPanels.prototype.getTabIndex = function(ele)
{
	var i = this.getIndex(ele, this.getTabs());
	if (i < 0)
		i = this.getIndex(ele, this.getContentPanels());
	return i;
};

Spry.Widget.TabbedPanels.prototype.getCurrentTabIndex = function()
{
	return this.currentTabIndex;
};

Spry.Widget.TabbedPanels.prototype.getTabbedPanelCount = function(ele)
{
	return Math.min(this.getTabs().length, this.getContentPanels().length);
};

Spry.Widget.TabbedPanels.addEventListener = function(element, eventType, handler, capture)
{
	try
	{
		if (element.addEventListener)
			element.addEventListener(eventType, handler, capture);
		else if (element.attachEvent)
			element.attachEvent("on" + eventType, handler);
	}
	catch (e) {}
};

Spry.Widget.TabbedPanels.prototype.cancelEvent = function(e)
{
	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	if (e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;

	return false;
};

Spry.Widget.TabbedPanels.prototype.onTabClick = function(e, tab)
{
	this.showPanel(tab);
	return this.cancelEvent(e);
};

Spry.Widget.TabbedPanels.prototype.onTabMouseOver = function(e, tab)
{
	this.addClassName(tab, this.tabHoverClass);
	return false;
};

Spry.Widget.TabbedPanels.prototype.onTabMouseOut = function(e, tab)
{
	this.removeClassName(tab, this.tabHoverClass);
	return false;
};

Spry.Widget.TabbedPanels.prototype.onTabFocus = function(e, tab)
{
	this.hasFocus = true;
	this.addClassName(tab, this.tabFocusedClass);
	return false;
};

Spry.Widget.TabbedPanels.prototype.onTabBlur = function(e, tab)
{
	this.hasFocus = false;
	this.removeClassName(tab, this.tabFocusedClass);
	return false;
};

Spry.Widget.TabbedPanels.KEY_UP = 38;
Spry.Widget.TabbedPanels.KEY_DOWN = 40;
Spry.Widget.TabbedPanels.KEY_LEFT = 37;
Spry.Widget.TabbedPanels.KEY_RIGHT = 39;



Spry.Widget.TabbedPanels.prototype.onTabKeyDown = function(e, tab)
{
	var key = e.keyCode;
	if (!this.hasFocus || (key != this.previousPanelKeyCode && key != this.nextPanelKeyCode))
		return true;

	var tabs = this.getTabs();
	for (var i =0; i < tabs.length; i++)
		if (tabs[i] == tab)
		{
			var el = false;
			if (key == this.previousPanelKeyCode && i > 0)
				el = tabs[i-1];
			else if (key == this.nextPanelKeyCode && i < tabs.length-1)
				el = tabs[i+1];

			if (el)
			{
				this.showPanel(el);
				el.focus();
				break;
			}
		}

	return this.cancelEvent(e);
};

Spry.Widget.TabbedPanels.prototype.preorderTraversal = function(root, func)
{
	var stopTraversal = false;
	if (root)
	{
		stopTraversal = func(root);
		if (root.hasChildNodes())
		{
			var child = root.firstChild;
			while (!stopTraversal && child)
			{
				stopTraversal = this.preorderTraversal(child, func);
				try { child = child.nextSibling; } catch (e) { child = null; }
			}
		}
	}
	return stopTraversal;
};

Spry.Widget.TabbedPanels.prototype.addPanelEventListeners = function(tab, panel)
{
	var self = this;
	Spry.Widget.TabbedPanels.addEventListener(tab, "click", function(e) { return self.onTabClick(e, tab); }, false);
	Spry.Widget.TabbedPanels.addEventListener(tab, "mouseover", function(e) { return self.onTabMouseOver(e, tab); }, false);
	Spry.Widget.TabbedPanels.addEventListener(tab, "mouseout", function(e) { return self.onTabMouseOut(e, tab); }, false);

	if (this.enableKeyboardNavigation)
	{
		// XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
		// rely on adding the tabindex attribute if it is missing to enable keyboard navigation
		// by default.

		// Find the first element within the tab container that has a tabindex or the first
		// anchor tag.
		
		var tabIndexEle = null;
		var tabAnchorEle = null;

		this.preorderTraversal(tab, function(node) {
			if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
			{
				var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
				if (tabIndexAttr)
				{
					tabIndexEle = node;
					return true;
				}
				if (!tabAnchorEle && node.nodeName.toLowerCase() == "a")
					tabAnchorEle = node;
			}
			return false;
		});

		if (tabIndexEle)
			this.focusElement = tabIndexEle;
		else if (tabAnchorEle)
			this.focusElement = tabAnchorEle;

		if (this.focusElement)
		{
			Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "focus", function(e) { return self.onTabFocus(e, tab); }, false);
			Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "blur", function(e) { return self.onTabBlur(e, tab); }, false);
			Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "keydown", function(e) { return self.onTabKeyDown(e, tab); }, false);
		}
	}
};

Spry.Widget.TabbedPanels.prototype.showPanel = function(elementOrIndex)
{
	var tpIndex = -1;
	
	if (typeof elementOrIndex == "number")
		tpIndex = elementOrIndex;
	else // Must be the element for the tab or content panel.
		tpIndex = this.getTabIndex(elementOrIndex);
	
	if (!tpIndex < 0 || tpIndex >= this.getTabbedPanelCount())
		return;

	var tabs = this.getTabs();
	var panels = this.getContentPanels();

	var numTabbedPanels = Math.max(tabs.length, panels.length);

	for (var i = 0; i < numTabbedPanels; i++)
	{
		if (i != tpIndex)
		{
			if (tabs[i])
				this.removeClassName(tabs[i], this.tabSelectedClass);
			if (panels[i])
			{
				this.removeClassName(panels[i], this.panelVisibleClass);
				panels[i].style.display = "none";
			}
		}
	}

	this.addClassName(tabs[tpIndex], this.tabSelectedClass);
	this.addClassName(panels[tpIndex], this.panelVisibleClass);
	panels[tpIndex].style.display = "block";

	this.currentTabIndex = tpIndex;
};

Spry.Widget.TabbedPanels.prototype.attachBehaviors = function(element)
{
	var tabs = this.getTabs();
	var panels = this.getContentPanels();
	var panelCount = this.getTabbedPanelCount();

	for (var i = 0; i < panelCount; i++)
		this.addPanelEventListeners(tabs[i], panels[i]);

	this.showPanel(this.defaultTab);
};

})(); // EndSpryComponent


