var g_miniCartTimeOut = 0;
var g_ie6 = 0;
var DOMUtils = {};
DOMUtils.applyBehaviors = function(root) {
	var baseElement = root || document.body;

	//find out if it's IE6
	if(typeof document.body.style.maxHeight === "undefined") {
		g_ie6 = 1;
	}
	
	//default values
	$('input:disabled').addClass('is-disabled');
	
	var barSearchVal = $('#barSearch input').val();
	$('#barSearch input').defaultvalue(barSearchVal);

	var fBarFrmVal = $('#fBarFrm input').val();
	$('#fBarFrm input').defaultvalue(fBarFrmVal);

	$('div.wishListOpts input').defaultvalue('Enter Name or Email Address');
	// logo mouseover
	$('body').append('<div id="barLogoHover"></div>');
	$('#bar a img').mousemove(function(e){
		$('#barLogoHover').css({'left' : e.pageX + 10 + 'px', 'top' : e.pageY + 10 + 'px'});
  	});
	var time = 0;
	$('#bar a img').hover(function(){
		 time = setTimeout("$('#barLogoHover').fadeIn('fast')",500);
	}, function(){
		clearTimeout(time);
		$('#barLogoHover').fadeOut('fast');
	});
	
	$('li.lngSel a:first-child').click(function() { $('#otherLngBx').fadeIn('fast'); });
	$('#otherLngBx p img.close').click(function() { $('#otherLngBx').fadeOut('fast'); })

	// language selector rules
	if ($('li.lngSel div.uHide a').length <= 2) {
		var curLoc = $('li.lngSel div.uHide span').text();
		var langVal = $('li.lngSel div.uHide a[href*=' + curLoc + ']').siblings('a').text();
		var langHref = $('li.lngSel div.uHide a[href*=' + curLoc + ']').siblings('a').attr('href');
		$('li.lngSel a:first-child').attr('href',langHref);
		$('li.lngSel a:first-child').text(langVal);
	}
	// feedback window controls
	if (g_ie6 > 0) {
		iconOffset = $(window).height() - 70 + $(document).scrollTop();
		$('#feedbackBx').animate({top: iconOffset + 'px'},{duration:500,queue:false});
		//boxOffset  = $(window).height() - 580 + $(document).scrollTop();
		//$('#feedback').animate({top: boxOffset + 'px'},{duration:500,queue:false});
		$(window).scroll(function () {
			iconOffset = $(window).height() - 70 + $(document).scrollTop();
			$('#feedbackBx').animate({top: iconOffset + 'px'},{duration:500,queue:false});
			//boxOffset  = $(window).height() - 580 + $(document).scrollTop();
			//$('#feedback').animate({top: boxOffset + 'px'},{duration:500,queue:false});
		})
	}
	var url = 'http://feedback.crocs.com/Default.aspx?p=' + cleanUrl();
	function cleanUrl() {
		var loc = window.location.href;
		var loc = loc.replace(/&/g, '^');
		var loc = loc.replace(/\?/g, '|');
		return loc;
	}
	$('#feedbackBx a').click(function() {
		window.open (url,"mywindow","location=0,status=0,scrollbars=0,width=302,height=600,resizable=1");
		//mywindow.moveTo(0,0);
	})
	
	// add class to remove all styling on inputs of type checkbox or radio
	$('input:checkbox, input:radio').addClass('noStyle');
	//
	$('input:text:disabled').addClass('disabled');
	// change cursor for disabled buttons
	$('button:disabled').css('cursor','default');
	// change class of span inside button elements if button is disabled
	$('button:disabled span').addClass('disabled');
	// stripe all tables with class zebra
	$('table.zebra tbody tr:odd').addClass('alt');
	// add class to the first list item's p of content nav to remove background
	$('ul.contNav li:first-child p').addClass('first');
	// apply expand/collapse functions to arrows
	$('ul.contNav li p span').click(function() {
		$(this).parent('p').toggleClass('alt').siblings('ul').slideToggle('fast');
	});
	// add details class to to the last table data on the my account small order history table
	$('#myAccOrdHistTbl tbody tr td:last-child').addClass('details');
	// add details class to the last table data on the order history large table
	$('#orderHistTbl tbody tr td:last-child').addClass('details');
	// add the all class to the last list item of the pagination list
	$('ul.pagination li:last-child').addClass('all');
	$('table.orderDetsTbl tbody tr:has(td):first').addClass('first');
	$('table.totalsTbl tr:has(h2)').addClass('divider');
	$('ul.checkoutForm li.review ~ li.last').addClass('reviewAddr');
	// apply expand/collapse functions to arrows on filters nav
	/*
	$('div.filtersNav ul li p span').click(function() {
		$(this).parent('p').toggleClass('alt').siblings('ul').slideToggle('fast');
	});*/
	// primary category tabs
	$('div.pCatProds').tabs();
	// product card rules
	//$('div.pCard ul li:nth-child(7)').addClass('more');
	
	$('div.pCard a.cardLnk').each(function() {
		$(this).attr('href', $(this).parent('div.pCardI').children('a:first-child').attr('href'));
	});
	
	$('div.pCard').hover(function() {
		// quick view not active for launch
		// if it's IE, show the quick view button, otherwise animate it
		/* if(jQuery.support.cssFloat == true) {
			$(this).children('div.qv').fadeIn('fast');
		} else {
			$(this).children('div.qv').show();
		}*/
		// if it's IE6, don't change the background position
		if (g_ie6 != 1) {
			$(this).css('border-color','#c1c1c1');
		}
		//$(this).children('div').children('p, span').css('text-decoration','underline');
		
	}, function() {
		// quick view not active for launch
		// if it's IE, show the quick view button, otherwise animate it
		/* if(jQuery.support.cssFloat == true) {
			$(this).children('div.qv').fadeOut('fast');
		} else {
			$(this).children('div.qv').hide();
		}*/
		if (g_ie6 != 1) {
			$(this).css('border-color','#ffffff');
		}
		$(this).children('div').children('p, span').css('text-decoration','none');
	});
	$('div.pCard ul li a img:not(div.pCard ul li.more a img)', baseElement).tooltip({
		delay: 0,
		track: true,
		showURL: false,
		fixPNG: true,
		top: 25,
		left: -9
	}).hover(function() {
		// IE6 can't handle this
		if (g_ie6 != 1) {
			var pID = $(this).parents('li').parents('ul').siblings('span').attr('id').toLowerCase();//$('div.pCardI span').attr('id');
			var pName = $(this).parents('li').parents('ul').siblings('span').attr('title');//$('div.pCardI span').attr('title');
			var appendix = $.trim($(this).parents('li').parents('ul').siblings('div').text());
			var imageAvail = $(this).siblings('span').attr('title');
			var color = $(this).attr('class');
			var colorName = refineColor($(this).siblings('span').text());
			var g_currentColorTitle = refineColor($(this).text());
			var g_currentProductCategory = refineCategory($('#crumbs a:eq(1)').text());
			if (color != '') {
				// $(this).parents('li').parents('ul').siblings('a').children('img.prod').attr('src','images/placeholder_pCard2_' + color + '.jpg');
				if (imageAvail == "imageAvail") {
					var picSrc = selectPictureSource(g_path+'product-images/thumbnail/' + pID + '_' + color + '.jpg', 
							scene7Path + "/" + thumbnailImagePreset + appendix + "/" + g_currentProductCategory + colorName + "-" + refineProduct(pName) + "-_" + pID.toUpperCase() + "_" + color.toUpperCase() + "_IS.jpg");
					$(this).parents('li').parents('ul').siblings('a').children('img.prod').attr('src', picSrc);
					$(this).parents('li').parents('ul').siblings('a:not("a.debuglink")').attr('href', $(this).parents('a').attr('href'));
				} else {
					var picSrc = g_path+'product-images/thumbnail/not_available.png'; //this picture source is not affected by Scene7
					$(this).parents('li').parents('ul').siblings('a').children('img.prod').attr('src', picSrc);
				}
			}
		}
	}, function() {
	});
	// mini cart
	$('#miniCart div.items li:odd').addClass('alt');
	$('#miniCart').mousemove(function() { clearTimeout(g_miniCartTimeOut); });
	// search suggest
	$('#barSearch input').focus(function () { 
		$(this).addClass('focus');
		$(this).removeClass('nosearch');
		showSearchSugg();
	});
	$('#barSearch input').blur(function () { 
		$(this).removeClass('focus');
		$(this).addClass('nosearch');
		hideSearchSugg();
	});
	$('#searchSugg ul li').hover(function() {
		$(this).toggleClass('sel');
	}, function() {
		$(this).toggleClass('sel');
	});
	$('a.notempty').bind('click', function () {
		app.minicart.cartShow();
		return false;
	});
	
	//Slider for radio button sets surrounded with box of class .slider
	$('.slider').each(function(){createSlider($(this))});
	
	$('.slide-radio').click(function(){
		$(this).parent().parent().find('div').slider('value',$(this).val()); 
	});
	
};

$(function(){DOMUtils.applyBehaviors(null);});

// set stay to true for a permanent mini cart, otherwise will hide itself in 6 seconds
function showMini(stay) {
	$('#miniCart').fadeIn(500, function() {
		$('#miniCart div.miCont').slideDown(500);
	});
	if (stay != true) {
		g_miniCartTimeOut = setTimeout("hideMini()",6000);
	}
}
function hideMini() {
	$('#miniCart div.miCont').slideUp(500, function() {
		$('#miniCart').fadeOut(500);
	});
}
function showSearchSugg() {
	//$('#searchSugg').slideDown('fast');
}
function hideSearchSugg() {
	$('#searchSugg').slideUp('fast');
}
function callFloodlight_same(trackingUrl,fwdUrl) {
	var axel = Math.random() + "";
	var a = axel * 10000000000000;
	var tag_url=trackingUrl+a+"?";
	if(document.getElementById("DCLK_FLDiv")){var flDiv=document.getElementById("DCLK_FLDiv");}
	else{var flDiv=document.body.appendChild(document.createElement("div"));flDiv.id="DCLK_FLDiv";flDiv.style.display="none";}
	var DCLK_FLIframe=document.createElement("iframe");
	DCLK_FLIframe.id="DCLK_FLIframe_"+a;
	DCLK_FLIframe.src=tag_url;
	flDiv.appendChild(DCLK_FLIframe);
	setTimeout("window.location.href ='" + fwdUrl + "';", 1000);
}

// create slider function using jquery UI 
function createSlider(slider) {
	var startVal = 4;
	var preselect = false;
	$(slider).find('input[type="radio"]').each(function(){
		$('label[for='+$(this).attr('id')+']').text('');
		if($(this).attr('checked') == true) {
			startVal = $(this).attr('value');
			preselect = true;
		}
	});
	var radios = $(slider).find('input[type="radio"]').length;
	var maxval = Number($(slider).find('input[type="radio"]:last').val());
	var minval = Number($(slider).find('input[type="radio"]:first').val());
	//var step = maxval/radios;
	$(slider).find('div').slider({
		value: startVal,
		min: minval,
		max: maxval,
		step: 1,
		slide: function(event, ui) {
			$(slider).find('input[type="radio"][value=' + ui.value + ']').attr('checked','checked');
			$(slider).find('input[type="radio"][value=' + ui.value + ']').trigger('updateState');
		}
	});
	if(preselect) {
		$(slider).find('input[type="radio"][value=' + $(slider).find('div').slider('value') + ']').attr('checked','checked');
	}
	
}

function selectPictureSource(legacySource, scene7Source) {
	if (useScene7 == true || useScene7 == 'true') {
		return scene7Source;
	}
	return legacySource;
}

function refineCategory(category) {
	category = category.indexOf("Search results for") != -1 ? "" : ($.trim(category) + "-");
	category = category.replace(/[^a-zA-Z 0-9 -]+/g,'').replace(' ', '-', 'g');
	if (category == "-") {
		category = "";
	}
	return category;
}

function refineColor(color) {
	color = $.trim(color).replace(/[^a-zA-Z 0-9 - \/]+/g,'').replace(' ', '-', 'g').replace('/', 'and', 'g');//TODO: localize and
	return color;
}

function refineProduct(product) {
	product = $.trim(product).replace(/[^a-zA-Z 0-9 -]+/g,'').replace(' ', '-', 'g');
	return product;
}

$(function() {
	$(".iservicesatcrocs").html('<a href="mailto:customerservice@crocs.com">customerservice@crocs.com</a>');
	$(".iservicesatcrocsEmailCs").html('<a href="mailto:customerservice@crocs.com">Email Customer Service</a>');
});
