// Current hash value.  Used to detect URL changes.
var current = '';
var locked = false;
var count = 0;

/*
 *  Redirect to index
 */
if(current_page != '' && current_page != '#' && current_page != 'index.php' && current_page != 'index.php#')
	window.location.href = site_root+'#'+current_page;
	
$(document).ready(function() {
	// PNG Fix
	$(document).pngFix();
	//loadHeader();
	
	menucartFun();
	
	jQuery.easing.def = "easeOutQuad";
			
	// Check hash for new URL
	if(window.location.hash && window.location.hash != '' && window.location.hash != '#')
		getURL(window.location.hash);
		
	current = window.location.hash.substring(window.location.hash.lastIndexOf('#') + 1);
	
	setInterval(checkURL, 500);
	
	// Remove link selection on click
	$('a').live('click', function() { this.blur(); });
	
	$('input:text, textarea').each(function() {
		$(this).data('default', $(this).val());
	})
	.focus(function() {
		if($(this).val() == $(this).data('default')) $(this).val('');
	})
	.blur(function() {
		if($(this).val() == '') $(this).val($(this).data('default'));
	});
	
	$('.submit').live('mouseover', function() {
		$(this).css({ 'background-color' : '#959595', color : '#ffffff' });
	}).live('mouseout', function() {
		$(this).css({ 'background-color' : '#ffffff', color : '#959595' });
	});
	
	$('.twit_module li:has(ul) a.toggle').live('mouseover', function() {
		if($(this).data('active') != true) {
			$('.twit_module li:has(ul) a.toggle').find('+ul').animate({ height : 0 }, { duration : 250, queue : false, complete : function() { $(this).css('display', 'none') } });
			$(this).find('+ul').stop().css({display : 'block', height : 0 }).animate({ height : 52 }, { duration : 250, queue : false });
			$('.twit_module li a').data('active', false);
			$(this).data('active', true);
		}
	});
	
	// Handle navigation AJAX clicks
	$('a').live('click', function(e) {
		if(e.button == 0) {
			if((this.href.indexOf('http://') == -1 || this.href.indexOf(site_root) != -1) && this.href.indexOf('mailto:') == -1 && this.href.indexOf('javascript:') == -1) {
				// Generate hash from link href.  Get URL
				var hashLink = this.href.substring(this.href.lastIndexOf('/') + 1);
				if( this.href.indexOf('team/') !== -1 )
					hashLink = 'team/' + hashLink;
				getURL(hashLink);
				return false;
			}
		}
	});
	
	$('.logo-noribachi.button').live('mouseover', function() {
		$(this).css({ 'margin-top':'-64px' });
		$('.logo-ammunition.page').css({ 'margin-top':'0' });
		})
	.live('mouseout', function() {
		$(this).css({ 'margin-top':'0' });
		$('.logo-ammunition.page').css({ 'margin-top':'-64px' });
		})
	.live('click', function(e) {
		if(e.button == 0)
			$(this).css({ 'margin-top':'-128px' });
		});
	
	$('.logo-ammunition.button').live('mouseover', function() {
		$(this).css({ 'margin-top':'-64px' });
		$('.logo-noribachi.page').css({ 'margin-top':'0' });
		})
	.live('mouseout', function() {
		$(this).css({ 'margin-top':'0' });
		$('.logo-noribachi.page').css({ 'margin-top':'-64px' });
		})
	.live('click', function(e) {
		if(e.button == 0)
			$(this).css({ 'margin-top':'-128px' });
		});
	
	$('.controls div').live('mouseover', function() {
            $(this).css({ 'background':'#391317' });
            });
	$('.controls div').live('mouseout', function() {
            $(this).css({ 'background':'none' });
            });

	
	$('.sub-tab-1, .sub-tab-2').live('mouseover', function() {
														   $('#inner .sub-tab-1, #inner .sub-tab-2').removeClass('tab-on').addClass('tab-off');
														   $(this).removeClass('tab-off').addClass('tab-on');
														   })
	                           .live('mouseout', function() {
														  if(!locked) {
															   $('#inner .sub-tab-1, #inner .sub-tab-2').removeClass('tab-on').addClass('tab-off');
															   switch(window.location.hash) {
																   case '#index.php': case '#': case '':
																   case '#perspective.php':
																   case '#customer_care.php':
																   case '#team.php':
																   //case '#blog.php':
																   //case '#blog_post.php':
																		$('#inner .sub-tab-1:first').removeClass('tab-off').addClass('tab-on');
																		break;
																   case '#executive_qa.php':
																   case '#news.php':
																   case '#press.php':
																   case '#press_post.php':
																   case '#faqs.php':
																   case '#team2.php':
																		$('#inner .sub-tab-2:first').removeClass('tab-off').addClass('tab-on');
																		break;
																   case '#events.php':
																   case '#contact_info.php':
																   case '#team3.php':
																		$('#inner .sub-tab-2:last').removeClass('tab-off').addClass('tab-on');
																		break;
																	default:
																		break;
																	
															   }
														  }
														   });
	$('#inner #blog-body .sub-tab-1:first').live('click', function(e) { if(e.button == 0) getURL('#blog.php'); });
	$('#inner #blog-body .sub-tab-2:first').live('click', function(e) { if(e.button == 0) getURL('#press.php'); });
	
	$('#inner #team-body .sub-tab-1:first').live('click', function(e) { if(e.button == 0) getURL('#team.php'); });
	$('#inner #team-body .sub-tab-2:first').live('click', function(e) { if(e.button == 0) getURL('#team2.php'); });
	$('#inner #team-body .sub-tab-2:last').live('click', function(e) { if(e.button == 0) getURL('#team3.php'); });
	
	$('#inner #perspective-body .sub-tab-1:first').live('click', function(e) { if(e.button == 0) getURL('#perspective.php'); });
	$('#inner #perspective-body .sub-tab-2:first').live('click', function(e) { if(e.button == 0) getURL('#executive_qa.php'); });

	$('#inner #customer-care-body .sub-tab-1:first').live('click', function(e) { if(e.button == 0) getURL('#customer_care.php'); });
	$('#inner #customer-care-body .sub-tab-2:first').live('click', function(e) { if(e.button == 0) getURL('#faqs.php'); });
	$('#inner #customer-care-body .sub-tab-2:last').live('click', function(e) { if(e.button == 0) getURL('#contact_info.php'); });
	
	$('.sharelink').click(shareOn);
	$('#share_mask, #close_button').click(shareOff);
	
});
/*
 *	Compares URL hash to current known hash.
 */
function scrollToTop() {
	$.scrollTo('0', 1000);
}
function checkURL() {
	if(!locked) {
		if(document.frames && document.frames['hiddenFrame'] && current != document.frames['hiddenFrame'].getHash()) window.location.hash = document.frames['hiddenFrame'].getHash();
		if(current != window.location.hash.substring(window.location.hash.lastIndexOf('#') + 1)) getURL(window.location.hash);
	}
}
/*
 *	Runs AJAX from hash.  Uses main navigation links as URL reference.
 */
function getURL(hash) {
	if(!locked) {
		locked = true;
		hash = hash.substring(hash.lastIndexOf('#') + 1);
		var hashLink = $("#nav a[href*='"+hash+"']");
		if(hash == '') hashLink = $('#nav a:first');
		$('#hidden').load(site_root + hash + ((hash.indexOf('?') == -1) ? '?ajax=1' : '&ajax=1'), function (responseText, textStatus, XMLHttpRequest) {//hashLink.attr('href')
			if(responseText != '') {
				$('#content .sub-tab p, #content h5, #content .inquire, #content .sub-tab-1 p, #content .sub-tab-2 p, #content .hash, #content a span, #inner .orange img:first, #hidden .orange img:first, #content .body-block p, #content .body-block h4, #content div.icon, #content .press .date, #content .press a, #content .contact-gmap').animate({ opacity : 0 }, { duration : 200, queue : false });
				if(hashLink.size() > 0) {
					$('#nav a').removeClass('active');
					hashLink.addClass('active');
				}
				window.location.hash = hash;
				$('#hiddenFrame').attr('src', site_root + "incl/store_hash.php?hash="+hash);
				current = window.location.hash.substring(window.location.hash.lastIndexOf('#') + 1);
				if(document.title) document.title = $('#content .page_title:first').html();
				$(document).pngFix();
				$('#inner div.col').css({ visibility : (hash == '' || current == '') ? 'visible' : 'hidden' });
				setTimeout(function() {
					var h = $('#hidden .body-block').height();
					$('#content .body-block').animate({ height : (h > 121) ? $('#hidden .body-block').height() : 121 },{ duration : 500});
					$('#inner div.colbox').animate({ height : (hash == '')?200:0 }, 500);
					$('#inner .orange').animate({ height : $('#hidden .orange').height()}, 500);
					$('#content .sub-tab, #content .sub-tab-1, #content .sub-tab-2').animate({ height : $('#hidden .sub-tab, #hidden .sub-tab-1, #hidden .sub-tab-2').height() }, 500);
					$('#content .body-block img').animate({ opacity : 0 }, 300);
					setTimeout(function() {
						$('#hidden + div').html($('#hidden').html());
						$('#content h5, #content .inquire, #content .sub-tab p, #content .sub-tab-1 p, #content .press .date, #content .press a, #content .sub-tab-2 p, #inner a span, #content .hash, #inner .orange img:first, #content .body-block p, #content .body-block h4, #content div.icon, #content .contact-gmap, #content #press-page, #content #press-post, #content #news-page, #content #news-post').animate({ opacity : 1 }, { duration : 500, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter");
 } });
						setTimeout(function() {
							$('#content .body-block img').animate({ opacity : 1 }, { duration : 300, queue : false });
							pageFold();
						}, 200);
						locked = false;
					}, 500);
				}, 200);
			} else
				locked = false;
		});
	}
	function pageFold(){ // toggle 'back to top' link below pagefold
//			setTimeout(function() {
		var windowHeight = $(window).height();
		var bodyHeight = $('#wrapper').height();
/*		if( typeof( window.innerHeight ) == 'number' ) { //Non-IE
			windowHeight = window.innerHeight;
		} else if( document.documentElement && (document.documentElement.clientHeight ) ) { //IE 6+
			windowHeight = document.documentElement.clientHeight;
		}*/
		if (bodyHeight < windowHeight){
			$('#page-fold').animate({ opacity : 0}, { duration: 400, queue : false });
		} else {
			$('#page-fold').animate({ opacity : 1}, { duration: 400, queue : false });
		}
//			}, 600);
	}
}
function shareOn() {
	updateShareLinks();
	$('#share_mask').css({
						width : $(document).width(),
						height : $(document).height(),
						display : 'block'
						});
	$('#wrapper').animate({ opacity : .5}, { duration : 500, queue : false, complete : function() {
		var h = $('#inner .body-block').height() + 20;
		$('#share_box_wrapper1').css({
										opacity : 0,
										display : 'block',
										top : 103 + $('#inner .orange').height()
									 }).animate({ opacity : 1 }, { duration : 500, queue : false, complete : function() {
										 if(jQuery.browser.msie) this.style.removeAttribute("filter");
									 }}).find('#share_box').css('height', (h > 300) ? h : 300);
	}});
}
function shareOff() {
	$('#share_mask').css({
						display : 'none'
						});
	$('#share_box_wrapper1').animate({ opacity : 0}, {duration : 500, queue : false, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter"); $(this).css('display', 'none'); } });
	$('#wrapper').animate({ opacity : 1}, {duration : 500, queue : false, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter");} });
}
function validate(form) {
	var ele;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	for(var i=0; i<form.elements.length; i++) {
		ele = $(form.elements[i]);
		if(ele.attr('class') == 'required' && (ele.val() == '' /*|| ele.data('default') == ele.val()*/)) {
			alert('Field "' + ele.attr('name') + '" contains invalid data.');
			ele.focus();
			return false;
		}
		if( (ele.attr('name') == 'your_name' && ele.val() == "Your name") || (ele.attr('name') == 'recipient_name' && ele.val() == "Recipient's name") ) {
			alert('Field "' + ele.attr('name') + '" must contain a real name.');
			ele.focus();
			return false;
		} else if( (ele.attr('name') == 'your_email' || ele.attr('name') == 'recipient_email') && (reg.test(ele.val()) == false) ) {
			alert('Field "' + ele.attr('name') + '" must contain a valid email.');
			ele.focus();
			return false;
		}
	}
	ajaxpost();
	return false;
}
function updateShareLinks() {
	var hash = window.location.hash;
	var url = encodeURIComponent('http://'+window.location.host+window.location.pathname+hash.substr(1));
	var sharelinks = $('div.share_column a');
	var links = new Array(
		'http://reddit.com/submit?title='+encodeURIComponent(document.title)+'&url='+url+'&',
		'http://www.facebook.com/share.php?u='+url+'&t='+encodeURIComponent(document.title)+'&',
		'http://del.icio.us/post?url='+url+'&',
		'http://friendfeed.com/share?url='+url+'&',
		'http://digg.com/submit?phase=2&title='+encodeURIComponent(document.title)+'&url='+url+'&',
		'http://www.hugg.com/node/add/storylink?edit[title]='+encodeURIComponent(document.title)+'&edit[url]='+url+'&',
		'http://www.stumbleupon.com/submit?title='+encodeURIComponent(document.title)+'&url='+url+'&',
		'http://www.mixx.com/submit?page_url='+url+'&',
		'http://www.linkedin.com/shareArticle?mini=true&ro=true&url='+url+'&title='+encodeURIComponent(document.title)+'&summary=&source=&armin=armin',
		'http://twitter.com/home?status='+url+'&',
		'http://slashdot.org/bookmark.pl?title='+encodeURIComponent(document.title)+'&url='+url+'&',
		'http://current.com/clipper.htm?title='+encodeURIComponent(document.title)+'&src=st&url='+url+'&'
	);
	sharelinks.each( function (i) {
		$(this).attr('href', links[i]);
		if(links[i] != 'javascript:')
			$(this).attr('target', '_blank');
		else
			$(this).attr('target', '');
	});
}

function ajaxpost(){
    $.post(site_root+"mail.php", 
        {your_name:  $("input[name='your_name']").val(), your_email: $("input[name='your_email']").val(), recipient_name: $("input[name='recipient_name']").val(), recipient_email: $("input[name='recipient_email']").val(), message: $("#message").val(), url: $("input[name='url']").val()+window.location.hash}, 
        function(data){if(data == "success"){shareOff()} else{alert('The mail server timed out. Better luck next time.')}});
}

function loadHeader()
{
  //$('#cap').load('http://72.47.253.54/reference/header/', function (responseText, textStatus, XMLHttpRequest) {alert(responseText+','+textStatus+','+XMLHttpRequest)});
  $('#cap').load('http://72.47.253.54/reference/header/', capCallback);
  function capCallback(responseText, textStatus, XMLHttpRequest) {
    //alert(responseText+','+textStatus+','+XMLHttpRequest)
  }
}

setInterval ( "menucartFun()", 500 );
function menucartFun(){
  $('#logged_in').load('/incl/signed_in/');
  var numberInCart = $('#foxee_product_count').html();
  if (numberInCart == '' || numberInCart == 0){
    $('.menucart-empty').css({display:'inline'});
    $('.menucart-full').css({display:'none'});
  } else {
    $('.menucart-empty').css({display:'none'});
    $('.menucart-full').css({display:'inline'});
  }
}
setInterval(resizeCart, 500 );

function resizeCart() {
    $('#fc_tb_iframeContent').css('height', Math.max(200, $(document).height() - 100));
    $('#fc_tb_window').css({
      marginTop : 0,
      top: 0,
      position: 'absolute'
    });
}

function initCustomerCare()
{
	//$('#care').load('http://72.47.253.54/foxee-test/trans');

  var memberID = 1;
  //$('#hidden_care').load('http://72.47.253.54/incl/get_member_id', function (responseText, textStatus, XMLHttpRequest) {
	//memberID = responseText;
	//alert('member id= '+member_id);
	/*$('#hidden_care').html(' ');
	  $('#hidden').load('http://72.47.253.54/incl/customer_care_id/'+member_id, function (responseText, textStatus, XMLHttpRequest) {
		//alert(responseText+':'+textStatus+':'+XMLHttpRequest);
		$('#care').css({opacity:0}).html(responseText);
		setTimeout(function() {
			$('#customer-care-body .body-block').animate({height:$('#care').height()},500);
			$('#customer-care-body #care').animate({opacity:1},{duration : 500, queue : false, complete : function() { if(jQuery.browser.msie) this.style.removeAttribute("filter");} });
		}, 100);
		
	  });*/
  //});

}

function addVideo() {
	$('#video_spot').css({display:'block'}).flash({swf:'/images/video/spot.swf',height:556,width:950,params:{wmode:'transparent'} });
}

function removeVideo() {
	$('#video_spot').html(' ').css({display:'none'});
}