var productIDs = new Array;
var productStates = new Array;
var filtersList = new Array;
var filtersListState = new Array;
var pageProductView = true;

filtersList[0] = 'nexus';
filtersList[1] = 'male';
filtersList[2] = 'female';
filtersList[3] = 'junior';

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

Event.observe(window, "load", function() { 

	// theres a selected filter 
	// box this must be a
	// category view page
	
	if ($("viewOptions")) {
	
		// define the page type
		pageProductView = false;
		
		for (var i=0;i<filtersList.length;i++) {
			// make all the filters as unavailable (state -1)
			var tempIndex = filtersList[i];
			filtersListState[tempIndex] = "Unavailable";
		}

		// build a list of ALL products and build a list of their states (inititally all off)	
		var products = $('productlist').select('li.productlistitem');
		
		for (var i=0;i<products.length;i++) {
		
			// assign a state for each product
			tempIndex = products[i].id;
			productIDs[i] = tempIndex;
			productStates[tempIndex] = 1;

			// match the tags to the filters, on page load, all available filters are enabled (state 2)
			// unmatched filters will stay at -1
			var tagVals = $(tempIndex + "_tags").value;	
			if(tagVals.match("n")) filtersList['nexus'] = "Off"; 
			if(tagVals.match("m")) filtersList['male'] = "On"; 
			if(tagVals.match("f")) filtersList['female'] = "On"; 
			if(tagVals.match("j")) filtersList['junior'] = "On";
			
		}
		
		Event.observe("sort", "mouseover", function() { 
			this.className = "filterOpen";
		});
		
		Event.observe("order", "mouseover", function() { 
			this.className = "filterOpen";
		});
		
		Event.observe("sort", "mouseout", function() { 
			this.className = "";
		});
		
		Event.observe("order", "mouseout", function() { 
			this.className = "";
		});
		
		//simulate click of subcategory button if subcat value is passed through querystring
		selectSubCategory();	
		
		if(Prototype.Browser.IE7 || Prototype.Browser.IE6) fixproductLinks();

	}
	
	else { //product view page - change circle graphic to utilise relevant tags 
	
		if ($("productID")) {
		
			var productID = $("productID").value;
			productCGTags = $("product_cgtags").value;
			fireCGvalues(productCGTags);
			
			//adjust reviews wrapper div to the correct height for it's contents, and hide it.
			if($("reviews_wrapper")) {
				var fullheight =  $("reviews").scrollHeight+35+"px";
				$("reviews_wrapper").style.display = "none";
				$("reviews_wrapper").style.height = fullheight;
			}	
		
		
		}
	}
		
});

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}


function fixproductLinks() {
	var prodlinks = $('productlist').select('a');
	var prodthumbs = $('productlist').select('span.thumbnail');
	//var prodlink = new Array;
	
	for (var i=0;i<prodthumbs.length;i++) {
		window['prodlink_'+str_replace('thumb','',prodthumbs[i].id)] = prodlinks[i].href;
		
		Event.observe(prodthumbs[i].id, "click", function() { openLink(window['prodlink_'+parseInt(str_replace('thumb','',this.id))]); });
	}
}

function selectSubCategory(selectedCategory) {

	// reset filter selection if a category is requested
	$("selectedfilter").value = ""; 
	
	if (selectedCategory == undefined) selectedCategory = $("selectedsubcat").value;
	
	// clear the selected value from the category menu and reapply it
	var subcats = $('catmenu').select('li.subcat');
	for (var i=0;i<subcats.length;i++) {
		subcats[i].className = "subcat";
	}
	
	if($("catbutton"+ selectedCategory)) $("catbutton"+ selectedCategory).className = "subcat selected";

/*

	// update the value of selectedsubcat
	if (!selectedCategory || selectedCategory == '') {
		selectedCategory = '';
		$("selectedsubcat").value = '';
	} else {
		$("selectedsubcat").value = selectedCategory;
	}

*/
	var tempIndex; 
	
	// ------------------ work out which products are faded in
	getProductsInCategory(selectedCategory);	
	
	for (var i=0;i<filtersList.length;i++) {
		// set all the filters to disabled unless they are unavailable globally
		var tempIndex = filtersList[i];
		filtersListState[tempIndex] = (filtersListState[tempIndex] != "Unavailable") ? "Disabled" : "Unavailable";
	} 
		
	// check for a tag match and enable any matching filters
	for (i=0;i<productIDs.length;i++) {
		tempIndex = productIDs[i];
		if (productStates[tempIndex] == 1) {
			var tagVals = $(tempIndex + "_tags").value;
			if(tagVals.match("n")) filtersListState['nexus'] = "Off"; 
			if(tagVals.match("m")) filtersListState['male'] = "On"; 
			if(tagVals.match("f")) filtersListState['female'] = "On"; 
			if(tagVals.match("j")) filtersListState['junior'] = "On";
		}
	
	}
	
	var tempArray = new Array;
	for (var i=0;i<filtersList.length;i++) {
		var tempIndex = filtersList[i];
		if (filtersListState[tempIndex] == "On") tempArray[i] = tempIndex.substring(0,1);
	}
	$('selectedfilter').value = tempArray.join(';');
	
	
	applyFilterStyles();
	applyProductFades();	
}
	
function getProductsInCategory() {

	// function populates the productStates array with fade values appropriate to that subcetegory

	selectedCategory= $("selectedsubcat").value;
	
	var tempIndex;
	
	if (selectedCategory != '') {
	
		// switch all products off
		for (i=0;i<productIDs.length;i++) {
			tempIndex = productIDs[i];
			productStates[tempIndex] = 0;
		}
		
		// switch all products in category on
		var productsInCategory = $('productlist').select('li.cat'+selectedCategory);
		
		for (i=0;i<productsInCategory.length;i++) {
			tempIndex = productsInCategory[i].id;
			productStates[tempIndex] = 1;
		}
		
	} else {
	
		for (i=0;i<productIDs.length;i++) {
			tempIndex = productIDs[i];
			productStates[tempIndex] = 1;
		}
		
	}
	
	
}

function applyFilterStyles() {

	var tempFilterIndex;

	// first off, set up the event handlers and the styles for the filter icons
	// then reapply them if the filtered products are in the category
	for (var i=0;i<filtersList.length;i++) {
		tempFilterIndex = filtersList[i];
		stripActions(tempFilterIndex);
		$(tempFilterIndex+"filter").className = "filter" + filtersListState[tempFilterIndex]; 
		if ((filtersListState[tempFilterIndex] == "On") || (filtersListState[tempFilterIndex] == "Off")) { appendActions(tempFilterIndex); } 
	}

}

function stripActions(filterIndex) {
	$(filterIndex+"filter").stopObserving('click');
}

function appendActions(filterIndex) {
	Event.observe(filterIndex + "filter", "click", function() { selectFilter(filterIndex); });
}

function applyProductFades() {

	var visible;	
	var selectFilter;	
	var tempIndex;
	var products = $('productlist').select('li.productlistitem');
	var tagVals;
 	var filterIndex;
	
	// getProductsInCategory();

 	for (var j=0;j<productIDs.length;j++) {
 	
		tempIndex = productIDs[j];		
		
		if (productStates[tempIndex] == 1) {
			// if the product is not already greyed out do so now
			productStates[tempIndex] = 0;
			// then check if there's a match. If there is - update it's opacity
			for (var i=0;i<filtersList.length;i++) {
				filterIndex = filtersList[i];
				tagVals = $(tempIndex + "_tags").value;
				if (tagVals.match(filterIndex.substring(0,1))) {
					if (filtersListState[filterIndex] == "On")  productStates[tempIndex] = 1;
					// productStates[tempIndex] = 1;
				}
			}	
		}
	
		if (productStates[tempIndex] != 1) {
			$(tempIndex).style.display = 'none';
		} else {
			$(tempIndex).style.display = 'block';
		}
		
		
	}
	
}

function selectFilter(filterIndex) {


	var activeCount = 0;
	var currentState = (filtersListState[filterIndex]);
	var oldTitle = $(filterIndex+"filter").title;
	
	getProductsInCategory() ;
	
	if (currentState == "On") {
	
		for (var i=0;i<filtersList.length;i++) {
			var tempIndex = filtersList[i];
			activeCount += (filtersListState[tempIndex] == "On") ? 1 : 0;		
		}
		
		if (activeCount > 1) {
			filtersListState[filterIndex] = "Off";
			$(filterIndex+"filter").title = str_replace('Remove','Add',oldTitle);
		}
		
	}
	
	if (currentState == "Off") {
		filtersListState[filterIndex] = "On";
		$(filterIndex+"filter").title = str_replace('Add','Remove',oldTitle);
	}
	
	$(filterIndex+"filter").className = "filter" + filtersListState[filterIndex]; 
	
	applyProductFades();
	
}


function writeReview() {
	if($("writeReview").offsetHeight == 0) Effect.BlindDown("writeReview");
	else Effect.BlindUp("writeReview");
}

function buyNow(productID) {
	//submitDoc("addtobasket");
	new Ajax.Request('/ajaxShoppingCart.php', { method: 'post', parameters: $('prod'+productID).serialize(), onComplete: function(basket){ updateBasket(basket, true) }} );
	//openLink("/?_g=co&_a=cart");
}

function addtoBasket(productID) {
	new Ajax.Updater('shoppingCart', '/ajaxShoppingCart.php', { method: 'post', parameters: $('prod'+productID).serialize(), onComplete: function(basket){ updateBasket(basket, false) }} );
}

function updateCircleGraphic(productID) {

		//if nexus, also display nexus logo
		//productTags = $("product"+productID+"_tags").value;
		//if(productTags.match('n')) $("nexuslogo").className = "logo";
		
		//switching circle graphics
		productCGTags = $("product"+productID+"_cgtags").value;
		fireCGvalues(productCGTags);
	
}

function revertCircleGraphic() {
	$("nexuslogo").className = "";
	fireCGvalues("");
}

function updateBasket(basket, forwardToCheckout) {
	var responseItems = basket.responseText.match(/<span class="txtCartPrice">(.*)<\/span>Items in cart/);
	
	$("cartItemsNo").innerHTML = parseInt(responseItems[1]);
	Effect.Pulsate('umCart', { pulses: 3, duration: 3, from: 0.37 });
	
	if(forwardToCheckout) openLink("/index.php?_g=co&_a=cart");
	else return true;
} 

function submitReview() {
	
	new Ajax.Request('/ajaxReview.php', { method: 'post', parameters: $('write_review').serialize(), onComplete: function(review){ reviewSubmitted(review) }} );
}

function reviewSubmitted(review) {	
	if(Prototype.Browser.IE) {
		var newdiv = document.createElement("div");
		newdiv.innerHTML = review.responseText;
		var container = document.getElementById("write_review");
		$("write_review").innerHTML = '';
		container.appendChild(newdiv);
	}
	else $("write_review").innerHTML = review.responseText;
	$("writeReview").style.height = $("write_review").offsetHeight+"px";
	//if(!review.responseText.match(/<p class="txtError">(.*)<\/p>/)) writeReview();
}

function showReviews() {
	if($("reviews_wrapper").offsetHeight == 0) Effect.BlindDown("reviews_wrapper");
	else Effect.BlindUp("reviews_wrapper");
}

function paginate(page) {
	new Ajax.Request('/ajaxReview.php', { method: 'get', parameters: { 'page': page, 'getReviews': 'true', 'productId': $("productID").value }, onComplete: function(reviews){ adjustReviewsHeight(reviews) }} );
}

function adjustReviewsHeight(reviews) {
	$("reviews").innerHTML = reviews.responseText; 
	var innerHeight = $("reviews").offsetHeight+35;
	$('reviews_wrapper').morph('height:'+innerHeight+'px;');
}
