// Attach events for store
if(typeof $ != 'undefined') {
	$(document).ready(function(){
		
		/***********************************************
		/ Enable brand bar
		/**********************************************/
		$('#BrandBar img[sortvalue]').click(function(e){
			$('#CategorySortBy').val($(this).attr('sortvalue'));
			$('#FindMyBrand').removeAttr('disabled');
			$('#frmSort').submit();
		});
		$('#BrandIconToggle').toggle(
			function(e){
				$(this).html('<img src="/shared/images/icon_menu_collapse.png" /> Hide more brands');
				$('#BrandBar ul').animate( { height:$('#BrandBar ul').attr('elemHeight')}, 500 );
			},
			function(e){
				$(this).html('See more brands <img src="/shared/images/icon_menu_expand.png" />');
				$('#BrandBar ul').animate( { height:154}, 500 );
		});
		
		/***********************************************
		/ Enable listMenu's
		/**********************************************/
		// Set initial value
		$('li.listMenu_Label > span').html('Select One');
		
		// Events to handle sub-menus
		$('ul.listMenu li:has(ul)').mouseenter(function(){
			$(this).children('ul').show();
		}).mouseleave(function(){
			$(this).find('li').removeClass('listMenu_Hovered');
			$(this).children('ul').hide();
		}).filter(':not(:has(span))').addClass('listMenu_Submenu');
		
		// Attach classes to handle overflow
		$('ul.listMenu ul:not(:has(ul))').addClass('listMenu_Overflow');
		
		// Add hover effects to menu
		$('ul.listMenu li:not(.listMenu_Disabled)').hover(function(){
			$(this).addClass('listMenu_Hovered');
		},function(){
			$(this).removeClass('listMenu_Hovered');
		});
		
		
		/***********************************************
		/ Enable tooltips
		/**********************************************/
		// Default tooltip styles
		$.fn.qtip.styles.standard = { // Last part is the name of the style
		   'font-size': 11,
		   title: {'font-size': 11, 'text-align': 'center'},
		   name: 'dark' // Inherit the rest of the attributes from the preset dark style
		}
		
		// General title tips
		$('.titleTip').each(function(){
			$(this).qtip({
				position: { adjust: { screen: true } },
				style: {
					tip: 'leftBottom',
					border: { radius: 5 },
					name: 'standard'
				},
				hide: {
					when: 'mouseout',
					fixed: true,
					delay: 500
				}
			});
		});
		
		// Target elem tips
		$('.targetTip[tiptarget]').each(function(){
			$(this).qtip({
				content: $('#' + $(this).attr('tiptarget')),
				position: { adjust: { screen: true } },
				style: {
					width: { max: 300 },
					tip: 'leftBottom',
					border: { radius: 5 },
					name: 'standard'
				}
			});
		});
		
		// Tip for cross sell zoom
		$('.crossSoldProduct').each(function(){
			$(this).qtip({
				content: {
					text: '<img src="' + $(this).attr('tipsrc') + '">',
					title: $(this).attr('name')
				},
				position: { adjust: { screen: true } },
				style: {
					tip: 'leftBottom',
					name: 'standard'
				}
			});
		});
		
		// Tip for product zoom
		$('.catPageProductZoom').each(function(){
			$(this).qtip({
				content: '<img src="' + $(this).attr('tipsrc') + '">',
				position: {
				  corner: {
					 target: 'bottomMiddle',
					 tooltip: 'topMiddle'
				  },
				  adjust: {
					 screen: true
				  }
			   },
				style: {
					width: 250,
					height: 225,
					tip: 'topMiddle',
					name: 'standard'
				}
			});
		});
		
		// Tip for product charts
		$('.catPageProductChart, .prdPageSizeChartLink').each(function(){
			$(this).qtip({
				content: '<img src="' + $(this).attr('tipsrc') + '">',
				position: {
				  corner: {
					 target: 'bottomMiddle',
					 tooltip: 'topMiddle'
				  },
				  adjust: {
					 screen: true
				  }
			   },
				style: {
					width: { max: 900 },
					tip: 'topMiddle',
					name: 'standard'
				}
			});
		});
		
		// Tip for best price on product page
		$('#Product #BestPrice').each(function(){
			$(this).qtip({
				content: $(this).attr('tip'),
				position: {
				  corner: {
					 target: 'bottomMiddle',
					 tooltip: 'topMiddle'
				  },
				  adjust: {
					 screen: true
				  }
			   },
				style: {
					tip: 'topMiddle',
					name: 'standard'
				}
			});
		});
		
		
		/***********************************************
		/ Enable category sorting
		/**********************************************/
		$('#frmSort input[name="Filter"]').each(function(){
			if(this.value.indexOf('Brand|') >= 0){
				$('#FindBrandMenu li.listMenu_Label > span').attr('filter',this.value).html($('#FindBrandMenu li[filter="'+ this.value +'"]').attr('title'));
			}else if(this.value.indexOf('Option|Size|') >= 0){
				$('#FindSizeMenu li.listMenu_Label > span').attr('filter',this.value).html($('#FindSizeMenu li[filter="'+ this.value +'"]').attr('title'));
			}else{
				$('#SortByMenu li.listMenu_Label > span').attr('filter',this.value).html($('#SortByMenu li[filter="'+ this.value +'"]').attr('title'));
			}
		});
		$('#SortBar ul.listMenu li[clearfilter]').click(function(){
			$('#frmSort input[value="' + $(this).attr('clearfilter') + '"]').remove();
			$('#frmSort').submit();
		});
		$('#SortBar ul.listMenu li[filter]:not(:has(ul)),#BrandBar img[filter]').click(function() {
			$('#frmSort input[value*="' + $(this).attr('filter').split('|')[0] + '"]').remove();
			$('#frmSort').append('<input type="hidden" name="Filter" value="' + $(this).attr('filter') + '" />');
			$('#frmSort').submit();
		});
		$('#SortReset').click(function(){
			$('#frmSort input[name="Filter"]').remove();
			$('#frmSort').submit();
		});
	});
}


// Alter product page for alt item selection
function selectAltItemInit() {
	if($('#BuyNow')) {
		$('#BuyNow').hide();
		$('#BestPrice').hide();
		$('#WishList').hide();
		$('#EmailFriend').hide();
		$('#SelectItem').show();
		$('#frmProduct').attr('action','/shared/includes/altconsole.cfm?Action=' + top.topFrame.Action + '&OrderID=' + top.topFrame.OrderID + '&AltOrderID=' + top.topFrame.AltOrderID + '&AltID=' + top.topFrame.AltID);
	}
}

// Add to wishlist
function addToWishlist() {
	if(validateProductForm()) {
		$('#frmProduct').attr('action','/store/wishlist.cfm');
		$('#frmProduct').submit();
	}
}

// Email product to a friend
function emailFriend(StoreName,Name,SKU) {
	var mailString = 'mailto:?Subject=Check out the ' + Name + ' at ' + StoreName + '&Body=I found this at ' + StoreName + ' and thought you might be interested in it: ' + SKU + ' - ' + Name + '%0A%0AYou can see the product by clicking this link:%0A' + location.href;
	location.href = mailString;
}

// Validation for product page
function validateProductForm() {
	// Reset validation box
	var Validated = true;
	$('#prdPageValidationMessage').hide();
	$('#prdPageValidationMessage').empty();
	
	// Validate options
	if(($('#Options')) && ($('#Options').val() == 0)) {
		$('#prdPageValidationMessage').append('Please select your ' + $('#Options').attr('title'));
		$('#prdPageValidationMessage').slideDown('normal');
		Validated = false;
	}
	
	// Validate kits
	if($('.prdPageKitOptions')) {
		$('.prdPageKitOptions').each(function(i) {
			if($(this).val() == 0) {
				$('#prdPageValidationMessage').append('Please select a ' + $(this).attr('title') + ' for your kit');
				$('#prdPageValidationMessage').slideDown('normal');
				Validated = false;
				return false;
			}
		});
	}
	
	// Return if no errors
	return Validated;
}

// Selecting alt items
function selectingAltItems() {
	if (top.window.name == 'ConsoleWin') {
		return true;
	}else{
		return false;
	}
}

// Functions for product imagees (zoom etc)
function zoomImage(ImageNumber) {
	// Set image to zoom
	selectZoomImage(ImageNumber);
	
	// Fade in viewer
	$('#prdPageZoomImageViewer').fadeIn('normal');
}
function selectZoomImage(ImageNumber) {
	// Set previous and next buttons
	if (ImageNumber - 2 >= 0) {
		$('#zoomPrev').unbind('click');
		$('#zoomPrev').click(function() {
			selectZoomImage(ImageNumber - 1);
		});
		$('#zoomPrev').show();
	}else{
		$('#zoomPrev').hide();
	}
	if (ImageNumber < ZoomImageArray.length) {
		$('#zoomNext').unbind('click');
		$('#zoomNext').click(function() {
			selectZoomImage(ImageNumber + 1);
		});
		$('#zoomNext').show();
	}else{
		$('#zoomNext').hide();
	}
	
	// Reset contents and append new image to view
	$('#zoomedImage').empty();
	$('#zoomedImage').append('<img src="' + ZoomImageArray[ImageNumber - 1] + '">');
}
function selectImage(ImageNumber) {
	// Set active border
	$('#prdPageThumbImages img').each(function(i) {
		$(this).removeClass();
	});
	$('#Thumb' + ImageNumber).addClass('ActiveThumb');
	
	// Set zoom image
	$('#zoomTrigger').click(function() {
		zoomImage(ImageNumber);
	});
	
	// Fade out old image and fade in new
	$('#prdPageLargeImages img:visible').each(function(i) {
		if (this.id != 'Image' + ImageNumber) {
			$(this).fadeOut('normal', function() {
				$('#Image' + ImageNumber).fadeIn();
			});
		}
	});
}

// Disable context menu for IMG tags
document.oncontextmenu = function(e) { 
	var target;
	if(!e) e = window.event;
	target = e.target || e.srcElement;
	if(target.tagName == "IMG") {
		return false;
	}
};
function getAttribFromCss(tdObj,Attrib) {
	var returnVal = '';
	//alert(tdObj.style.height); //it is just for only inline style
	if ( tdObj.currentStyle ) {
		//alert(tdObj.currentStyle.height);
		returnVal = tdObj.currentStyle[Attrib];
	} else if ( document.defaultView.getComputedStyle){
		//alert(document.defaultView.getComputedStyle(tdObj,'') .height);
		returnVal = document.defaultView.getComputedStyle(tdObj,'')[Attrib];
	}
	return returnVal
}
function OpenViewer() {
	// Vars
	var Width = 430;
	var Height = 465;
	var URL = '';
	//Center the Window
	var left = ((screen.width - Width) / 2) - 150;
	var top = (screen.height - Height) / 2;
	//Set the Params
	var params = 'toolbar=0, scrollbars=0, location=0, statusbar=0, menubar=0, resizable=1, width='+Width+', height='+Height+', left='+left+', top = '+top+'';
	//Pop the Window
	WinName = window.open(URL, 'ZoomViewer', params);
	WinName.focus();
}
function OpenChart(ChartID) {
	// Vars
	var Width = 475;
	var Height = 425;
	var URL = '/store/viewchart.cfm?ChartID=' + ChartID;
	var left = screen.width - Width;
	var top = 0;
	//Set the Params
	var params = 'toolbar=0, scrollbars=1, location=0, statusbar=0, menubar=0, resizable=1, width='+Width+', height='+Height+', left='+left+', top = '+top+'';
	//Pop the Window
	WinName = window.open(URL, 'ChartViewer', params);
	WinName.focus();
}
function Validate() {
	var SpecialOption = 'NA';
	var KitCount = document.getElementById('KitCompCount').value;
	var RequiresValidation = document.getElementById('RequiresValidation').value;
	document.getElementById('ValidateMsg').style.display = 'none';
	//ResetMessages('Options',OptCount);
	ResetMessages('Kits',KitCount);
	
	// Only continue if we need to
	if (RequiresValidation == 1) {
		
		// Set Special Options
		if (document.getElementById('SpecialOptions')) {
			SpecialOption = document.getElementById('SpecialOptions').value;
		}
		
		// Validate Options
		for (i=0; i<1; i++) {
			if (document.getElementById('Options') != null) {
				OptionField = document.getElementById('Options');
				OptionValue = OptionField.options[OptionField.selectedIndex].value;
				ValidateMessage = document.getElementById('ValidateMsg');
				if ((OptionValue == 'NA') && (SpecialOption == 'NA')) {
					ValidateMessage.style.display = '';
					return false;
				}
			/*}else{
				ValidateMessage = document.getElementById('ValidateSpecialMsg');
				OptionValue = 'NA';*/
			}
		}
	
		// Validate Kits
		for (i=1; i<KitCount+1; i++) {
			KitField = document.getElementById('kitComp' + i);
			KitValue = KitField.options[KitField.selectedIndex].value;
			if(kitValue == 'NA') {
				ValidateMessage = document.getElementById('ValidateKitMsg' + i);
				ValidateMessage.style.display = '';
				return false;
			}
		}
	}
	return true;
}
function ResetMessages(Type,Count) {
	if (Type == 'Options') {
		for (i=0; i<Count; i++) {
			if (document.getElementById('ValidateMsg' + i) != null) {
				document.getElementById('ValidateMsg' + i).style.display = 'none';
			}	
		}
	}
	else if (Type == 'Kits') {
		for (i=0; i<Count; i++) {
			if(document.getElementById('ValidateKitMsg' + i) != null) {
				document.getElementById('ValidateKitMsg' + i).style.display = 'none';
			}
		}
	}
}
function PopUp(Width,Height,Scrolling,URL) {
	//Center the Window
	var left = (screen.width - Width) / 2;
	var top = (screen.height - Height) / 2;
	//Set the Params
	var params = 'toolbar=0, scrollbars='+Scrolling+', location=0, statusbar=0, menubar=0, resizable=1, width='+Width+', height='+Height+', left='+left+', top = '+top+'';
	//Pop the Window
	WinName = window.open(URL, 'Preview', params);
	WinName.focus();
}
function ShowHintText(theField,theHint,activeColor) {
	if (theField.value.length == 0) {
		theField.style.color = '#CCCCCC';
		theField.value = theHint;
	}
	else if (theField.value == theHint) {
		theField.style.color = activeColor;
		theField.value = '';
	}
}
function JumpToURL(URL) {
	window.self.location = URL;
}
function UpdateTextCounter(elem, max) {
	var counter = document.getElementById(elem.id + "_counter");
	var remaining = document.getElementById(elem.id + "_remaining");
	if(elem.value.length > max) {
		elem.value = elem.value.substring(0, max);
	}
	if(counter != null) {
		counter.innerHTML = elem.value.length;
	}
	if(remaining != null) {
		remaining.innerHTML = max - elem.value.length;
	}
}
function AC_AddExtension(src, ext)
{
	// Only add extension if it's not already there
	if(src.indexOf(ext) == -1) {
		if (src.indexOf('?') != -1) {
			return src.replace(/\?/, ext+'?'); 
		} else {
			return src + ext;
		}
	} else {
		return src;
	}
}
function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}