var hitchjs = jQuery.noConflict();
hitchjs(document).ready(function(){

	hitchjs("a.storelocation").fancybox()	
	
	hitchjs("ul.hitchproducts li").hoverIntent(showLevel2,hideLevel2);
	hitchjs("ul.subnav li").hoverIntent(showLevel3,hideLevel3);
	
	hitchjs('ul.hitchproducts li a span').each(function (){
		var actheight = hitchjs(this).height()
		var parentheight = hitchjs(this).parent().height()
		var pad = (parentheight - actheight) / 2
		hitchjs(this).css('padding-top',pad)
	})

	function showLevel2()
	{
		hitchjs(this).find("ul.subnav").fadeIn("fast")
	}

	function hideLevel2()
	{
		hitchjs(this).find("ul.subnav").hide()
	}

	function showLevel3()
	{
		hitchjs(this).find("ul.level3").fadeIn("fast")
	}

	function hideLevel3()
	{
		hitchjs(this).find("ul.level3").hide()
	}

	hitchjs('a.bookmark').click(function (obj){
		var urlAddress = "http://www.discounthitches.com/";
		var pageName = "Discount Curt Trailer Hitches";
	
		if (window.sidebar)
		{ 
			// Mozilla Firefox Bookmark
			window.sidebar.addPanel(pageName, urlAddress,"");
		} else if( window.external ) { 
			// IE Favorite
			window.external.AddFavorite( urlAddress, pageName); 
		}	else if(window.opera && window.print) {
			// Opera Hotlist
			obj.setAttribute('href',urlAddress);
	    obj.setAttribute('title',pageName);
	    obj.setAttribute('rel','sidebar');
	    obj.click();
	    return false;
		} else {
			alert("Sorry, but your browser doesn't support adding to favorites like this.\n Please press Control + D to add the item to favorites.")
		}
		
	})

	hitchjs('div.searchTabs ul li').click(function (){
		var x = hitchjs(this).attr('id')
		
		var x = Number(x.split('_')[1]) - 1
		
		hitchjs('div.pageview').each(function(i){
			if(i == x)
				hitchjs(this).show()
			else
				hitchjs(this).hide()
		})

		hitchjs('div.searchTabs ul li').each(function(i){
			if(i == x)
			{
				hitchjs(this).removeClass('active')
				hitchjs(this).addClass('active')
			}
			else
			{
				hitchjs(this).removeClass('active')
			}
		})

	})
	
});

function ajaxRequester()
{
	var myRequest;
	try{
		myRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			myRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(oc){
			myRequest = null;
		}
	}
 
	if(!myRequest && typeof XMLHttpRequest != "undefined"){
		myRequest = new XMLHttpRequest();
	}
	return myRequest;
}

var paginate = 8;

function loadGallery(galleryid,startnum)
{
  var loadAjax = ajaxRequester();

  if( loadAjax != null)
  {
		var strQueryString = '../www/index.cfm/event/loadgallery/galleryid/' + galleryid
		loadAjax.open("GET", strQueryString, true);
		loadAjax.onreadystatechange = function (aEvt) {
			if( loadAjax.readyState == 4)
			{ //The load is complete when readyState equals 4
				if( loadAjax.status != "200" &&  loadAjax.status != undefined)
				{
					var x = loadAjax.responseText;
					document.getElementById('gallerycont').innerHTML = x + "<br />" + strQueryString;
				} else {
          var xmlDoc; 
          if(window.ActiveXObject)
          {
              //Internet Explorer
              xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.async = false;
              xmlDoc.loadXML( loadAjax.responseText);
          }
          else if(document.implementation && document.implementation.createDocument)
          {
              //Mozilla
              xmlDoc =  loadAjax.responseXML;
          }
          
          var count = Number(xmlDoc.documentElement.getElementsByTagName('Count')[0].childNodes[0].nodeValue)
          var container = document.getElementById('photobox');
          container.innerHTML = ""

          if(!(startnum)) startnum = 0

          hitchjs('#gallerybox').fadeOut('normal',function (){hitchjs('#photobox').fadeIn('normal')});
          
          var galleryTitle = xmlDoc.documentElement.getElementsByTagName('Name')[0].childNodes[0].nodeValue;
          var titleElement = document.createElement('p');
          titleElement.className = "galleryTitle";
          titleElement.innerHTML = galleryTitle;
          var backLink = document.createElement('a');
          backLink.className = 'backLink'
          backLink.innerHTML = 'Back to Galleries'
          backLink.onclick = new Function("evt", 'loadGalleries()')
          titleElement.appendChild(backLink)
          container.appendChild(titleElement)
          hitchjs(titleElement).fadeIn('fast');
          
          if((startnum == 0))
          {
          	currentpage = 1
          	if(count > paginate)
          	{
          		endnum = (paginate - 1)
          	} else {
	          	endnum = (count - 1)
          	}
          } else {
						currentpage = Math.ceil(startnum / paginate) + 1
          	if(count > (paginate * currentpage))
          	{
          		endnum = ((paginate * currentpage) - 1)
          	} else {
	          	endnum = (count - 1)
          	}
          }
          if(count > paginate)
          {
          	var pages = Math.ceil(count / paginate)
          	var pagination = document.createElement('p')
          	pagination.className = 'pagination'
          	for(var i = 1; i <= pages; i++)
          	{
          		var pagelink = document.createElement('a')
          		if(i == currentpage)
          		{
          			pagelink.className = "current"
          		} else {
          			var newstart = (i-1) * paginate
          			pagelink.onclick = new Function ("evt", 'loadGallery("' + galleryid + '","' + newstart + '")')
          		}
          		pagelink.innerHTML = i
	          	pagination.appendChild(pagelink)
          	}
          container.appendChild(pagination)
          }

					var photos = xmlDoc.documentElement.getElementsByTagName('Photo')
					for(var i = startnum; i <= endnum; i++)
					{
						var photodiv = document.createElement('div');
						photodiv.className = 'photocont';
						photodiv.onclick = new Function ('evt', "loadImage(this)")
						var photo = document.createElement('img');
						photo.className = 'photothumb'
						photo.src = photos[i].getAttribute('thumb')
						photo.alt = photos[i].getAttribute('alttext')
						photodiv.appendChild(photo)
						var photoTitle = document.createElement('p')
						photoTitle.className = 'photoTitle'
						photoTitle.innerHTML = photos[i].getAttribute('title')
						photodiv.appendChild(photoTitle)
						var fullsrc = document.createElement('input')
						fullsrc.type = 'hidden'
						fullsrc.className = 'imgsrc'
						fullsrc.value = photos[i].getAttribute('path')
						var caption = document.createElement('input')
						caption.type = 'hidden'
						caption.className = 'imgcaption'
						caption.value = photos[i].getAttribute('caption')
						photodiv.appendChild(fullsrc)
						photodiv.appendChild(caption)
						var cleardiv = document.createElement('div')
						cleardiv.style.clear = 'both'
						photodiv.appendChild(cleardiv)
						hitchjs('#photobox').append(photodiv)
						hitchjs(photodiv).fadeIn()
						if(i == photos.length - 1) hitchjs('photobox').append(cleardiv);
					}
				}
			}
		}
		loadAjax.send(null);
	}
}

function loadGalleries()
{
	hitchjs('#mainphoto').slideUp('normal', function (){
		hitchjs('#photobox').fadeOut('normal', function (){
			hitchjs('#gallerybox').fadeIn('normal')
		})
	})
}

function loadImage(imagecont)
{
	hitchjs('#mainphoto').empty()
	var path = hitchjs(imagecont).find('input.imgsrc').val()
	var caption = hitchjs(imagecont).find('input.imgcaption').val()
	var mainimg = document.createElement('img')
	mainimg.src = path
	var cap = document.createElement('p')
	cap.className = 'caption'
	cap.innerHTML = caption
	hitchjs('#mainphoto').append(mainimg)
	hitchjs('#mainphoto').append(cap)
	hitchjs('#mainphoto').slideDown('slow', function (){hitchjs(mainimg).fadeIn('normal');hitchjs(cap).fadeIn('normal')})
}

function emailSubmit()
{
	var fullName = document.getElementById('marketingfullName').value
	var email = document.getElementById('marketingemail').value
	
	if((fullName == 'Your Email') || (email == 'Was added successfully!') || (fullName == 'Enter Full Name') || (email == 'Enter Email Address') || (fullName == '') || (email == ''))
	{
		document.getElementById('marketingfullName').value = 'Enter Full Name'
		document.getElementById('marketingemail').value = 'Enter Email Address'
		return;
	}

	if((fullName == 'Your Email') || (email == 'Was added successfully!'))
	{
		document.getElementById('marketingfullName').value = 'Enter Full Name'
		document.getElementById('marketingemail').value = 'Enter Email Address'
		return;
	}
	
  var loadAjax = ajaxRequester();

  if( loadAjax != null)
  {
		var strQueryString = 'index.cfm/event/emailmarketingajax/fullName/' + document.getElementById('marketingfullName').value + '/email/' + document.getElementById('marketingemail').value + '/'
		loadAjax.open("GET", strQueryString, true);
		loadAjax.onreadystatechange = function (aEvt) {
			if( loadAjax.readyState == 4)
			{ //The load is complete when readyState equals 4
				if( loadAjax.status != "200" &&  loadAjax.status != undefined)
				{
					var x = loadAjax.responseText; //error
					alert(x)
				} else {
          var xmlDoc; 
          if(window.ActiveXObject)
          {
              //Internet Explorer
              xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.async = false;
              xmlDoc.loadXML( loadAjax.responseText);
          }
          else if(document.implementation && document.implementation.createDocument)
          {
              //Mozilla
              xmlDoc =  loadAjax.responseXML;
          }
          document.getElementById('marketingfullName').value = 'Your Email'
					document.getElementById('marketingemail').value = 'Was added successfully!'
					alert('Your email: ' + email + '\n was submitted successfully.')
				}
			}
		}
		loadAjax.send(null);
	}
}

function RunHomeFlash() {
	var target = document.getElementById('flashrotation')
	var targetHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="543" height="263" id="discountHitches102809a_main" align="middle">\n'
	targetHTML = targetHTML + '<param name="allowScriptAccess" value="sameDomain" />\n'
	targetHTML = targetHTML + '<param name="movie" value="flash/discountHitches102809a_main.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /><embed src="flash/discountHitches102809a_main.swf" quality="high" wmode="transparent" bgcolor="#fffff" width="543" height="263" name="hitchesDirect101409a_main" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />\n'
	targetHTML = targetHTML + '</object>\n'
	target.innerHTML = targetHTML
}

function adjustNavigation()
{
	var nav = document.getElementById('navigation')
	var pwidth = nav.parentNode.offsetWidth
	var owidth = 0
	hitchjs('#navigation').find('li a').each(function(index,item){
		owidth = owidth + item.offsetWidth
	})
	var pad = (pwidth - owidth) / 2
	nav.style.paddingLeft = pad + 'px'
}


function addItemToCart(itemid)
{
	var qty = trim(document.getElementById('qty_' + itemid).value)
	if(isNaN(qty) || (Number(qty) < 1))
	{
		if(isNaN(qty)) document.getElementById('qty_' + itemid).value = '0'
		document.getElementById('qty_' + itemid).select()
		return;
	}
	var stock = Number(document.getElementById('stock_' + itemid).value)
	var sku = trim(document.getElementById('sku_' + itemid).value)
	var itemname = trim(document.getElementById('name_' + itemid).value.substring(0,255))
	var itemweight = trim(document.getElementById('weight_' + itemid).value)
	var msrp = trim(document.getElementById('msrp_' + itemid).value)
	var price = trim(document.getElementById('price_' + itemid).value)
	var code = trim(document.getElementById('code_' + itemid).value)
	var vendor = trim(document.getElementById('vendor_' + itemid).value)
	var partnumber = 'keystone-' + trim(document.getElementById('partnumber_' + itemid).value)

	if(qty > stock)
	{
		var checkqty = confirm("There's only " + stock + " of this item in stock.\nWould you like that amount instead?")
		if(checkqty)
		{
			qty = stock
			document.getElementById('qty_' + itemid).value = stock
		} else {return;}
	}
	
  var loadAjax = ajaxRequester();

  if( loadAjax != null)
  {
		var strQueryString = 'index.cfm/event/addcatalogitemtocart/partnum/' + xmlencode(partnumber) + '/weight/' + xmlencode(itemweight) + '/msrp/' + xmlencode(msrp) + '/price/' + xmlencode(price) + '/code/' + xmlencode(code) + '/vendor/' + xmlencode(vendor) + '/qty/' + qty + '/name/' + xmlencode(itemname)
		loadAjax.open("POST", strQueryString, true);
		loadAjax.onreadystatechange = function (aEvt) {
			if( loadAjax.readyState == 4)
			{ //The load is complete when readyState equals 4
				if( loadAjax.status != "200" &&  loadAjax.status != undefined)
				{
				} else {
					var pos = getPosition()
					var fancy_overlay = document.getElementById('fancy_overlay')
					var hoverdiv = document.createElement('div')
					var htmlstuff = loadAjax.responseText
					var closeimg = document.createElement('img')
					hoverdiv.style.top = ((pos.y/2) - (260/2)) + 'px'
					hoverdiv.style.left = ((pos.x/2) - (420/2)) + 'px'
					hoverdiv.style.zIndex = '9999'
					hoverdiv.style.display = 'none'
					hoverdiv.id = 'hovercart'
					hoverdiv.innerHTML = htmlstuff
					closeimg.alt = 'Close Window'
					closeimg.src = 'images/fancybox/fancy_closebox.png'
					closeimg.className = 'cartClose'
					closeimg.onclick = new Function ("evt",'closeHoverCart()')
					fancy_overlay.style.backgroundColor = '#666666'
					hitchjs("#fancy_overlay").css('opacity', '.3').show();
					hoverdiv.appendChild(closeimg)
					document.body.appendChild(hoverdiv)
					hitchjs(hoverdiv).fadeIn()
				}
			}
		}
		loadAjax.send(null);
	}

}

function closeHoverCart()
{
	var fancy_overlay = document.getElementById('fancy_overlay')
	var hoverdiv = document.getElementById('hovercart')
	hoverdiv.parentNode.removeChild(hoverdiv)
	fancy_overlay.style.display = 'none'
}

function getPosition()
{
	var x = 0
	var y = 0
	if (self.innerHeight)
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) 
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	
	return {x:x, y:y}
}

function addToFavorites(obj)
{
	var urlAddress = "http://www.discounthitches.com/";
	var pageName = "Discount Curt Trailer Hitches";

	if (window.sidebar)
	{ 
		// Mozilla Firefox Bookmark
		window.sidebar.addPanel(pageName, urlAddress,"");
	} else if( window.external ) { 
		// IE Favorite
		window.external.AddFavorite( urlAddress, pageName); 
	}	else if(window.opera && window.print) {
		// Opera Hotlist
		obj.setAttribute('href',urlAddress);
    obj.setAttribute('title',pageName);
    obj.setAttribute('rel','sidebar');
    obj.click();
    return false;
	} else {
		alert("Sorry, but your browser doesn't support adding to favorites like this.\n Please press Control + D to add the item to favorites.")
	}
}