﻿var CARTURL = '/remote/remote.php?action=';
window.ETCRemote = '/remote/remote.php?action=';
window.subURL = CARTURL;
window.productType = 'product-grid';
window.loadInProgress = false;


$(function () {
	if (location.href.indexOf('etc.thechampeon.com') == -1) {
		if (location.href.indexOf('https://') == -1) {
			location.href = 'https://everything2connect.com/';
		}
	}

	//$('#under-nav > li:gt(9)').remove();
	//$('#under-nav > li > ul > li:gt(25)').remove();
	//	tracerAction('activate');
	loaderAction('start');
	initPage();
	initRefineBox();
	setupSearchInput();
	initMenus();
	etcInitCart();

	if ($('#slides').length > 0) {
		$('#slides').cycle({
			fx: 'fade',
			speed: 1750,
			timeout: 5000,
			randomizeEffects: true,
			easing: 'easeOutCubic',
			next: '.slideNext',
			prev: '.slidePrev',
			pager: '#slidePager',
			cleartypeNoBg: true
		});
	}


});

/* Inits */
function initPage() {
	fHeight = $(window).height();
	$('.wrapper').css({
		'min-height': fHeight
	});

	$('#footer').css({
		'opacity': 0.9
	});
}

function initMenus() {

	window.menuInitTimer = setTimeout(function () {
		$('#undermenu').animate({
				'top': 70
			}, 700, 'linear', function () {
				$('#topmenu').animate({
					'top': -27
				}, 700, 'linear', function () {
			});
		});

	}, 100);

	initHrefs('body');


	jQuery("#under-nav a").removeAttr('title');
	jQuery("#under-nav ul").css({ display: "none" }); // Opera Fix


	$('#under-nav > li').bind('mouseenter', function () {
		jQuery(this).find('ul:first').css({
			visibility: "visible",
			display: "none"
		}).slideDown(400, "easeInOutQuart");
	});

	$('#under-nav > li > ul').bind('mouseenter', function () {
		$(this).css({
			'visibility': 'visible'
		});
	});

	$('#under-nav > li > ul  > li').bind('mouseenter mouseleave', function () {
		$(this).toggleClass('hover');
	});

	$('#under-nav > li > ul  > li > a').bind('click', function () {
		$(this).parent().parent().hide();
	});

	$('#under-nav > li').bind('mouseleave', function () {
		jQuery(this).find('ul:first').css({
			visibility: "hidden"
		});
	});

	$('#under-nav > li > ul').addClass('shadow');
}

function initHrefs(fDom) {
	$(fDom+' a[pid]').each(function () {
		$(this).attr('url', $(this).attr('href'));
		$(this).bind('click', function () {
			$(this).attr('href', 'javascript:void(0)');
			loadPage($(this).attr('pid'), 0, function () { loaderAction('stop'); });
		});

		$(this).bind('mouseenter, mouseleave', function () {
			$(this).attr('href', $(this).attr('url'));
		});
	});

}

/* LIVE SEARCH */

function liveSearch() {
	setWindowTitle('Searching...');

	if (window.liveSearchTimer) {
		clearTimeout(window.liveSearchTimer);
	}

	fPageType = getPageType();
	if (fPageType != 'inside-products') {
		window.loadInProgress = true;
		loadPage(3, 1, function (data) {
			performLiveSearch();
		});
	} else {
		performLiveSearch();
	}
}

function performLiveSearch() {
	$('#breadcrumb-path').html(' » <img src="/net/images/loading-blue.gif" width="12" height="10"> <strong>Searching ...</strong>');
	window.liveSearchTimer = setTimeout(function () {
		fType = getProductPageType();
		fSearch = $('#topbar-search-input-box').val();
		$('#refine-search').val(fSearch);
		fArray = $('#refine-form').serializeArray();
		$.post(window.ETCRemote + 'search&spid=' + fType + '&rnum=' + getRandomNumber(99999999), fArray, function (data) {
			$('#breadcrumb-path').html(' » <strong>Product Live Search</strong>');
			$('#product-container').html(data);
			googleTrackSearch(fSearch);
			setWindowTitle('Product Live Search :: ' + fSearch);
			loaderAction('stop');
			window.groupid = 0;
			window.pid = 0;
		});
	}, 1000);
}


/* Global Stuff */
function setWindowTitle(fTitle) {
	if (fTitle == undefined) {
		fTitle = $('#meta-page-name').val();
	}

	document.title = 'ETC :: Everything To Connect :: ' + fTitle;
}

function googleTrackHit() {
	fSlug = $('#meta-page-slug').val();
	_gaq.push(['_trackPageview', fSlug]);
}

function googleTrackSearch(fSearch) {
	_gaq.push(['_trackEvent', 'Products', 'Search', fSearch]);
}

function googleTrackProductView() {
	fProductName = $('#meta-product-name').val();
	fProductID = $('#meta-product-id').val();
	_gaq.push(['_trackEvent', 'Products', 'View', fProductName + ' ('+fProductID+')']);
}

function loadPage(fPID, fIsSearch, fOnComplete) {
	$.fancybox.close();
	loaderAction('start');
	fType = getProductPageType();
	trace('Loading Page...'+fType);
	$.get(window.ETCRemote + 'page&linkid=' + fPID + '&spid=' + fType + '&issearch=' + fIsSearch + '&rnum=' + getRandomNumber(99999999), function (data) {
		$('#page-container').html(data);
		initHrefs('#page-container');
		setWindowTitle();
		googleTrackHit();
		fOnComplete();
		window.pid = fPID;
		window.issearch = fIsSearch;
	});

}

function getPageType() {
	fData = $('#page-type').attr('type');
	return fData;
}

function traceAjaxError(fURL, fData) {
}

/* Loader */
function loaderAction(fAction) {
	fObj = $('#loader');
	switch (fAction) {
		case 'start':
			fObj.fadeIn(300);
			break;
		case 'stop':
			fObj.fadeOut(300);
			break;
	}
}

/* Search Stuff */
function setupSearchInput() {
	window.origData = $('#product-container').html();
	window.origBreadCrumb = $('#breadcrumb-path').html();
	$('#topbar-search-input-box').bind('keyup keydown change', function () {
		fVal = $(this).val();
		if (fVal.length > 2) {
			liveSearch();
		} else {
			//$('#product-container').html(window.origData);
			//$('#breadcrumb-path').html(window.origBreadCrumb);
		}
	});
/*
	$.ajax({
		url: '/files/xml/products.xml',
		dataType: 'xml',
		success: function(xmlResponse) {
			window.productXMLData = $('item', xmlResponse).map(function() {
				return {
					value: $('name', this).text(),
					id: $('id', this).text(),
					groups: $('groups', this).text(),
					groupnames: $('groupnames', this).text()
				};
			}).get();
			initSearchInput();
		}
	});
*/
}

function initSearchInput() {
/*
	$("#topbar-search-input-box").autocomplete({
		minLength: 0,
		source: window.productXMLData,
		focus: function (event, ui) {
			$("#topbar-search-input-box").val(ui.item.label);
			return false;
		},
		select: function (event, ui) {
			$("#topbar-search-input-box").val(ui.item.label);
			fID = ui.item.id;
			loadProductViewer(fID);
			return true;
		},
		open: function () {
			$('.ui-autocomplete').css({
				'z-index': 9998
			});
		}
	})
	.data("autocomplete")._renderItem = function (ul, item) {
		fGroups = item.groups;
		fStatus = true;
		$('.refine-checkbox:checked').each(function () {
			fVal = '{' + $(this).val() + '}';
			if (stringExists(fGroups, fVal) == false) {
				fStatus = false;
			}
		});

		if (fStatus) {
			return $("<li></li>")
				.data("item.autocomplete", item)
				.append('<a><div class="autocomplete-icon"></div><div class="autocomplete-label"><div>' + item.label + '</div><div class="autocomplete-groups">' + item.groupnames + '</div></div><div class="clear"></div></a>')
				.appendTo(ul);
		} else {
			return $('');
		}
	};
*/
}

/*  Search - Refine Stuff */
function initRefineBox() {
	$('#refine-box, #topbar-search-refine').bind('mouseleave', function () {
		window.refineBoxTimer = setTimeout(function () {
			refineBox('close');
		}, 800);

	});

	$('#refine-box, #topbar-search-refine').bind('mouseenter', function () {
		try {
			clearTimeout(window.refineBoxTimer);
		} catch (e) {
		}
	});

	$('#topbar-search-refine').bind('click', function () {
		refineBox('toggle');
	});

	$('#topbar-search-refine').bind('mouseenter', function () {
		refineBox('open');
	});


}

function refineBox(fAction) {
	if (fAction == undefined) {
		fAction = 'toggle';
	}

	switch (fAction) {
		case 'toggle':
			$('#refine-box').slideToggle('fast');
			break;
		case 'close':
			$('#refine-box').slideUp(100);
			break;
		case 'open':
			$('#refine-box').slideDown(300);
			break;
	}
}


function refineUpdate() {
	loaderAction('start');
	liveSearch();
}



/* Products Page */
function loadUp(fDomID, fID, fType, fFunc) {
	loaderAction('start');
	if (fID > 0 && fID != 3) {
		$.post(window.ETCRemote + fType + '&linkid=' + fID + '&rnum=' + getRandomNumber(99999999), {}, function (data) {
			$('#' + fDomID).html(data);
			window.origData = data;
			fFunc();
			loaderAction('stop');
		});
	} else {
		addProductPageClass(fType);
		liveSearch();
	}
}

function getProductPageTypeArray() {
	fArray = ['product-list', 'product-grid', 'product-view'];
	return fArray;
}

function addProductPageClass(fClass) {
	fArray = getProductPageTypeArray();
	for (i = 0; i < fArray.length; i++) {
		fThisClass = fArray[i];
		if (fThisClass != fClass) {
			$('#product-container').removeClass(fThisClass);
		}
	}
	$('#product-container').addClass(fClass);
	window.productType = fClass;
}

function getProductPageType() {
	fArray = getProductPageTypeArray();
	fClass = '';
	for (i = 0; i < fArray.length; i++) {
		fThisClass = fArray[i];

		if ($('#product-container').hasClass(fThisClass)) {
			fClass = fThisClass;
		}
	}

	if (fClass == '') {
		fClass = 'product-grid';
	}

	return fClass;
}

function loadProductList() {
	loadUp('product-container', window.pid, 'product-list', function () {
		addProductPageClass('product-list');
	});
}

function loadProductGrid() {
	loadUp('product-container', window.pid, 'product-grid', function () {
		addProductPageClass('product-grid');
	});
}

function loadProductViewer(fID) {
	loaderAction('start');
	fURL = window.ETCRemote + 'product-view&linkid=' + fID + '&rnum=' + getRandomNumber(99999999);
	$.get(fURL, function (data) {
		loaderAction('stop');
		fancyboxDisplay(data, function () { });
		googleTrackProductView();
	});
}



/* Footer Functions */
function footerToggle(fAction) {
	switch (fAction) {
		case 'open':
			$('#footer').animate({
				'bottom': 0
			}, 500);
			break;
		case 'close':
			$('#footer').animate({
				'bottom': -40
			}, 500);
			break;
		
	}
}

/* Cart Functions */
function etcAddToCart(fProductID, fQty) {
	loaderAction('start');
	fURL = window.CARTURL + 'addtocart&productid=' + fProductID + '&qty=' + fQty + '&salepricenum=1&optionid=0' + '&rnum=' + getRandomNumber(99999999);
	$.get(fURL, function (data) {

		//alert(data);
		if (data != 'OK') {
			traceAjaxError(fURL, fData);
		} else {
			etcUpdateCartCount();
		}

	});
}

function etcUpdateCartCount() {
	loaderAction('start');

	fURL = window.CARTURL + 'loadcart&trace=1' + '&rnum=' + getRandomNumber(99999999);
	$.get(fURL, function (data) {
		$('#footer-cart-count').html(data);
		//alert(data);
		if (data != '0') {
			footerToggle('open');
		} else {
			footerToggle('close');
		}
		loaderAction('stop');
	});
}

function etcViewCart() {
	loaderAction('start');
	fURL = window.CARTURL + 'viewcart';
	$.get(fURL, function (data) {
		loaderAction('stop');
		fancyboxDisplay(data, function () { });
	});
}

function removeFromCartCallback(fID) {
	etcUpdateCartCount();
}

function etcInitCart() {
	fSID = $.cookie('etcOrderSID');
	if (fSID == undefined || fSID == '') {
		fSID = '';
	}
	fURL = window.ETCRemote + 'orders-get-orderid&sid=' + fSID + '&rnum=' + getRandomNumber(99999999);
	$.get(fURL, function (data) {
		loaderAction('stop');
		fArray = data.split('|');
		fSID = fArray[1];
		etcSetCartURL(fSID);
		$.cookie('etcOrderSID', fSID, { expires: 1 });
		etcUpdateCartCount();
	});
}

function etcSetCartURL(fSID) {
	window.CARTURL = '/remote/remote.php?sid=' + fSID + '&action=';
	window.subURL = window.CARTURL;
	window.ETCRemote = window.CARTURL;

}

function etcResetCart() {
	$.cookie('etcOrderSID', '');
	etcSetCartURL('');
	etcInitCart();
	etcUpdateCartCount();
}
